From 2f19f0fd702fef22dd9d694c82b88aaff35b4757 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonne=20Ha=C3=9F?= Date: Wed, 10 Apr 2024 22:05:54 +0200 Subject: [PATCH] restore community edition --- .github/workflows/release-tracker.yml | 42 - .github/workflows/release.yml | 15 +- .github/workflows/update-docs.yml | 53 - go.mod | 3 - go.sum | 8 - hack/build.sh | 12 - main.go | 1 - pkg/cmds/server/options.go | 21 - pkg/cmds/server/start.go | 5 - pkg/controller/backup_configuration.go | 3 - pkg/controller/backup_session.go | 39 +- pkg/controller/config.go | 42 - pkg/controller/controller.go | 2 - pkg/controller/repository.go | 3 - pkg/controller/restore_session.go | 37 +- pkg/server/server.go | 4 - .../github.com/PuerkitoBio/purell/.gitignore | 5 - vendor/github.com/PuerkitoBio/purell/LICENSE | 13 - .../github.com/PuerkitoBio/purell/README.md | 188 - .../github.com/PuerkitoBio/purell/purell.go | 380 - .../github.com/PuerkitoBio/purell/urlesc.go | 174 - .../github.com/cloudevents/sdk-go/v2/LICENSE | 201 - .../github.com/cloudevents/sdk-go/v2/alias.go | 187 - .../sdk-go/v2/binding/binary_writer.go | 52 - .../cloudevents/sdk-go/v2/binding/doc.go | 66 - .../cloudevents/sdk-go/v2/binding/encoding.go | 50 - .../sdk-go/v2/binding/event_message.go | 110 - .../sdk-go/v2/binding/finish_message.go | 42 - .../sdk-go/v2/binding/format/doc.go | 12 - .../sdk-go/v2/binding/format/format.go | 105 - .../cloudevents/sdk-go/v2/binding/message.go | 153 - .../sdk-go/v2/binding/spec/attributes.go | 141 - .../cloudevents/sdk-go/v2/binding/spec/doc.go | 12 - .../v2/binding/spec/match_exact_version.go | 81 - .../sdk-go/v2/binding/spec/spec.go | 189 - .../sdk-go/v2/binding/structured_writer.go | 22 - .../cloudevents/sdk-go/v2/binding/to_event.go | 153 - .../sdk-go/v2/binding/transformer.go | 42 - .../cloudevents/sdk-go/v2/binding/write.go | 179 - .../cloudevents/sdk-go/v2/client/client.go | 295 - .../sdk-go/v2/client/client_http.go | 35 - .../sdk-go/v2/client/client_observed.go | 12 - .../sdk-go/v2/client/defaulters.go | 57 - .../cloudevents/sdk-go/v2/client/doc.go | 11 - .../sdk-go/v2/client/http_receiver.go | 45 - .../cloudevents/sdk-go/v2/client/invoker.go | 145 - .../sdk-go/v2/client/observability.go | 54 - .../cloudevents/sdk-go/v2/client/options.go | 141 - .../cloudevents/sdk-go/v2/client/receiver.go | 193 - .../cloudevents/sdk-go/v2/context/context.go | 110 - .../sdk-go/v2/context/delegating.go | 25 - .../cloudevents/sdk-go/v2/context/doc.go | 10 - .../cloudevents/sdk-go/v2/context/logger.go | 48 - .../cloudevents/sdk-go/v2/context/retry.go | 76 - .../sdk-go/v2/event/content_type.go | 47 - .../sdk-go/v2/event/data_content_encoding.go | 16 - .../sdk-go/v2/event/datacodec/codec.go | 78 - .../sdk-go/v2/event/datacodec/doc.go | 10 - .../sdk-go/v2/event/datacodec/json/data.go | 56 - .../sdk-go/v2/event/datacodec/json/doc.go | 9 - .../sdk-go/v2/event/datacodec/text/data.go | 30 - .../sdk-go/v2/event/datacodec/text/doc.go | 9 - .../sdk-go/v2/event/datacodec/xml/data.go | 40 - .../sdk-go/v2/event/datacodec/xml/doc.go | 9 - .../cloudevents/sdk-go/v2/event/doc.go | 9 - .../cloudevents/sdk-go/v2/event/event.go | 125 - .../cloudevents/sdk-go/v2/event/event_data.go | 118 - .../sdk-go/v2/event/event_interface.go | 102 - .../sdk-go/v2/event/event_marshal.go | 203 - .../sdk-go/v2/event/event_reader.go | 103 - .../sdk-go/v2/event/event_unmarshal.go | 480 - .../sdk-go/v2/event/event_validation.go | 50 - .../sdk-go/v2/event/event_writer.go | 117 - .../sdk-go/v2/event/eventcontext.go | 125 - .../sdk-go/v2/event/eventcontext_v03.go | 330 - .../v2/event/eventcontext_v03_reader.go | 99 - .../v2/event/eventcontext_v03_writer.go | 103 - .../sdk-go/v2/event/eventcontext_v1.go | 315 - .../sdk-go/v2/event/eventcontext_v1_reader.go | 104 - .../sdk-go/v2/event/eventcontext_v1_writer.go | 97 - .../cloudevents/sdk-go/v2/event/extensions.go | 57 - .../cloudevents/sdk-go/v2/protocol/doc.go | 25 - .../cloudevents/sdk-go/v2/protocol/error.go | 42 - .../v2/protocol/http/abuse_protection.go | 128 - .../sdk-go/v2/protocol/http/context.go | 48 - .../sdk-go/v2/protocol/http/doc.go | 9 - .../sdk-go/v2/protocol/http/headers.go | 55 - .../sdk-go/v2/protocol/http/message.go | 175 - .../sdk-go/v2/protocol/http/options.go | 300 - .../sdk-go/v2/protocol/http/protocol.go | 411 - .../v2/protocol/http/protocol_lifecycle.go | 143 - .../sdk-go/v2/protocol/http/protocol_rate.go | 34 - .../sdk-go/v2/protocol/http/protocol_retry.go | 126 - .../sdk-go/v2/protocol/http/result.go | 60 - .../sdk-go/v2/protocol/http/retries_result.go | 59 - .../sdk-go/v2/protocol/http/utility.go | 89 - .../sdk-go/v2/protocol/http/write_request.go | 142 - .../v2/protocol/http/write_responsewriter.go | 126 - .../cloudevents/sdk-go/v2/protocol/inbound.go | 54 - .../sdk-go/v2/protocol/lifecycle.go | 23 - .../sdk-go/v2/protocol/outbound.go | 49 - .../cloudevents/sdk-go/v2/protocol/result.go | 127 - .../cloudevents/sdk-go/v2/staticcheck.conf | 3 - .../cloudevents/sdk-go/v2/types/allocate.go | 41 - .../cloudevents/sdk-go/v2/types/doc.go | 45 - .../cloudevents/sdk-go/v2/types/timestamp.go | 75 - .../cloudevents/sdk-go/v2/types/uri.go | 86 - .../cloudevents/sdk-go/v2/types/uriref.go | 82 - .../cloudevents/sdk-go/v2/types/value.go | 337 - .../stargz-snapshotter/estargz/LICENSE | 202 - .../stargz-snapshotter/estargz/build.go | 690 - .../estargz/errorutil/errors.go | 40 - .../stargz-snapshotter/estargz/estargz.go | 1223 - .../stargz-snapshotter/estargz/gzip.go | 237 - .../stargz-snapshotter/estargz/testutil.go | 2366 -- .../stargz-snapshotter/estargz/types.go | 342 - vendor/github.com/docker/cli/AUTHORS | 852 - vendor/github.com/docker/cli/LICENSE | 191 - vendor/github.com/docker/cli/NOTICE | 19 - .../docker/cli/cli/config/config.go | 153 - .../docker/cli/cli/config/configfile/file.go | 352 - .../cli/cli/config/configfile/file_unix.go | 36 - .../cli/cli/config/configfile/file_windows.go | 5 - .../cli/cli/config/credentials/credentials.go | 17 - .../cli/config/credentials/default_store.go | 21 - .../credentials/default_store_darwin.go | 5 - .../config/credentials/default_store_linux.go | 13 - .../credentials/default_store_unsupported.go | 8 - .../credentials/default_store_windows.go | 5 - .../cli/cli/config/credentials/file_store.go | 81 - .../cli/config/credentials/native_store.go | 147 - .../docker/cli/cli/config/types/authconfig.go | 22 - vendor/github.com/docker/distribution/LICENSE | 202 - .../registry/client/auth/challenge/addr.go | 27 - .../client/auth/challenge/authchallenge.go | 237 - .../docker/docker-credential-helpers/LICENSE | 20 - .../client/client.go | 121 - .../client/command.go | 57 - .../credentials/credentials.go | 186 - .../credentials/error.go | 102 - .../credentials/helper.go | 14 - .../credentials/version.go | 16 - vendor/github.com/docker/docker/AUTHORS | 2390 -- vendor/github.com/docker/docker/LICENSE | 191 - vendor/github.com/docker/docker/NOTICE | 19 - .../docker/pkg/homedir/homedir_linux.go | 105 - .../docker/pkg/homedir/homedir_others.go | 33 - .../docker/docker/pkg/homedir/homedir_unix.go | 39 - .../docker/pkg/homedir/homedir_windows.go | 24 - .../google/go-containerregistry/LICENSE | 202 - .../internal/and/and_closer.go | 48 - .../internal/compression/compression.go | 97 - .../internal/estargz/estargz.go | 54 - .../go-containerregistry/internal/gzip/zip.go | 118 - .../internal/redact/redact.go | 89 - .../internal/retry/retry.go | 94 - .../wait/kubernetes_apimachinery_wait.go | 123 - .../internal/verify/verify.go | 122 - .../internal/windows/windows.go | 114 - .../internal/zstd/zstd.go | 116 - .../go-containerregistry/pkg/authn/README.md | 322 - .../go-containerregistry/pkg/authn/anon.go | 26 - .../go-containerregistry/pkg/authn/auth.go | 30 - .../go-containerregistry/pkg/authn/authn.go | 115 - .../go-containerregistry/pkg/authn/basic.go | 29 - .../go-containerregistry/pkg/authn/bearer.go | 27 - .../go-containerregistry/pkg/authn/doc.go | 17 - .../pkg/authn/keychain.go | 249 - .../pkg/authn/multikeychain.go | 41 - .../pkg/compression/compression.go | 26 - .../go-containerregistry/pkg/crane/append.go | 114 - .../go-containerregistry/pkg/crane/catalog.go | 35 - .../go-containerregistry/pkg/crane/config.go | 24 - .../go-containerregistry/pkg/crane/copy.go | 181 - .../go-containerregistry/pkg/crane/delete.go | 33 - .../go-containerregistry/pkg/crane/digest.go | 52 - .../go-containerregistry/pkg/crane/doc.go | 16 - .../go-containerregistry/pkg/crane/export.go | 54 - .../go-containerregistry/pkg/crane/filemap.go | 72 - .../go-containerregistry/pkg/crane/get.go | 61 - .../go-containerregistry/pkg/crane/list.go | 33 - .../pkg/crane/manifest.go | 32 - .../go-containerregistry/pkg/crane/options.go | 178 - .../go-containerregistry/pkg/crane/pull.go | 142 - .../go-containerregistry/pkg/crane/push.go | 65 - .../go-containerregistry/pkg/crane/tag.go | 39 - .../go-containerregistry/pkg/legacy/config.go | 33 - .../go-containerregistry/pkg/legacy/doc.go | 18 - .../pkg/legacy/tarball/README.md | 6 - .../pkg/legacy/tarball/doc.go | 18 - .../pkg/legacy/tarball/write.go | 371 - .../go-containerregistry/pkg/logs/logs.go | 39 - .../go-containerregistry/pkg/name/README.md | 3 - .../go-containerregistry/pkg/name/check.go | 43 - .../go-containerregistry/pkg/name/digest.go | 94 - .../go-containerregistry/pkg/name/doc.go | 42 - .../go-containerregistry/pkg/name/errors.go | 48 - .../go-containerregistry/pkg/name/options.go | 83 - .../go-containerregistry/pkg/name/ref.go | 75 - .../go-containerregistry/pkg/name/registry.go | 142 - .../pkg/name/repository.go | 121 - .../go-containerregistry/pkg/name/tag.go | 108 - .../go-containerregistry/pkg/v1/config.go | 151 - .../google/go-containerregistry/pkg/v1/doc.go | 18 - .../pkg/v1/empty/README.md | 8 - .../go-containerregistry/pkg/v1/empty/doc.go | 16 - .../pkg/v1/empty/image.go | 52 - .../pkg/v1/empty/index.go | 65 - .../go-containerregistry/pkg/v1/hash.go | 123 - .../go-containerregistry/pkg/v1/image.go | 59 - .../go-containerregistry/pkg/v1/index.go | 43 - .../go-containerregistry/pkg/v1/layer.go | 42 - .../pkg/v1/layout/README.md | 5 - .../pkg/v1/layout/blob.go | 37 - .../go-containerregistry/pkg/v1/layout/doc.go | 19 - .../go-containerregistry/pkg/v1/layout/gc.go | 137 - .../pkg/v1/layout/image.go | 139 - .../pkg/v1/layout/index.go | 161 - .../pkg/v1/layout/layoutpath.go | 25 - .../pkg/v1/layout/options.go | 71 - .../pkg/v1/layout/read.go | 32 - .../pkg/v1/layout/write.go | 482 - .../go-containerregistry/pkg/v1/manifest.go | 71 - .../pkg/v1/match/match.go | 92 - .../pkg/v1/mutate/README.md | 56 - .../go-containerregistry/pkg/v1/mutate/doc.go | 16 - .../pkg/v1/mutate/image.go | 293 - .../pkg/v1/mutate/index.go | 232 - .../pkg/v1/mutate/mutate.go | 555 - .../pkg/v1/mutate/rebase.go | 144 - .../pkg/v1/partial/README.md | 82 - .../pkg/v1/partial/compressed.go | 188 - .../pkg/v1/partial/doc.go | 17 - .../pkg/v1/partial/image.go | 28 - .../pkg/v1/partial/index.go | 165 - .../pkg/v1/partial/uncompressed.go | 223 - .../pkg/v1/partial/with.go | 436 - .../go-containerregistry/pkg/v1/platform.go | 149 - .../go-containerregistry/pkg/v1/progress.go | 25 - .../pkg/v1/remote/README.md | 117 - .../pkg/v1/remote/catalog.go | 159 - .../pkg/v1/remote/check.go | 72 - .../pkg/v1/remote/delete.go | 28 - .../pkg/v1/remote/descriptor.go | 198 - .../go-containerregistry/pkg/v1/remote/doc.go | 17 - .../pkg/v1/remote/fetcher.go | 317 - .../pkg/v1/remote/image.go | 277 - .../pkg/v1/remote/index.go | 287 - .../pkg/v1/remote/layer.go | 77 - .../pkg/v1/remote/list.go | 152 - .../pkg/v1/remote/mount.go | 108 - .../pkg/v1/remote/multi_write.go | 46 - .../pkg/v1/remote/options.go | 349 - .../pkg/v1/remote/progress.go | 76 - .../pkg/v1/remote/puller.go | 222 - .../pkg/v1/remote/pusher.go | 559 - .../pkg/v1/remote/referrers.go | 117 - .../pkg/v1/remote/schema1.go | 118 - .../pkg/v1/remote/transport/README.md | 129 - .../pkg/v1/remote/transport/basic.go | 62 - .../pkg/v1/remote/transport/bearer.go | 391 - .../pkg/v1/remote/transport/doc.go | 18 - .../pkg/v1/remote/transport/error.go | 196 - .../pkg/v1/remote/transport/logger.go | 91 - .../pkg/v1/remote/transport/ping.go | 217 - .../pkg/v1/remote/transport/retry.go | 111 - .../pkg/v1/remote/transport/schemer.go | 44 - .../pkg/v1/remote/transport/scope.go | 24 - .../pkg/v1/remote/transport/transport.go | 109 - .../pkg/v1/remote/transport/useragent.go | 94 - .../pkg/v1/remote/write.go | 713 - .../pkg/v1/stream/README.md | 68 - .../pkg/v1/stream/layer.go | 275 - .../pkg/v1/tarball/README.md | 280 - .../pkg/v1/tarball/doc.go | 17 - .../pkg/v1/tarball/image.go | 440 - .../pkg/v1/tarball/layer.go | 354 - .../pkg/v1/tarball/write.go | 457 - .../pkg/v1/types/types.go | 98 - .../pkg/v1/zz_deepcopy_generated.go | 339 - .../jonboulle/clockwork/.editorconfig | 12 - .../github.com/jonboulle/clockwork/.gitignore | 27 - vendor/github.com/jonboulle/clockwork/LICENSE | 201 - .../github.com/jonboulle/clockwork/README.md | 80 - .../jonboulle/clockwork/clockwork.go | 349 - .../github.com/jonboulle/clockwork/context.go | 25 - .../github.com/jonboulle/clockwork/ticker.go | 48 - .../github.com/jonboulle/clockwork/timer.go | 53 - .../klauspost/compress/.gitattributes | 2 - .../github.com/klauspost/compress/.gitignore | 32 - .../klauspost/compress/.goreleaser.yml | 127 - vendor/github.com/klauspost/compress/LICENSE | 304 - .../github.com/klauspost/compress/README.md | 661 - .../github.com/klauspost/compress/SECURITY.md | 25 - .../klauspost/compress/compressible.go | 85 - .../klauspost/compress/flate/deflate.go | 1017 - .../klauspost/compress/flate/dict_decoder.go | 184 - .../klauspost/compress/flate/fast_encoder.go | 193 - .../compress/flate/huffman_bit_writer.go | 1182 - .../klauspost/compress/flate/huffman_code.go | 417 - .../compress/flate/huffman_sortByFreq.go | 159 - .../compress/flate/huffman_sortByLiteral.go | 201 - .../klauspost/compress/flate/inflate.go | 829 - .../klauspost/compress/flate/inflate_gen.go | 1283 -- .../klauspost/compress/flate/level1.go | 241 - .../klauspost/compress/flate/level2.go | 214 - .../klauspost/compress/flate/level3.go | 241 - .../klauspost/compress/flate/level4.go | 221 - .../klauspost/compress/flate/level5.go | 708 - .../klauspost/compress/flate/level6.go | 325 - .../compress/flate/matchlen_amd64.go | 16 - .../klauspost/compress/flate/matchlen_amd64.s | 68 - .../compress/flate/matchlen_generic.go | 33 - .../klauspost/compress/flate/regmask_amd64.go | 37 - .../klauspost/compress/flate/regmask_other.go | 40 - .../klauspost/compress/flate/stateless.go | 318 - .../klauspost/compress/flate/token.go | 379 - .../klauspost/compress/fse/README.md | 79 - .../klauspost/compress/fse/bitreader.go | 122 - .../klauspost/compress/fse/bitwriter.go | 167 - .../klauspost/compress/fse/bytereader.go | 47 - .../klauspost/compress/fse/compress.go | 683 - .../klauspost/compress/fse/decompress.go | 376 - .../github.com/klauspost/compress/fse/fse.go | 144 - vendor/github.com/klauspost/compress/gen.sh | 4 - .../klauspost/compress/huff0/.gitignore | 1 - .../klauspost/compress/huff0/README.md | 89 - .../klauspost/compress/huff0/bitreader.go | 229 - .../klauspost/compress/huff0/bitwriter.go | 102 - .../klauspost/compress/huff0/bytereader.go | 44 - .../klauspost/compress/huff0/compress.go | 741 - .../klauspost/compress/huff0/decompress.go | 1167 - .../compress/huff0/decompress_amd64.go | 226 - .../compress/huff0/decompress_amd64.s | 830 - .../compress/huff0/decompress_generic.go | 299 - .../klauspost/compress/huff0/huff0.go | 337 - .../compress/internal/cpuinfo/cpuinfo.go | 34 - .../internal/cpuinfo/cpuinfo_amd64.go | 11 - .../compress/internal/cpuinfo/cpuinfo_amd64.s | 36 - .../compress/internal/snapref/LICENSE | 27 - .../compress/internal/snapref/decode.go | 264 - .../compress/internal/snapref/decode_other.go | 113 - .../compress/internal/snapref/encode.go | 289 - .../compress/internal/snapref/encode_other.go | 250 - .../compress/internal/snapref/snappy.go | 98 - vendor/github.com/klauspost/compress/s2sx.mod | 4 - vendor/github.com/klauspost/compress/s2sx.sum | 0 .../klauspost/compress/zstd/README.md | 441 - .../klauspost/compress/zstd/bitreader.go | 136 - .../klauspost/compress/zstd/bitwriter.go | 112 - .../klauspost/compress/zstd/blockdec.go | 726 - .../klauspost/compress/zstd/blockenc.go | 889 - .../compress/zstd/blocktype_string.go | 85 - .../klauspost/compress/zstd/bytebuf.go | 131 - .../klauspost/compress/zstd/bytereader.go | 82 - .../klauspost/compress/zstd/decodeheader.go | 229 - .../klauspost/compress/zstd/decoder.go | 948 - .../compress/zstd/decoder_options.go | 169 - .../klauspost/compress/zstd/dict.go | 534 - .../klauspost/compress/zstd/enc_base.go | 173 - .../klauspost/compress/zstd/enc_best.go | 531 - .../klauspost/compress/zstd/enc_better.go | 1242 - .../klauspost/compress/zstd/enc_dfast.go | 1123 - .../klauspost/compress/zstd/enc_fast.go | 891 - .../klauspost/compress/zstd/encoder.go | 619 - .../compress/zstd/encoder_options.go | 339 - .../klauspost/compress/zstd/framedec.go | 413 - .../klauspost/compress/zstd/frameenc.go | 137 - .../klauspost/compress/zstd/fse_decoder.go | 307 - .../compress/zstd/fse_decoder_amd64.go | 65 - .../compress/zstd/fse_decoder_amd64.s | 126 - .../compress/zstd/fse_decoder_generic.go | 72 - .../klauspost/compress/zstd/fse_encoder.go | 701 - .../klauspost/compress/zstd/fse_predefined.go | 158 - .../klauspost/compress/zstd/hash.go | 35 - .../klauspost/compress/zstd/history.go | 116 - .../compress/zstd/internal/xxhash/LICENSE.txt | 22 - .../compress/zstd/internal/xxhash/README.md | 71 - .../compress/zstd/internal/xxhash/xxhash.go | 230 - .../zstd/internal/xxhash/xxhash_amd64.s | 210 - .../zstd/internal/xxhash/xxhash_arm64.s | 184 - .../zstd/internal/xxhash/xxhash_asm.go | 16 - .../zstd/internal/xxhash/xxhash_other.go | 76 - .../zstd/internal/xxhash/xxhash_safe.go | 11 - .../klauspost/compress/zstd/matchlen_amd64.go | 16 - .../klauspost/compress/zstd/matchlen_amd64.s | 68 - .../compress/zstd/matchlen_generic.go | 33 - .../klauspost/compress/zstd/seqdec.go | 503 - .../klauspost/compress/zstd/seqdec_amd64.go | 394 - .../klauspost/compress/zstd/seqdec_amd64.s | 4175 ---- .../klauspost/compress/zstd/seqdec_generic.go | 237 - .../klauspost/compress/zstd/seqenc.go | 114 - .../klauspost/compress/zstd/snappy.go | 434 - .../github.com/klauspost/compress/zstd/zip.go | 141 - .../klauspost/compress/zstd/zstd.go | 121 - .../github.com/mitchellh/go-homedir/LICENSE | 21 - .../github.com/mitchellh/go-homedir/README.md | 14 - .../mitchellh/go-homedir/homedir.go | 167 - vendor/github.com/nats-io/nats.go/.gitignore | 45 - .../github.com/nats-io/nats.go/.golangci.yaml | 16 - vendor/github.com/nats-io/nats.go/.travis.yml | 36 - vendor/github.com/nats-io/nats.go/.words | 106 - .../github.com/nats-io/nats.go/.words.readme | 25 - .../nats-io/nats.go/CODE-OF-CONDUCT.md | 3 - .../nats-io/nats.go/CONTRIBUTING.md | 45 - .../github.com/nats-io/nats.go/GOVERNANCE.md | 3 - vendor/github.com/nats-io/nats.go/LICENSE | 201 - .../github.com/nats-io/nats.go/MAINTAINERS.md | 8 - vendor/github.com/nats-io/nats.go/README.md | 482 - vendor/github.com/nats-io/nats.go/context.go | 244 - .../nats-io/nats.go/dependencies.md | 15 - vendor/github.com/nats-io/nats.go/enc.go | 269 - .../nats.go/encoders/builtin/default_enc.go | 117 - .../nats.go/encoders/builtin/gob_enc.go | 45 - .../nats.go/encoders/builtin/json_enc.go | 56 - vendor/github.com/nats-io/nats.go/go_test.mod | 22 - vendor/github.com/nats-io/nats.go/go_test.sum | 47 - .../nats-io/nats.go/internal/parser/parse.go | 104 - vendor/github.com/nats-io/nats.go/js.go | 3848 ---- vendor/github.com/nats-io/nats.go/jserrors.go | 235 - vendor/github.com/nats-io/nats.go/jsm.go | 1675 -- vendor/github.com/nats-io/nats.go/kv.go | 1178 - .../nats-io/nats.go/legacy_jetstream.md | 83 - vendor/github.com/nats-io/nats.go/nats.go | 5694 ----- vendor/github.com/nats-io/nats.go/netchan.go | 111 - vendor/github.com/nats-io/nats.go/object.go | 1422 -- vendor/github.com/nats-io/nats.go/parser.go | 554 - vendor/github.com/nats-io/nats.go/rand.go | 29 - .../nats-io/nats.go/testing_internal.go | 59 - vendor/github.com/nats-io/nats.go/timer.go | 56 - vendor/github.com/nats-io/nats.go/util/tls.go | 28 - .../nats-io/nats.go/util/tls_go17.go | 50 - vendor/github.com/nats-io/nats.go/ws.go | 780 - vendor/github.com/nats-io/nkeys/.gitignore | 16 - .../github.com/nats-io/nkeys/.goreleaser.yml | 63 - vendor/github.com/nats-io/nkeys/GOVERNANCE.md | 3 - vendor/github.com/nats-io/nkeys/LICENSE | 201 - .../github.com/nats-io/nkeys/MAINTAINERS.md | 8 - vendor/github.com/nats-io/nkeys/README.md | 68 - vendor/github.com/nats-io/nkeys/TODO.md | 5 - vendor/github.com/nats-io/nkeys/crc16.go | 68 - .../github.com/nats-io/nkeys/creds_utils.go | 78 - .../github.com/nats-io/nkeys/dependencies.md | 12 - vendor/github.com/nats-io/nkeys/errors.go | 50 - vendor/github.com/nats-io/nkeys/keypair.go | 146 - vendor/github.com/nats-io/nkeys/nkeys.go | 100 - vendor/github.com/nats-io/nkeys/public.go | 86 - vendor/github.com/nats-io/nkeys/strkey.go | 314 - vendor/github.com/nats-io/nkeys/xkeys.go | 185 - vendor/github.com/nats-io/nuid/.gitignore | 24 - vendor/github.com/nats-io/nuid/.travis.yml | 17 - vendor/github.com/nats-io/nuid/GOVERNANCE.md | 3 - vendor/github.com/nats-io/nuid/LICENSE | 201 - vendor/github.com/nats-io/nuid/MAINTAINERS.md | 6 - vendor/github.com/nats-io/nuid/README.md | 47 - vendor/github.com/nats-io/nuid/nuid.go | 135 - .../opencontainers/image-spec/LICENSE | 191 - .../image-spec/specs-go/v1/annotations.go | 68 - .../image-spec/specs-go/v1/config.go | 111 - .../image-spec/specs-go/v1/descriptor.go | 72 - .../image-spec/specs-go/v1/index.go | 32 - .../image-spec/specs-go/v1/layout.go | 28 - .../image-spec/specs-go/v1/manifest.go | 49 - .../image-spec/specs-go/v1/mediatype.go | 75 - .../image-spec/specs-go/version.go | 32 - .../image-spec/specs-go/versioned.go | 23 - vendor/github.com/sirupsen/logrus/.gitignore | 4 - .../github.com/sirupsen/logrus/.golangci.yml | 40 - vendor/github.com/sirupsen/logrus/.travis.yml | 15 - .../github.com/sirupsen/logrus/CHANGELOG.md | 259 - vendor/github.com/sirupsen/logrus/LICENSE | 21 - vendor/github.com/sirupsen/logrus/README.md | 515 - vendor/github.com/sirupsen/logrus/alt_exit.go | 76 - .../github.com/sirupsen/logrus/appveyor.yml | 14 - .../github.com/sirupsen/logrus/buffer_pool.go | 43 - vendor/github.com/sirupsen/logrus/doc.go | 26 - vendor/github.com/sirupsen/logrus/entry.go | 442 - vendor/github.com/sirupsen/logrus/exported.go | 270 - .../github.com/sirupsen/logrus/formatter.go | 78 - vendor/github.com/sirupsen/logrus/hooks.go | 34 - .../sirupsen/logrus/json_formatter.go | 128 - vendor/github.com/sirupsen/logrus/logger.go | 417 - vendor/github.com/sirupsen/logrus/logrus.go | 186 - .../logrus/terminal_check_appengine.go | 11 - .../sirupsen/logrus/terminal_check_bsd.go | 13 - .../sirupsen/logrus/terminal_check_js.go | 7 - .../logrus/terminal_check_no_terminal.go | 11 - .../logrus/terminal_check_notappengine.go | 17 - .../sirupsen/logrus/terminal_check_solaris.go | 11 - .../sirupsen/logrus/terminal_check_unix.go | 13 - .../sirupsen/logrus/terminal_check_windows.go | 27 - .../sirupsen/logrus/text_formatter.go | 339 - vendor/github.com/sirupsen/logrus/writer.go | 102 - vendor/github.com/vbatts/tar-split/LICENSE | 28 - .../vbatts/tar-split/archive/tar/common.go | 723 - .../vbatts/tar-split/archive/tar/format.go | 303 - .../vbatts/tar-split/archive/tar/reader.go | 925 - .../tar-split/archive/tar/stat_actime1.go | 20 - .../tar-split/archive/tar/stat_actime2.go | 20 - .../vbatts/tar-split/archive/tar/stat_unix.go | 96 - .../vbatts/tar-split/archive/tar/strconv.go | 326 - .../vbatts/tar-split/archive/tar/writer.go | 653 - vendor/go.bytebuilders.dev/audit/LICENSE | 201 - .../go.bytebuilders.dev/audit/api/v1/doc.go | 19 - .../go.bytebuilders.dev/audit/api/v1/types.go | 46 - .../audit/api/v1/zz_generated.deepcopy.go | 43 - .../audit/lib/audit_event.go | 40 - .../audit/lib/billing_event.go | 48 - vendor/go.bytebuilders.dev/audit/lib/nats.go | 195 - vendor/go.bytebuilders.dev/audit/lib/node.go | 127 - .../audit/lib/publisher.go | 301 - .../go.bytebuilders.dev/audit/lib/resource.go | 150 - .../license-proxyserver/LICENSE | 202 - .../apis/proxyserver/register.go | 21 - .../apis/proxyserver/v1alpha1/doc.go | 23 - .../v1alpha1/license_request_types.go | 51 - .../v1alpha1/license_status_types.go | 101 - .../proxyserver/v1alpha1/openapi_generated.go | 18682 ---------------- .../apis/proxyserver/v1alpha1/register.go | 62 - .../v1alpha1/zz_generated.deepcopy.go | 265 - .../client/clientset/versioned/clientset.go | 120 - .../client/clientset/versioned/scheme/doc.go | 20 - .../clientset/versioned/scheme/register.go | 56 - .../typed/proxyserver/v1alpha1/doc.go | 20 - .../v1alpha1/generated_expansion.go | 23 - .../proxyserver/v1alpha1/licenserequest.go | 64 - .../proxyserver/v1alpha1/licensestatus.go | 82 - .../v1alpha1/proxyserver_client.go | 112 - .../license-verifier/.gitignore | 19 - .../license-verifier/LICENSE | 201 - .../license-verifier/Makefile | 279 - .../license-verifier/README.md | 4 - .../apis/licenses/register.go | 20 - .../apis/licenses/v1alpha1/doc.go | 25 - .../apis/licenses/v1alpha1/helper.go | 62 - .../apis/licenses/v1alpha1/register.go | 60 - .../apis/licenses/v1alpha1/types.go | 64 - .../v1alpha1/zz_generated.deepcopy.go | 120 - .../license-verifier/info/lib.go | 192 - .../license-verifier/kubernetes/.gitignore | 37 - .../license-verifier/kubernetes/LICENSE | 201 - .../license-verifier/kubernetes/Makefile | 279 - .../license-verifier/kubernetes/lib.go | 412 - .../license-verifier/lib.go | 214 - vendor/golang.org/x/crypto/blake2b/blake2b.go | 291 - .../x/crypto/blake2b/blake2bAVX2_amd64.go | 37 - .../x/crypto/blake2b/blake2bAVX2_amd64.s | 744 - .../x/crypto/blake2b/blake2b_amd64.s | 278 - .../x/crypto/blake2b/blake2b_generic.go | 182 - .../x/crypto/blake2b/blake2b_ref.go | 11 - vendor/golang.org/x/crypto/blake2b/blake2x.go | 177 - .../golang.org/x/crypto/blake2b/register.go | 30 - .../x/crypto/curve25519/curve25519.go | 59 - .../x/crypto/curve25519/curve25519_compat.go | 105 - .../x/crypto/curve25519/curve25519_go120.go | 46 - .../x/crypto/curve25519/internal/field/README | 7 - .../x/crypto/curve25519/internal/field/fe.go | 416 - .../curve25519/internal/field/fe_amd64.go | 15 - .../curve25519/internal/field/fe_amd64.s | 378 - .../internal/field/fe_amd64_noasm.go | 11 - .../curve25519/internal/field/fe_arm64.go | 15 - .../curve25519/internal/field/fe_arm64.s | 42 - .../internal/field/fe_arm64_noasm.go | 11 - .../curve25519/internal/field/fe_generic.go | 264 - .../curve25519/internal/field/sync.checkpoint | 1 - .../crypto/curve25519/internal/field/sync.sh | 19 - vendor/golang.org/x/crypto/ed25519/ed25519.go | 71 - vendor/golang.org/x/crypto/nacl/box/box.go | 182 - vendor/golang.org/x/sys/execabs/execabs.go | 102 - .../golang.org/x/sys/execabs/execabs_go118.go | 17 - .../golang.org/x/sys/execabs/execabs_go119.go | 20 - vendor/gomodules.xyz/counter/LICENSE | 201 - vendor/gomodules.xyz/counter/hourly/int.go | 20 - vendor/gomodules.xyz/counter/hourly/int32.go | 20 - vendor/gomodules.xyz/counter/hourly/int64.go | 20 - vendor/gomodules.xyz/counter/hourly/lib.go | 78 - .../client-go/tools/clusterid/lib.go | 77 - .../custom-resources/util/siteinfo/lib.go | 166 - .../kmodules.xyz/go-containerregistry/LICENSE | 201 - .../go-containerregistry/name/lib.go | 104 - .../kmodules.xyz/offshoot-api/api/v2/doc.go | 20 - .../offshoot-api/api/v2/openapi_generated.go | 452 - .../kmodules.xyz/offshoot-api/api/v2/types.go | 292 - .../api/v2/zz_generated.deepcopy.go | 206 - vendor/kmodules.xyz/resource-metadata/LICENSE | 201 - .../apis/core/v1alpha1/doc.go | 23 - .../core/v1alpha1/generic_resource_helpers.go | 193 - .../generic_resource_service_types.go | 113 - .../generic_resource_summary_types.go | 82 - .../core/v1alpha1/generic_resource_types.go | 92 - .../apis/core/v1alpha1/groupversion_info.go | 35 - .../apis/core/v1alpha1/openapi_generated.go | 17656 --------------- .../apis/core/v1alpha1/podview_types.go | 239 - .../apis/core/v1alpha1/project_types.go | 86 - .../core/v1alpha1/zz_generated.deepcopy.go | 841 - .../resource-metadata/apis/shared/doc.go | 20 - .../resource-metadata/apis/shared/helm.go | 112 - .../resource-metadata/apis/shared/helpers.go | 207 - .../apis/shared/openapi_generated.go | 911 - .../resource-metadata/apis/shared/types.go | 146 - .../apis/shared/zz_generated.deepcopy.go | 540 - .../kmodules.xyz/resource-metrics/.gitignore | 35 - .../resource-metrics/CONTRIBUTING.md | 37 - vendor/kmodules.xyz/resource-metrics/DCO | 36 - vendor/kmodules.xyz/resource-metrics/LICENSE | 201 - vendor/kmodules.xyz/resource-metrics/Makefile | 300 - .../kmodules.xyz/resource-metrics/README.md | 8 - .../resource-metrics/api/constants.go | 35 - .../kmodules.xyz/resource-metrics/api/doc.go | 17 - .../resource-metrics/api/interface.go | 131 - .../resource-metrics/api/plugins.go | 76 - .../resource-metrics/api/utils.go | 381 - .../resource-metrics/apps/v1/daemonset.go | 61 - .../resource-metrics/apps/v1/deployment.go | 77 - .../resource-metrics/apps/v1/replicaset.go | 77 - .../resource-metrics/apps/v1/statefulset.go | 77 - .../resource-metrics/batch/v1/cronjob.go | 61 - .../resource-metrics/batch/v1/job.go | 61 - .../resource-metrics/batch/v1beta1/cronjob.go | 61 - .../resource-metrics/calculator.go | 110 - .../resource-metrics/core/v1/pod.go | 60 - .../resource-metrics/core/v1/pv.go | 41 - .../resource-metrics/core/v1/rc.go | 76 - vendor/kmodules.xyz/resource-metrics/doc.go | 17 - vendor/kmodules.xyz/resource-metrics/eval.go | 116 - .../kubedb.com/v1alpha2/constants.go | 33 - .../kubedb.com/v1alpha2/elasticsearch.go | 180 - .../kubedb.com/v1alpha2/kafka.go | 181 - .../kubedb.com/v1alpha2/mariadb.go | 94 - .../kubedb.com/v1alpha2/memcached.go | 94 - .../kubedb.com/v1alpha2/mongodb.go | 171 - .../kubedb.com/v1alpha2/mysql.go | 132 - .../kubedb.com/v1alpha2/perconaxtradb.go | 94 - .../kubedb.com/v1alpha2/pgbouncer.go | 94 - .../kubedb.com/v1alpha2/postgres.go | 95 - .../kubedb.com/v1alpha2/proxysql.go | 94 - .../kubedb.com/v1alpha2/rabbitmq.go | 94 - .../kubedb.com/v1alpha2/redis.go | 137 - .../kubedb.com/v1alpha2/redissentinel.go | 82 - .../kubedb.com/v1alpha2/singlestore.go | 142 - .../kubedb.com/v1alpha2/zookeeper.go | 94 - .../kubevault.com/v1alpha2/constant.go | 19 - .../kubevault.com/v1alpha2/vaultserver.go | 96 - .../ops.kubedb.com/v1alpha1/calculator.go | 102 - .../ops.kubedb.com/v1alpha1/constansts.go | 27 - .../v1alpha1/elasticsearch_mapping.go | 91 - .../ops.kubedb.com/v1alpha1/kafka_mapping.go | 63 - .../ops.kubedb.com/v1alpha1/mapper.go | 69 - .../v1alpha1/mariadb_mapping.go | 51 - .../v1alpha1/memcached_mapping.go | 51 - .../v1alpha1/mongodb_mapping.go | 76 - .../ops.kubedb.com/v1alpha1/mysql_mapping.go | 59 - .../v1alpha1/pgbouncer_mapping.go | 51 - .../v1alpha1/postgres_mapping.go | 61 - .../v1alpha1/proxysql_mapping.go | 55 - .../ops.kubedb.com/v1alpha1/redis_mapping.go | 60 - .../v1alpha1/redissentinel_mapping.go | 59 - .../ops.kubedb.com/v1alpha1/scale.go | 110 - .../kmodules.xyz/resource-metrics/template.go | 194 - vendor/modules.txt | 117 - vendor/sigs.k8s.io/cli-utils/LICENSE | 201 - vendor/sigs.k8s.io/cli-utils/LICENSE_TEMPLATE | 2 - .../sigs.k8s.io/cli-utils/LICENSE_TEMPLATE_GO | 2 - .../cli-utils/pkg/kstatus/status/core.go | 627 - .../cli-utils/pkg/kstatus/status/doc.go | 43 - .../cli-utils/pkg/kstatus/status/generic.go | 99 - .../cli-utils/pkg/kstatus/status/status.go | 242 - .../cli-utils/pkg/kstatus/status/util.go | 143 - .../releases/v1alpha1/application_types.go | 38 - .../apis/releases/v1alpha1/bundle_helpers.go | 27 - .../apis/releases/v1alpha1/bundle_types.go | 133 - .../apis/releases/v1alpha1/bundle_ui_types.go | 57 - .../apis/releases/v1alpha1/editor_types.go | 159 - .../releases/v1alpha1/groupversion_info.go | 36 - .../apis/releases/v1alpha1/helpers.go | 46 - .../apis/releases/v1alpha1/hub.go | 29 - .../apis/releases/v1alpha1/order_helpers.go | 27 - .../apis/releases/v1alpha1/order_types.go | 90 - .../releases/v1alpha1/package_ui_types.go | 74 - .../apis/releases/v1alpha1/types.go | 70 - .../v1alpha1/zz_generated.deepcopy.go | 1287 -- .../apimachinery/apis/shared/types.go | 71 - .../apis/shared/zz_generated.deepcopy.go | 84 - .../crds/charts.x-helm.dev_chartpresets.yaml | 45 - ...charts.x-helm.dev_clusterchartpresets.yaml | 46 - .../crds/drivers.x-helm.dev_appreleases.yaml | 386 - vendor/x-helm.dev/apimachinery/crds/lib.go | 60 - .../crds/products.x-helm.dev_plans.yaml | 179 - .../crds/products.x-helm.dev_products.yaml | 167 - .../crds/releases.x-helm.dev_bundles.yaml | 412 - .../crds/releases.x-helm.dev_orders.yaml | 261 - 691 files changed, 36 insertions(+), 160351 deletions(-) delete mode 100644 .github/workflows/release-tracker.yml delete mode 100644 .github/workflows/update-docs.yml delete mode 100644 vendor/github.com/PuerkitoBio/purell/.gitignore delete mode 100644 vendor/github.com/PuerkitoBio/purell/LICENSE delete mode 100644 vendor/github.com/PuerkitoBio/purell/README.md delete mode 100644 vendor/github.com/PuerkitoBio/purell/purell.go delete mode 100644 vendor/github.com/PuerkitoBio/purell/urlesc.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/LICENSE delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/alias.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/binary_writer.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/doc.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/encoding.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/event_message.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/finish_message.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/format/doc.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/format/format.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/message.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/spec/attributes.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/spec/doc.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/spec/match_exact_version.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/spec/spec.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/structured_writer.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/to_event.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/transformer.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/binding/write.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/client/client.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/client/client_http.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/client/client_observed.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/client/defaulters.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/client/doc.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/client/http_receiver.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/client/invoker.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/client/observability.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/client/options.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/client/receiver.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/context/context.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/context/delegating.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/context/doc.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/context/logger.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/context/retry.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/content_type.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/data_content_encoding.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/codec.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/doc.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/json/data.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/json/doc.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/text/data.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/text/doc.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/xml/data.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/xml/doc.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/doc.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/event.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/event_data.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/event_interface.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/event_marshal.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/event_reader.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/event_unmarshal.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/event_validation.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/event_writer.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03_reader.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03_writer.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1_reader.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1_writer.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/event/extensions.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/doc.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/error.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/abuse_protection.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/context.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/doc.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/headers.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/message.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/options.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_lifecycle.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_rate.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_retry.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/result.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/retries_result.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/utility.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/write_request.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/http/write_responsewriter.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/inbound.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/lifecycle.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/outbound.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/protocol/result.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/staticcheck.conf delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/types/allocate.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/types/doc.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/types/timestamp.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/types/uri.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/types/uriref.go delete mode 100644 vendor/github.com/cloudevents/sdk-go/v2/types/value.go delete mode 100644 vendor/github.com/containerd/stargz-snapshotter/estargz/LICENSE delete mode 100644 vendor/github.com/containerd/stargz-snapshotter/estargz/build.go delete mode 100644 vendor/github.com/containerd/stargz-snapshotter/estargz/errorutil/errors.go delete mode 100644 vendor/github.com/containerd/stargz-snapshotter/estargz/estargz.go delete mode 100644 vendor/github.com/containerd/stargz-snapshotter/estargz/gzip.go delete mode 100644 vendor/github.com/containerd/stargz-snapshotter/estargz/testutil.go delete mode 100644 vendor/github.com/containerd/stargz-snapshotter/estargz/types.go delete mode 100644 vendor/github.com/docker/cli/AUTHORS delete mode 100644 vendor/github.com/docker/cli/LICENSE delete mode 100644 vendor/github.com/docker/cli/NOTICE delete mode 100644 vendor/github.com/docker/cli/cli/config/config.go delete mode 100644 vendor/github.com/docker/cli/cli/config/configfile/file.go delete mode 100644 vendor/github.com/docker/cli/cli/config/configfile/file_unix.go delete mode 100644 vendor/github.com/docker/cli/cli/config/configfile/file_windows.go delete mode 100644 vendor/github.com/docker/cli/cli/config/credentials/credentials.go delete mode 100644 vendor/github.com/docker/cli/cli/config/credentials/default_store.go delete mode 100644 vendor/github.com/docker/cli/cli/config/credentials/default_store_darwin.go delete mode 100644 vendor/github.com/docker/cli/cli/config/credentials/default_store_linux.go delete mode 100644 vendor/github.com/docker/cli/cli/config/credentials/default_store_unsupported.go delete mode 100644 vendor/github.com/docker/cli/cli/config/credentials/default_store_windows.go delete mode 100644 vendor/github.com/docker/cli/cli/config/credentials/file_store.go delete mode 100644 vendor/github.com/docker/cli/cli/config/credentials/native_store.go delete mode 100644 vendor/github.com/docker/cli/cli/config/types/authconfig.go delete mode 100644 vendor/github.com/docker/distribution/LICENSE delete mode 100644 vendor/github.com/docker/distribution/registry/client/auth/challenge/addr.go delete mode 100644 vendor/github.com/docker/distribution/registry/client/auth/challenge/authchallenge.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/LICENSE delete mode 100644 vendor/github.com/docker/docker-credential-helpers/client/client.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/client/command.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/credentials/error.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/credentials/helper.go delete mode 100644 vendor/github.com/docker/docker-credential-helpers/credentials/version.go delete mode 100644 vendor/github.com/docker/docker/AUTHORS delete mode 100644 vendor/github.com/docker/docker/LICENSE delete mode 100644 vendor/github.com/docker/docker/NOTICE delete mode 100644 vendor/github.com/docker/docker/pkg/homedir/homedir_linux.go delete mode 100644 vendor/github.com/docker/docker/pkg/homedir/homedir_others.go delete mode 100644 vendor/github.com/docker/docker/pkg/homedir/homedir_unix.go delete mode 100644 vendor/github.com/docker/docker/pkg/homedir/homedir_windows.go delete mode 100644 vendor/github.com/google/go-containerregistry/LICENSE delete mode 100644 vendor/github.com/google/go-containerregistry/internal/and/and_closer.go delete mode 100644 vendor/github.com/google/go-containerregistry/internal/compression/compression.go delete mode 100644 vendor/github.com/google/go-containerregistry/internal/estargz/estargz.go delete mode 100644 vendor/github.com/google/go-containerregistry/internal/gzip/zip.go delete mode 100644 vendor/github.com/google/go-containerregistry/internal/redact/redact.go delete mode 100644 vendor/github.com/google/go-containerregistry/internal/retry/retry.go delete mode 100644 vendor/github.com/google/go-containerregistry/internal/retry/wait/kubernetes_apimachinery_wait.go delete mode 100644 vendor/github.com/google/go-containerregistry/internal/verify/verify.go delete mode 100644 vendor/github.com/google/go-containerregistry/internal/windows/windows.go delete mode 100644 vendor/github.com/google/go-containerregistry/internal/zstd/zstd.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/authn/README.md delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/authn/anon.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/authn/auth.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/authn/authn.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/authn/basic.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/authn/bearer.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/authn/doc.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/authn/keychain.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/authn/multikeychain.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/compression/compression.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/crane/append.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/crane/catalog.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/crane/config.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/crane/copy.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/crane/delete.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/crane/digest.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/crane/doc.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/crane/export.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/crane/filemap.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/crane/get.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/crane/list.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/crane/manifest.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/crane/options.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/crane/pull.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/crane/push.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/crane/tag.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/legacy/config.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/legacy/doc.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/legacy/tarball/README.md delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/legacy/tarball/doc.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/legacy/tarball/write.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/logs/logs.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/name/README.md delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/name/check.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/name/digest.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/name/doc.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/name/errors.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/name/options.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/name/ref.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/name/registry.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/name/repository.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/name/tag.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/config.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/doc.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/empty/README.md delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/empty/doc.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/empty/image.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/empty/index.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/hash.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/image.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/index.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/layer.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/layout/README.md delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/layout/blob.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/layout/doc.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/layout/gc.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/layout/image.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/layout/index.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/layout/layoutpath.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/layout/options.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/layout/read.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/layout/write.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/manifest.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/match/match.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/mutate/README.md delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/mutate/doc.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/mutate/image.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/mutate/index.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/mutate/mutate.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/mutate/rebase.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/partial/README.md delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/partial/compressed.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/partial/doc.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/partial/image.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/partial/index.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/partial/uncompressed.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/partial/with.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/platform.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/progress.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/README.md delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/catalog.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/check.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/delete.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/descriptor.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/doc.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/fetcher.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/image.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/index.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/layer.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/list.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/mount.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/multi_write.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/options.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/progress.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/puller.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/pusher.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/referrers.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/schema1.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/README.md delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/basic.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/bearer.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/doc.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/error.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/logger.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/ping.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/retry.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/schemer.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/scope.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/transport.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/useragent.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/remote/write.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/stream/README.md delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/stream/layer.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/tarball/README.md delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/tarball/doc.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/tarball/image.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/tarball/layer.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/tarball/write.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/types/types.go delete mode 100644 vendor/github.com/google/go-containerregistry/pkg/v1/zz_deepcopy_generated.go delete mode 100644 vendor/github.com/jonboulle/clockwork/.editorconfig delete mode 100644 vendor/github.com/jonboulle/clockwork/.gitignore delete mode 100644 vendor/github.com/jonboulle/clockwork/LICENSE delete mode 100644 vendor/github.com/jonboulle/clockwork/README.md delete mode 100644 vendor/github.com/jonboulle/clockwork/clockwork.go delete mode 100644 vendor/github.com/jonboulle/clockwork/context.go delete mode 100644 vendor/github.com/jonboulle/clockwork/ticker.go delete mode 100644 vendor/github.com/jonboulle/clockwork/timer.go delete mode 100644 vendor/github.com/klauspost/compress/.gitattributes delete mode 100644 vendor/github.com/klauspost/compress/.gitignore delete mode 100644 vendor/github.com/klauspost/compress/.goreleaser.yml delete mode 100644 vendor/github.com/klauspost/compress/LICENSE delete mode 100644 vendor/github.com/klauspost/compress/README.md delete mode 100644 vendor/github.com/klauspost/compress/SECURITY.md delete mode 100644 vendor/github.com/klauspost/compress/compressible.go delete mode 100644 vendor/github.com/klauspost/compress/flate/deflate.go delete mode 100644 vendor/github.com/klauspost/compress/flate/dict_decoder.go delete mode 100644 vendor/github.com/klauspost/compress/flate/fast_encoder.go delete mode 100644 vendor/github.com/klauspost/compress/flate/huffman_bit_writer.go delete mode 100644 vendor/github.com/klauspost/compress/flate/huffman_code.go delete mode 100644 vendor/github.com/klauspost/compress/flate/huffman_sortByFreq.go delete mode 100644 vendor/github.com/klauspost/compress/flate/huffman_sortByLiteral.go delete mode 100644 vendor/github.com/klauspost/compress/flate/inflate.go delete mode 100644 vendor/github.com/klauspost/compress/flate/inflate_gen.go delete mode 100644 vendor/github.com/klauspost/compress/flate/level1.go delete mode 100644 vendor/github.com/klauspost/compress/flate/level2.go delete mode 100644 vendor/github.com/klauspost/compress/flate/level3.go delete mode 100644 vendor/github.com/klauspost/compress/flate/level4.go delete mode 100644 vendor/github.com/klauspost/compress/flate/level5.go delete mode 100644 vendor/github.com/klauspost/compress/flate/level6.go delete mode 100644 vendor/github.com/klauspost/compress/flate/matchlen_amd64.go delete mode 100644 vendor/github.com/klauspost/compress/flate/matchlen_amd64.s delete mode 100644 vendor/github.com/klauspost/compress/flate/matchlen_generic.go delete mode 100644 vendor/github.com/klauspost/compress/flate/regmask_amd64.go delete mode 100644 vendor/github.com/klauspost/compress/flate/regmask_other.go delete mode 100644 vendor/github.com/klauspost/compress/flate/stateless.go delete mode 100644 vendor/github.com/klauspost/compress/flate/token.go delete mode 100644 vendor/github.com/klauspost/compress/fse/README.md delete mode 100644 vendor/github.com/klauspost/compress/fse/bitreader.go delete mode 100644 vendor/github.com/klauspost/compress/fse/bitwriter.go delete mode 100644 vendor/github.com/klauspost/compress/fse/bytereader.go delete mode 100644 vendor/github.com/klauspost/compress/fse/compress.go delete mode 100644 vendor/github.com/klauspost/compress/fse/decompress.go delete mode 100644 vendor/github.com/klauspost/compress/fse/fse.go delete mode 100644 vendor/github.com/klauspost/compress/gen.sh delete mode 100644 vendor/github.com/klauspost/compress/huff0/.gitignore delete mode 100644 vendor/github.com/klauspost/compress/huff0/README.md delete mode 100644 vendor/github.com/klauspost/compress/huff0/bitreader.go delete mode 100644 vendor/github.com/klauspost/compress/huff0/bitwriter.go delete mode 100644 vendor/github.com/klauspost/compress/huff0/bytereader.go delete mode 100644 vendor/github.com/klauspost/compress/huff0/compress.go delete mode 100644 vendor/github.com/klauspost/compress/huff0/decompress.go delete mode 100644 vendor/github.com/klauspost/compress/huff0/decompress_amd64.go delete mode 100644 vendor/github.com/klauspost/compress/huff0/decompress_amd64.s delete mode 100644 vendor/github.com/klauspost/compress/huff0/decompress_generic.go delete mode 100644 vendor/github.com/klauspost/compress/huff0/huff0.go delete mode 100644 vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo.go delete mode 100644 vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.go delete mode 100644 vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.s delete mode 100644 vendor/github.com/klauspost/compress/internal/snapref/LICENSE delete mode 100644 vendor/github.com/klauspost/compress/internal/snapref/decode.go delete mode 100644 vendor/github.com/klauspost/compress/internal/snapref/decode_other.go delete mode 100644 vendor/github.com/klauspost/compress/internal/snapref/encode.go delete mode 100644 vendor/github.com/klauspost/compress/internal/snapref/encode_other.go delete mode 100644 vendor/github.com/klauspost/compress/internal/snapref/snappy.go delete mode 100644 vendor/github.com/klauspost/compress/s2sx.mod delete mode 100644 vendor/github.com/klauspost/compress/s2sx.sum delete mode 100644 vendor/github.com/klauspost/compress/zstd/README.md delete mode 100644 vendor/github.com/klauspost/compress/zstd/bitreader.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/bitwriter.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/blockdec.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/blockenc.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/blocktype_string.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/bytebuf.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/bytereader.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/decodeheader.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/decoder.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/decoder_options.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/dict.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/enc_base.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/enc_best.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/enc_better.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/enc_dfast.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/enc_fast.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/encoder.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/encoder_options.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/framedec.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/frameenc.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/fse_decoder.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.s delete mode 100644 vendor/github.com/klauspost/compress/zstd/fse_decoder_generic.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/fse_encoder.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/fse_predefined.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/hash.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/history.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/internal/xxhash/LICENSE.txt delete mode 100644 vendor/github.com/klauspost/compress/zstd/internal/xxhash/README.md delete mode 100644 vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_amd64.s delete mode 100644 vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_arm64.s delete mode 100644 vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_asm.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_other.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_safe.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/matchlen_amd64.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/matchlen_amd64.s delete mode 100644 vendor/github.com/klauspost/compress/zstd/matchlen_generic.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/seqdec.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s delete mode 100644 vendor/github.com/klauspost/compress/zstd/seqdec_generic.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/seqenc.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/snappy.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/zip.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/zstd.go delete mode 100644 vendor/github.com/mitchellh/go-homedir/LICENSE delete mode 100644 vendor/github.com/mitchellh/go-homedir/README.md delete mode 100644 vendor/github.com/mitchellh/go-homedir/homedir.go delete mode 100644 vendor/github.com/nats-io/nats.go/.gitignore delete mode 100644 vendor/github.com/nats-io/nats.go/.golangci.yaml delete mode 100644 vendor/github.com/nats-io/nats.go/.travis.yml delete mode 100644 vendor/github.com/nats-io/nats.go/.words delete mode 100644 vendor/github.com/nats-io/nats.go/.words.readme delete mode 100644 vendor/github.com/nats-io/nats.go/CODE-OF-CONDUCT.md delete mode 100644 vendor/github.com/nats-io/nats.go/CONTRIBUTING.md delete mode 100644 vendor/github.com/nats-io/nats.go/GOVERNANCE.md delete mode 100644 vendor/github.com/nats-io/nats.go/LICENSE delete mode 100644 vendor/github.com/nats-io/nats.go/MAINTAINERS.md delete mode 100644 vendor/github.com/nats-io/nats.go/README.md delete mode 100644 vendor/github.com/nats-io/nats.go/context.go delete mode 100644 vendor/github.com/nats-io/nats.go/dependencies.md delete mode 100644 vendor/github.com/nats-io/nats.go/enc.go delete mode 100644 vendor/github.com/nats-io/nats.go/encoders/builtin/default_enc.go delete mode 100644 vendor/github.com/nats-io/nats.go/encoders/builtin/gob_enc.go delete mode 100644 vendor/github.com/nats-io/nats.go/encoders/builtin/json_enc.go delete mode 100644 vendor/github.com/nats-io/nats.go/go_test.mod delete mode 100644 vendor/github.com/nats-io/nats.go/go_test.sum delete mode 100644 vendor/github.com/nats-io/nats.go/internal/parser/parse.go delete mode 100644 vendor/github.com/nats-io/nats.go/js.go delete mode 100644 vendor/github.com/nats-io/nats.go/jserrors.go delete mode 100644 vendor/github.com/nats-io/nats.go/jsm.go delete mode 100644 vendor/github.com/nats-io/nats.go/kv.go delete mode 100644 vendor/github.com/nats-io/nats.go/legacy_jetstream.md delete mode 100644 vendor/github.com/nats-io/nats.go/nats.go delete mode 100644 vendor/github.com/nats-io/nats.go/netchan.go delete mode 100644 vendor/github.com/nats-io/nats.go/object.go delete mode 100644 vendor/github.com/nats-io/nats.go/parser.go delete mode 100644 vendor/github.com/nats-io/nats.go/rand.go delete mode 100644 vendor/github.com/nats-io/nats.go/testing_internal.go delete mode 100644 vendor/github.com/nats-io/nats.go/timer.go delete mode 100644 vendor/github.com/nats-io/nats.go/util/tls.go delete mode 100644 vendor/github.com/nats-io/nats.go/util/tls_go17.go delete mode 100644 vendor/github.com/nats-io/nats.go/ws.go delete mode 100644 vendor/github.com/nats-io/nkeys/.gitignore delete mode 100644 vendor/github.com/nats-io/nkeys/.goreleaser.yml delete mode 100644 vendor/github.com/nats-io/nkeys/GOVERNANCE.md delete mode 100644 vendor/github.com/nats-io/nkeys/LICENSE delete mode 100644 vendor/github.com/nats-io/nkeys/MAINTAINERS.md delete mode 100644 vendor/github.com/nats-io/nkeys/README.md delete mode 100644 vendor/github.com/nats-io/nkeys/TODO.md delete mode 100644 vendor/github.com/nats-io/nkeys/crc16.go delete mode 100644 vendor/github.com/nats-io/nkeys/creds_utils.go delete mode 100644 vendor/github.com/nats-io/nkeys/dependencies.md delete mode 100644 vendor/github.com/nats-io/nkeys/errors.go delete mode 100644 vendor/github.com/nats-io/nkeys/keypair.go delete mode 100644 vendor/github.com/nats-io/nkeys/nkeys.go delete mode 100644 vendor/github.com/nats-io/nkeys/public.go delete mode 100644 vendor/github.com/nats-io/nkeys/strkey.go delete mode 100644 vendor/github.com/nats-io/nkeys/xkeys.go delete mode 100644 vendor/github.com/nats-io/nuid/.gitignore delete mode 100644 vendor/github.com/nats-io/nuid/.travis.yml delete mode 100644 vendor/github.com/nats-io/nuid/GOVERNANCE.md delete mode 100644 vendor/github.com/nats-io/nuid/LICENSE delete mode 100644 vendor/github.com/nats-io/nuid/MAINTAINERS.md delete mode 100644 vendor/github.com/nats-io/nuid/README.md delete mode 100644 vendor/github.com/nats-io/nuid/nuid.go delete mode 100644 vendor/github.com/opencontainers/image-spec/LICENSE delete mode 100644 vendor/github.com/opencontainers/image-spec/specs-go/v1/annotations.go delete mode 100644 vendor/github.com/opencontainers/image-spec/specs-go/v1/config.go delete mode 100644 vendor/github.com/opencontainers/image-spec/specs-go/v1/descriptor.go delete mode 100644 vendor/github.com/opencontainers/image-spec/specs-go/v1/index.go delete mode 100644 vendor/github.com/opencontainers/image-spec/specs-go/v1/layout.go delete mode 100644 vendor/github.com/opencontainers/image-spec/specs-go/v1/manifest.go delete mode 100644 vendor/github.com/opencontainers/image-spec/specs-go/v1/mediatype.go delete mode 100644 vendor/github.com/opencontainers/image-spec/specs-go/version.go delete mode 100644 vendor/github.com/opencontainers/image-spec/specs-go/versioned.go delete mode 100644 vendor/github.com/sirupsen/logrus/.gitignore delete mode 100644 vendor/github.com/sirupsen/logrus/.golangci.yml delete mode 100644 vendor/github.com/sirupsen/logrus/.travis.yml delete mode 100644 vendor/github.com/sirupsen/logrus/CHANGELOG.md delete mode 100644 vendor/github.com/sirupsen/logrus/LICENSE delete mode 100644 vendor/github.com/sirupsen/logrus/README.md delete mode 100644 vendor/github.com/sirupsen/logrus/alt_exit.go delete mode 100644 vendor/github.com/sirupsen/logrus/appveyor.yml delete mode 100644 vendor/github.com/sirupsen/logrus/buffer_pool.go delete mode 100644 vendor/github.com/sirupsen/logrus/doc.go delete mode 100644 vendor/github.com/sirupsen/logrus/entry.go delete mode 100644 vendor/github.com/sirupsen/logrus/exported.go delete mode 100644 vendor/github.com/sirupsen/logrus/formatter.go delete mode 100644 vendor/github.com/sirupsen/logrus/hooks.go delete mode 100644 vendor/github.com/sirupsen/logrus/json_formatter.go delete mode 100644 vendor/github.com/sirupsen/logrus/logger.go delete mode 100644 vendor/github.com/sirupsen/logrus/logrus.go delete mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_appengine.go delete mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_bsd.go delete mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_js.go delete mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go delete mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go delete mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_solaris.go delete mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_unix.go delete mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_windows.go delete mode 100644 vendor/github.com/sirupsen/logrus/text_formatter.go delete mode 100644 vendor/github.com/sirupsen/logrus/writer.go delete mode 100644 vendor/github.com/vbatts/tar-split/LICENSE delete mode 100644 vendor/github.com/vbatts/tar-split/archive/tar/common.go delete mode 100644 vendor/github.com/vbatts/tar-split/archive/tar/format.go delete mode 100644 vendor/github.com/vbatts/tar-split/archive/tar/reader.go delete mode 100644 vendor/github.com/vbatts/tar-split/archive/tar/stat_actime1.go delete mode 100644 vendor/github.com/vbatts/tar-split/archive/tar/stat_actime2.go delete mode 100644 vendor/github.com/vbatts/tar-split/archive/tar/stat_unix.go delete mode 100644 vendor/github.com/vbatts/tar-split/archive/tar/strconv.go delete mode 100644 vendor/github.com/vbatts/tar-split/archive/tar/writer.go delete mode 100644 vendor/go.bytebuilders.dev/audit/LICENSE delete mode 100644 vendor/go.bytebuilders.dev/audit/api/v1/doc.go delete mode 100644 vendor/go.bytebuilders.dev/audit/api/v1/types.go delete mode 100644 vendor/go.bytebuilders.dev/audit/api/v1/zz_generated.deepcopy.go delete mode 100644 vendor/go.bytebuilders.dev/audit/lib/audit_event.go delete mode 100644 vendor/go.bytebuilders.dev/audit/lib/billing_event.go delete mode 100644 vendor/go.bytebuilders.dev/audit/lib/nats.go delete mode 100644 vendor/go.bytebuilders.dev/audit/lib/node.go delete mode 100644 vendor/go.bytebuilders.dev/audit/lib/publisher.go delete mode 100644 vendor/go.bytebuilders.dev/audit/lib/resource.go delete mode 100644 vendor/go.bytebuilders.dev/license-proxyserver/LICENSE delete mode 100644 vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/register.go delete mode 100644 vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/doc.go delete mode 100644 vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/license_request_types.go delete mode 100644 vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/license_status_types.go delete mode 100644 vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/openapi_generated.go delete mode 100644 vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/register.go delete mode 100644 vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/zz_generated.deepcopy.go delete mode 100644 vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/clientset.go delete mode 100644 vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/scheme/doc.go delete mode 100644 vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/scheme/register.go delete mode 100644 vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1/doc.go delete mode 100644 vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1/generated_expansion.go delete mode 100644 vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1/licenserequest.go delete mode 100644 vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1/licensestatus.go delete mode 100644 vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1/proxyserver_client.go delete mode 100644 vendor/go.bytebuilders.dev/license-verifier/.gitignore delete mode 100644 vendor/go.bytebuilders.dev/license-verifier/LICENSE delete mode 100644 vendor/go.bytebuilders.dev/license-verifier/Makefile delete mode 100644 vendor/go.bytebuilders.dev/license-verifier/README.md delete mode 100644 vendor/go.bytebuilders.dev/license-verifier/apis/licenses/register.go delete mode 100644 vendor/go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1/doc.go delete mode 100644 vendor/go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1/helper.go delete mode 100644 vendor/go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1/register.go delete mode 100644 vendor/go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1/types.go delete mode 100644 vendor/go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1/zz_generated.deepcopy.go delete mode 100644 vendor/go.bytebuilders.dev/license-verifier/info/lib.go delete mode 100644 vendor/go.bytebuilders.dev/license-verifier/kubernetes/.gitignore delete mode 100644 vendor/go.bytebuilders.dev/license-verifier/kubernetes/LICENSE delete mode 100644 vendor/go.bytebuilders.dev/license-verifier/kubernetes/Makefile delete mode 100644 vendor/go.bytebuilders.dev/license-verifier/kubernetes/lib.go delete mode 100644 vendor/go.bytebuilders.dev/license-verifier/lib.go delete mode 100644 vendor/golang.org/x/crypto/blake2b/blake2b.go delete mode 100644 vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.go delete mode 100644 vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.s delete mode 100644 vendor/golang.org/x/crypto/blake2b/blake2b_amd64.s delete mode 100644 vendor/golang.org/x/crypto/blake2b/blake2b_generic.go delete mode 100644 vendor/golang.org/x/crypto/blake2b/blake2b_ref.go delete mode 100644 vendor/golang.org/x/crypto/blake2b/blake2x.go delete mode 100644 vendor/golang.org/x/crypto/blake2b/register.go delete mode 100644 vendor/golang.org/x/crypto/curve25519/curve25519.go delete mode 100644 vendor/golang.org/x/crypto/curve25519/curve25519_compat.go delete mode 100644 vendor/golang.org/x/crypto/curve25519/curve25519_go120.go delete mode 100644 vendor/golang.org/x/crypto/curve25519/internal/field/README delete mode 100644 vendor/golang.org/x/crypto/curve25519/internal/field/fe.go delete mode 100644 vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64.go delete mode 100644 vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64.s delete mode 100644 vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64_noasm.go delete mode 100644 vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64.go delete mode 100644 vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64.s delete mode 100644 vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64_noasm.go delete mode 100644 vendor/golang.org/x/crypto/curve25519/internal/field/fe_generic.go delete mode 100644 vendor/golang.org/x/crypto/curve25519/internal/field/sync.checkpoint delete mode 100644 vendor/golang.org/x/crypto/curve25519/internal/field/sync.sh delete mode 100644 vendor/golang.org/x/crypto/ed25519/ed25519.go delete mode 100644 vendor/golang.org/x/crypto/nacl/box/box.go delete mode 100644 vendor/golang.org/x/sys/execabs/execabs.go delete mode 100644 vendor/golang.org/x/sys/execabs/execabs_go118.go delete mode 100644 vendor/golang.org/x/sys/execabs/execabs_go119.go delete mode 100644 vendor/gomodules.xyz/counter/LICENSE delete mode 100644 vendor/gomodules.xyz/counter/hourly/int.go delete mode 100644 vendor/gomodules.xyz/counter/hourly/int32.go delete mode 100644 vendor/gomodules.xyz/counter/hourly/int64.go delete mode 100644 vendor/gomodules.xyz/counter/hourly/lib.go delete mode 100644 vendor/kmodules.xyz/client-go/tools/clusterid/lib.go delete mode 100644 vendor/kmodules.xyz/custom-resources/util/siteinfo/lib.go delete mode 100644 vendor/kmodules.xyz/go-containerregistry/LICENSE delete mode 100644 vendor/kmodules.xyz/go-containerregistry/name/lib.go delete mode 100644 vendor/kmodules.xyz/offshoot-api/api/v2/doc.go delete mode 100644 vendor/kmodules.xyz/offshoot-api/api/v2/openapi_generated.go delete mode 100644 vendor/kmodules.xyz/offshoot-api/api/v2/types.go delete mode 100644 vendor/kmodules.xyz/offshoot-api/api/v2/zz_generated.deepcopy.go delete mode 100644 vendor/kmodules.xyz/resource-metadata/LICENSE delete mode 100644 vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/doc.go delete mode 100644 vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/generic_resource_helpers.go delete mode 100644 vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/generic_resource_service_types.go delete mode 100644 vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/generic_resource_summary_types.go delete mode 100644 vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/generic_resource_types.go delete mode 100644 vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/groupversion_info.go delete mode 100644 vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/openapi_generated.go delete mode 100644 vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/podview_types.go delete mode 100644 vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/project_types.go delete mode 100644 vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/zz_generated.deepcopy.go delete mode 100644 vendor/kmodules.xyz/resource-metadata/apis/shared/doc.go delete mode 100644 vendor/kmodules.xyz/resource-metadata/apis/shared/helm.go delete mode 100644 vendor/kmodules.xyz/resource-metadata/apis/shared/helpers.go delete mode 100644 vendor/kmodules.xyz/resource-metadata/apis/shared/openapi_generated.go delete mode 100644 vendor/kmodules.xyz/resource-metadata/apis/shared/types.go delete mode 100644 vendor/kmodules.xyz/resource-metadata/apis/shared/zz_generated.deepcopy.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/.gitignore delete mode 100644 vendor/kmodules.xyz/resource-metrics/CONTRIBUTING.md delete mode 100644 vendor/kmodules.xyz/resource-metrics/DCO delete mode 100644 vendor/kmodules.xyz/resource-metrics/LICENSE delete mode 100644 vendor/kmodules.xyz/resource-metrics/Makefile delete mode 100644 vendor/kmodules.xyz/resource-metrics/README.md delete mode 100644 vendor/kmodules.xyz/resource-metrics/api/constants.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/api/doc.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/api/interface.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/api/plugins.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/api/utils.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/apps/v1/daemonset.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/apps/v1/deployment.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/apps/v1/replicaset.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/apps/v1/statefulset.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/batch/v1/cronjob.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/batch/v1/job.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/batch/v1beta1/cronjob.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/calculator.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/core/v1/pod.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/core/v1/pv.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/core/v1/rc.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/doc.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/eval.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/constants.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/elasticsearch.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/kafka.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/mariadb.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/memcached.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/mongodb.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/mysql.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/perconaxtradb.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/pgbouncer.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/postgres.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/proxysql.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/rabbitmq.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/redis.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/redissentinel.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/singlestore.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/zookeeper.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/kubevault.com/v1alpha2/constant.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/kubevault.com/v1alpha2/vaultserver.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/calculator.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/constansts.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/elasticsearch_mapping.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/kafka_mapping.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/mapper.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/mariadb_mapping.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/memcached_mapping.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/mongodb_mapping.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/mysql_mapping.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/pgbouncer_mapping.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/postgres_mapping.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/proxysql_mapping.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/redis_mapping.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/redissentinel_mapping.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/scale.go delete mode 100644 vendor/kmodules.xyz/resource-metrics/template.go delete mode 100644 vendor/sigs.k8s.io/cli-utils/LICENSE delete mode 100644 vendor/sigs.k8s.io/cli-utils/LICENSE_TEMPLATE delete mode 100644 vendor/sigs.k8s.io/cli-utils/LICENSE_TEMPLATE_GO delete mode 100644 vendor/sigs.k8s.io/cli-utils/pkg/kstatus/status/core.go delete mode 100644 vendor/sigs.k8s.io/cli-utils/pkg/kstatus/status/doc.go delete mode 100644 vendor/sigs.k8s.io/cli-utils/pkg/kstatus/status/generic.go delete mode 100644 vendor/sigs.k8s.io/cli-utils/pkg/kstatus/status/status.go delete mode 100644 vendor/sigs.k8s.io/cli-utils/pkg/kstatus/status/util.go delete mode 100644 vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/application_types.go delete mode 100644 vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/bundle_helpers.go delete mode 100644 vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/bundle_types.go delete mode 100644 vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/bundle_ui_types.go delete mode 100644 vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/editor_types.go delete mode 100644 vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/groupversion_info.go delete mode 100644 vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/helpers.go delete mode 100644 vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/hub.go delete mode 100644 vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/order_helpers.go delete mode 100644 vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/order_types.go delete mode 100644 vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/package_ui_types.go delete mode 100644 vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/types.go delete mode 100644 vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/zz_generated.deepcopy.go delete mode 100644 vendor/x-helm.dev/apimachinery/apis/shared/types.go delete mode 100644 vendor/x-helm.dev/apimachinery/apis/shared/zz_generated.deepcopy.go delete mode 100644 vendor/x-helm.dev/apimachinery/crds/charts.x-helm.dev_chartpresets.yaml delete mode 100644 vendor/x-helm.dev/apimachinery/crds/charts.x-helm.dev_clusterchartpresets.yaml delete mode 100644 vendor/x-helm.dev/apimachinery/crds/drivers.x-helm.dev_appreleases.yaml delete mode 100644 vendor/x-helm.dev/apimachinery/crds/lib.go delete mode 100644 vendor/x-helm.dev/apimachinery/crds/products.x-helm.dev_plans.yaml delete mode 100644 vendor/x-helm.dev/apimachinery/crds/products.x-helm.dev_products.yaml delete mode 100644 vendor/x-helm.dev/apimachinery/crds/releases.x-helm.dev_bundles.yaml delete mode 100644 vendor/x-helm.dev/apimachinery/crds/releases.x-helm.dev_orders.yaml diff --git a/.github/workflows/release-tracker.yml b/.github/workflows/release-tracker.yml deleted file mode 100644 index 20712333f..000000000 --- a/.github/workflows/release-tracker.yml +++ /dev/null @@ -1,42 +0,0 @@ -name: release-tracker - -on: - pull_request: - types: [closed] - # Allows you to run this workflow manually from the Actions tab - workflow_dispatch: - -concurrency: - group: ${{ github.workflow }}-${{ github.head_ref || github.ref }} - cancel-in-progress: true - -jobs: - build: - runs-on: ubuntu-20.04 - - steps: - - uses: actions/checkout@v1 - - - name: Prepare git - env: - GITHUB_USER: 1gtm - GITHUB_TOKEN: ${{ secrets.LGTM_GITHUB_TOKEN }} - run: | - git config --global user.name "${GITHUB_USER}" - git config --global user.email "${GITHUB_USER}@appscode.com" - git remote set-url origin https://${GITHUB_USER}:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git - - - name: Install GitHub CLI - run: | - curl -fsSL https://github.com/github/hub/raw/master/script/get | bash -s 2.14.1 - sudo mv bin/hub /usr/local/bin - - - name: Update release tracker - if: | - github.event.action == 'closed' && - github.event.pull_request.merged == true - env: - GITHUB_USER: 1gtm - GITHUB_TOKEN: ${{ secrets.LGTM_GITHUB_TOKEN }} - run: | - ./hack/scripts/update-release-tracker.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f05bbaae1..a99f7b024 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -32,23 +32,14 @@ jobs: - name: Publish to GitHub Container Registry env: - REGISTRY: ghcr.io/stashed - DOCKER_TOKEN: ${{ secrets.LGTM_GITHUB_TOKEN }} - USERNAME: 1gtm + REGISTRY: ghcr.io/jhass + DOCKER_TOKEN: ${{ secrets.GITHUB_TOKEN }} + USERNAME: ${{ github.actor }} APPSCODE_ENV: prod run: | docker login ghcr.io --username ${USERNAME} --password ${DOCKER_TOKEN} make release - - name: Publish to Docker Registry - env: - DOCKER_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }} - USERNAME: 1gtm - APPSCODE_ENV: prod - run: | - docker login --username ${USERNAME} --password ${DOCKER_TOKEN} - make release - - name: Release uses: softprops/action-gh-release@v1 if: startsWith(github.ref, 'refs/tags/') diff --git a/.github/workflows/update-docs.yml b/.github/workflows/update-docs.yml deleted file mode 100644 index e78f012e4..000000000 --- a/.github/workflows/update-docs.yml +++ /dev/null @@ -1,53 +0,0 @@ -name: update-docs - -on: - push: - branches: - - master - # Allows you to run this workflow manually from the Actions tab - workflow_dispatch: - -concurrency: - group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}-docs - cancel-in-progress: true - -jobs: - build: - name: Build - runs-on: ubuntu-20.04 - steps: - - name: Set up Go 1.22 - uses: actions/setup-go@v1 - with: - go-version: '1.22' - id: go - - - uses: actions/checkout@v1 - - - name: Install GitHub CLI - run: | - curl -fsSL https://github.com/github/hub/raw/master/script/get | bash -s 2.14.1 - sudo mv bin/hub /usr/local/bin - - - name: Clone charts repository - env: - GITHUB_USER: 1gtm - GITHUB_TOKEN: ${{ secrets.LGTM_GITHUB_TOKEN }} - DOCS_REPOSITORY: ${{ secrets.DOCS_REPOSITORY }} - run: | - url="https://${GITHUB_USER}:${GITHUB_TOKEN}@${DOCS_REPOSITORY}.git" - cd $RUNNER_WORKSPACE - git clone $url - cd $(basename $DOCS_REPOSITORY) - git config user.name "${GITHUB_USER}" - git config user.email "${GITHUB_USER}@appscode.com" - - - name: Update docs - env: - GITHUB_USER: 1gtm - GITHUB_TOKEN: ${{ secrets.LGTM_GITHUB_TOKEN }} - DOCS_REPOSITORY: ${{ secrets.DOCS_REPOSITORY }} - run: | - export DOCS_ROOT=$RUNNER_WORKSPACE/$(basename $DOCS_REPOSITORY) - ./hack/gendocs/make.sh - $DOCS_ROOT/hack/scripts/open-pr.sh diff --git a/go.mod b/go.mod index 63e5745d3..d7291d01e 100644 --- a/go.mod +++ b/go.mod @@ -14,9 +14,6 @@ require ( github.com/spf13/cobra v1.8.0 github.com/spf13/pflag v1.0.5 go.bytebuilders.dev/audit v0.0.33 - go.bytebuilders.dev/license-proxyserver v0.0.9 - go.bytebuilders.dev/license-verifier v0.14.0 - go.bytebuilders.dev/license-verifier/kubernetes v0.14.0 golang.org/x/text v0.14.0 gomodules.xyz/blobfs v0.1.14 gomodules.xyz/cert v1.6.0 diff --git a/go.sum b/go.sum index bc0b4ae63..9d8910778 100644 --- a/go.sum +++ b/go.sum @@ -862,14 +862,6 @@ github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0= github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA= github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q= -go.bytebuilders.dev/audit v0.0.33 h1:p9cPJpRimV6asHh55RSr1IB6NhSZABvLPo0Md6QB4Nc= -go.bytebuilders.dev/audit v0.0.33/go.mod h1:RjYq4EVdUGLfzSnnm0CtS0kjBgW3zDIDrTQr0YN6SRA= -go.bytebuilders.dev/license-proxyserver v0.0.9 h1:MFArxunIZS0o3LZ+JuSwub8GwZ4bdE3kkfJ8hJfkREQ= -go.bytebuilders.dev/license-proxyserver v0.0.9/go.mod h1:mLX/7EK1gouPWXmG3qibRXF8y+dkR3H1Hgttioy6Dww= -go.bytebuilders.dev/license-verifier v0.14.0 h1:O6pXhz9vz7dPWIJATkX+JiMLhUD2ydzvKzf26c+3Jrw= -go.bytebuilders.dev/license-verifier v0.14.0/go.mod h1:GB9XTSQUcllJ4AVq29TdJI6yRjoI86HGz0XMqq9nLwY= -go.bytebuilders.dev/license-verifier/kubernetes v0.14.0 h1:eeOKHu1YgdHhsaCXf9GNo1ha3SOfaSSe40xG1gc+ArA= -go.bytebuilders.dev/license-verifier/kubernetes v0.14.0/go.mod h1:ms4GTV6vb5eg+dglr8N6EaOybGE77s+kkppFUZ3aZZQ= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.etcd.io/bbolt v1.3.8 h1:xs88BrvEv273UsB79e0hcVrlUWmS0a8upikMFhSyAtA= go.etcd.io/bbolt v1.3.8/go.mod h1:N9Mkw9X8x5fupy0IKsmuqVtoGDyxsaDlbk4Rd05IAQw= diff --git a/hack/build.sh b/hack/build.sh index fb9836e35..8b4e22ad3 100755 --- a/hack/build.sh +++ b/hack/build.sh @@ -35,14 +35,6 @@ export GOOS="${OS}" export GO111MODULE=on export GOFLAGS="-mod=vendor" -ENFORCE_LICENSE=${ENFORCE_LICENSE:-} -if [ ! -z "${git_tag:-}" ]; then - ENFORCE_LICENSE=true -fi -if [ "$ENFORCE_LICENSE" != "true" ]; then - ENFORCE_LICENSE=false -fi - go install \ -installsuffix "static" \ -ldflags " \ @@ -55,9 +47,5 @@ go install \ -X main.GoVersion=$(go version | cut -d " " -f 3) \ -X main.Compiler=$(go env CC) \ -X main.Platform=${OS}/${ARCH} \ - -X 'go.bytebuilders.dev/license-verifier/info.EnforceLicense=${ENFORCE_LICENSE}' \ - -X 'go.bytebuilders.dev/license-verifier/info.LicenseCA=$(curl -fsSL https://licenses.appscode.com/certificates/ca.crt)' \ - -X 'go.bytebuilders.dev/license-verifier/info.ProductOwnerName=${PRODUCT_OWNER_NAME}' \ - -X 'go.bytebuilders.dev/license-verifier/info.ProductName=${PRODUCT_NAME}' \ " \ ./... diff --git a/main.go b/main.go index e95427ad2..1e3d64c57 100644 --- a/main.go +++ b/main.go @@ -23,7 +23,6 @@ import ( _ "stash.appscode.dev/apimachinery/client/clientset/versioned/fake" "stash.appscode.dev/stash/pkg/cmds" - _ "go.bytebuilders.dev/license-verifier/info" "gomodules.xyz/logs" _ "k8s.io/client-go/kubernetes/fake" _ "k8s.io/client-go/plugin/pkg/client/auth" diff --git a/pkg/cmds/server/options.go b/pkg/cmds/server/options.go index 5004a2387..805a89a0f 100644 --- a/pkg/cmds/server/options.go +++ b/pkg/cmds/server/options.go @@ -28,11 +28,7 @@ import ( "stash.appscode.dev/stash/pkg/controller" "github.com/spf13/pflag" - licenseapi "go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1" - "go.bytebuilders.dev/license-verifier/info" - license "go.bytebuilders.dev/license-verifier/kubernetes" crd_cs "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" - "k8s.io/apimachinery/pkg/util/sets" "k8s.io/client-go/kubernetes" "kmodules.xyz/client-go/discovery" appcatalog_cs "kmodules.xyz/custom-resources/client/clientset/versioned" @@ -41,8 +37,6 @@ import ( ) type ExtraOptions struct { - LicenseFile string - LicenseApiService string StashImage string StashImageTag string DockerRegistry string @@ -81,8 +75,6 @@ func (s *ExtraOptions) AddFlags(fs *pflag.FlagSet) { fs.StringVar(&s.StashImageTag, "image-tag", s.StashImageTag, "Image tag for sidecar, init-container, check-job and recovery-job") fs.StringVar(&s.DockerRegistry, "docker-registry", s.DockerRegistry, "Docker image registry for sidecar, init-container, check-job, recovery-job and kubectl-job") fs.StringSliceVar(&s.ImagePullSecrets, "image-pull-secrets", s.ImagePullSecrets, "List of image pull secrets for pulling image from private registries") - fs.StringVar(&s.LicenseFile, "license-file", s.LicenseFile, "Path to license file") - fs.StringVar(&s.LicenseApiService, "license-apiservice", s.LicenseApiService, "Name of the ApiService to use by the addons to identify the respective service and certificate for license verification request") fs.Float64Var(&s.QPS, "qps", s.QPS, "The maximum QPS to the master from this client") fs.IntVar(&s.Burst, "burst", s.Burst, "The maximum burst for throttle") @@ -101,8 +93,6 @@ func (s *ExtraOptions) AddFlags(fs *pflag.FlagSet) { func (s *ExtraOptions) ApplyTo(cfg *controller.Config) error { var err error - cfg.LicenseFile = s.LicenseFile - cfg.LicenseApiService = s.LicenseApiService cfg.StashImage = s.StashImage cfg.StashImageTag = s.StashImageTag cfg.DockerRegistry = s.DockerRegistry @@ -139,17 +129,6 @@ func (s *ExtraOptions) ApplyTo(cfg *controller.Config) error { } } - if cfg.LicenseProvided() { - l := license.MustLicenseEnforcer(cfg.ClientConfig, cfg.LicenseFile).LoadLicense() - if l.Status != licenseapi.LicenseActive { - return fmt.Errorf("license status %s, reason: %s", l.Status, l.Reason) - } - if !sets.NewString(l.Features...).HasAny(info.Features()...) { - return fmt.Errorf("not a valid license for this product") - } - cfg.License = l - } - metrics.SetPushgatewayURL(s.PushgatewayURL) return nil } diff --git a/pkg/cmds/server/start.go b/pkg/cmds/server/start.go index 5e34dbc2e..1b6b60d89 100644 --- a/pkg/cmds/server/start.go +++ b/pkg/cmds/server/start.go @@ -26,7 +26,6 @@ import ( "stash.appscode.dev/stash/pkg/server" "github.com/spf13/pflag" - licenseEnforcer "go.bytebuilders.dev/license-verifier/kubernetes" admissionv1beta1 "k8s.io/api/admission/v1beta1" utilerrors "k8s.io/apimachinery/pkg/util/errors" openapinamer "k8s.io/apiserver/pkg/endpoints/openapi" @@ -142,9 +141,5 @@ func (o StashOptions) Run(stopCh <-chan struct{}) error { return err } - // Start periodic license verification - //nolint:errcheck - go licenseEnforcer.VerifyLicensePeriodically(config.ExtraConfig.ClientConfig, o.ExtraOptions.LicenseFile, stopCh) - return s.Run(stopCh) } diff --git a/pkg/controller/backup_configuration.go b/pkg/controller/backup_configuration.go index ee2944fb7..8c5a184b2 100644 --- a/pkg/controller/backup_configuration.go +++ b/pkg/controller/backup_configuration.go @@ -113,9 +113,6 @@ func (c *StashController) validateBackupConfiguration(bc *api_v1beta1.BackupConf func (c *StashController) initBackupConfigurationWatcher() { c.bcInformer = c.stashInformerFactory.Stash().V1beta1().BackupConfigurations().Informer() c.bcQueue = queue.New(api_v1beta1.ResourceKindBackupConfiguration, c.MaxNumRequeues, c.NumThreads, c.runBackupConfigurationProcessor) - if c.auditor != nil { - c.auditor.ForGVK(c.bcInformer, api_v1beta1.SchemeGroupVersion.WithKind(api_v1beta1.ResourceKindBackupConfiguration)) - } _, _ = c.bcInformer.AddEventHandler(queue.NewEventHandler(c.bcQueue.GetQueue(), func(oldObj, newObj interface{}) bool { bc := newObj.(*api_v1beta1.BackupConfiguration) desiredPhase := invoker.CalculateBackupInvokerPhase(bc.Spec.Driver, bc.Status.Conditions) diff --git a/pkg/controller/backup_session.go b/pkg/controller/backup_session.go index 50ae49f2c..511f92931 100644 --- a/pkg/controller/backup_session.go +++ b/pkg/controller/backup_session.go @@ -92,9 +92,6 @@ func (c *StashController) NewBackupSessionWebhook() hooks.AdmissionHook { func (c *StashController) initBackupSessionWatcher() { c.backupSessionInformer = c.stashInformerFactory.Stash().V1beta1().BackupSessions().Informer() c.backupSessionQueue = queue.New(api_v1beta1.ResourceKindBackupSession, c.MaxNumRequeues, c.NumThreads, c.processBackupSessionEvent) - if c.auditor != nil { - c.auditor.ForGVK(c.backupSessionInformer, api_v1beta1.SchemeGroupVersion.WithKind(api_v1beta1.ResourceKindBackupSession)) - } _, _ = c.backupSessionInformer.AddEventHandler(queue.DefaultEventHandler(c.backupSessionQueue.GetQueue(), core.NamespaceAll)) c.backupSessionLister = c.stashInformerFactory.Stash().V1beta1().BackupSessions().Lister() } @@ -400,16 +397,15 @@ func (c *StashController) newSidecarExecutor(inv invoker.BackupInvoker, w *wapi. } e := &executor.Sidecar{ - KubeClient: c.kubeClient, - OpenshiftClient: c.ocClient, - StashClient: c.stashClient, - RBACOptions: rbacOptions, - Invoker: inv, - Index: index, - Image: c.getDockerImage(), - LicenseApiService: c.LicenseApiService, - Caller: caller, - Workload: w, + KubeClient: c.kubeClient, + OpenshiftClient: c.ocClient, + StashClient: c.stashClient, + RBACOptions: rbacOptions, + Invoker: inv, + Index: index, + Image: c.getDockerImage(), + Caller: caller, + Workload: w, } e.Repository, err = c.repoLister.Repositories(inv.GetRepoRef().Namespace).Get(inv.GetRepoRef().Name) @@ -460,15 +456,14 @@ func (c *StashController) newBackupJob(inv invoker.BackupInvoker, session *invok } e := &executor.BackupJob{ - KubeClient: c.kubeClient, - StashClient: c.stashClient, - CatalogClient: c.appCatalogClient, - RBACOptions: rbacOptions, - Invoker: inv, - Session: session, - Index: index, - Image: c.getDockerImage(), - LicenseApiService: c.LicenseApiService, + KubeClient: c.kubeClient, + StashClient: c.stashClient, + CatalogClient: c.appCatalogClient, + RBACOptions: rbacOptions, + Invoker: inv, + Session: session, + Index: index, + Image: c.getDockerImage(), } e.Repository, err = c.repoLister.Repositories(inv.GetRepoRef().Namespace).Get(inv.GetRepoRef().Name) diff --git a/pkg/controller/config.go b/pkg/controller/config.go index 152ca5850..0662afcc2 100644 --- a/pkg/controller/config.go +++ b/pkg/controller/config.go @@ -17,7 +17,6 @@ limitations under the License. package controller import ( - "fmt" "time" cs "stash.appscode.dev/apimachinery/client/clientset/versioned" @@ -26,16 +25,12 @@ import ( "stash.appscode.dev/stash/pkg/eventer" "stash.appscode.dev/stash/pkg/util" - auditlib "go.bytebuilders.dev/audit/lib" - proxyserver "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1" - licenseapi "go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1" crd_cs "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" reg_util "kmodules.xyz/client-go/admissionregistration/v1" "kmodules.xyz/client-go/discovery" - "kmodules.xyz/client-go/tools/clusterid" appcatalog_cs "kmodules.xyz/custom-resources/client/clientset/versioned" oc_cs "kmodules.xyz/openshift/client/clientset/versioned" oc_informers "kmodules.xyz/openshift/client/informers/externalversions" @@ -47,9 +42,6 @@ const ( ) type config struct { - LicenseFile string - License licenseapi.License - LicenseApiService string StashImage string StashImageTag string DockerRegistry string @@ -81,18 +73,6 @@ func NewConfig(clientConfig *rest.Config) *Config { } } -func (c Config) LicenseProvided() bool { - if c.LicenseFile != "" { - return true - } - - ok, _ := discovery.HasGVK( - c.KubeClient.Discovery(), - proxyserver.SchemeGroupVersion.String(), - proxyserver.ResourceKindLicenseRequest) - return ok -} - func (c *Config) New() (*StashController, error) { if err := discovery.IsDefaultSupportedVersion(c.KubeClient); err != nil { return nil, err @@ -105,27 +85,6 @@ func (c *Config) New() (*StashController, error) { informerFactory := informers.NewSharedInformerFactoryWithOptions(c.KubeClient, c.ResyncPeriod) - // audit event publisher - // WARNING: https://stackoverflow.com/a/46275411/244009 - var auditor *auditlib.EventPublisher - if c.LicenseProvided() && !c.License.DisableAnalytics() { - cmeta, err := clusterid.ClusterMetadata(c.KubeClient.CoreV1().Namespaces()) - if err != nil { - return nil, fmt.Errorf("failed to extract cluster metadata, reason: %v", err) - } - fn := auditlib.BillingEventCreator{ - Mapper: mapper, - ClusterMetadata: cmeta, - } - auditor = auditlib.NewResilientEventPublisher(func() (*auditlib.NatsConfig, error) { - return auditlib.NewNatsConfig(c.ClientConfig, cmeta.UID, c.LicenseFile) - }, mapper, fn.CreateEvent) - err = auditor.SetupSiteInfoPublisher(c.ClientConfig, c.KubeClient, informerFactory) - if err != nil { - return nil, fmt.Errorf("failed to setup site info publisher, reason: %v", err) - } - } - ctrl := &StashController{ config: c.config, clientConfig: c.ClientConfig, @@ -139,7 +98,6 @@ func (c *Config) New() (*StashController, error) { ocInformerFactory: oc_informers.NewSharedInformerFactory(c.OcClient, c.ResyncPeriod), recorder: eventer.NewEventRecorder(c.KubeClient, "stash-operator"), mapper: mapper, - auditor: auditor, } // ensure default functions diff --git a/pkg/controller/controller.go b/pkg/controller/controller.go index 4de3cf5a9..a8c335e90 100644 --- a/pkg/controller/controller.go +++ b/pkg/controller/controller.go @@ -25,7 +25,6 @@ import ( stash_listers_v1beta1 "stash.appscode.dev/apimachinery/client/listers/stash/v1beta1" "stash.appscode.dev/apimachinery/pkg/docker" - auditlib "go.bytebuilders.dev/audit/lib" crd_cs "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/client-go/informers" @@ -56,7 +55,6 @@ type StashController struct { appCatalogClient appcatalog_cs.Interface recorder record.EventRecorder mapper discovery.ResourceMapper - auditor *auditlib.EventPublisher kubeInformerFactory informers.SharedInformerFactory ocInformerFactory oc_informers.SharedInformerFactory diff --git a/pkg/controller/repository.go b/pkg/controller/repository.go index d7408517f..dec8b8f3a 100644 --- a/pkg/controller/repository.go +++ b/pkg/controller/repository.go @@ -74,9 +74,6 @@ func (c *StashController) NewRepositoryWebhook() hooks.AdmissionHook { func (c *StashController) initRepositoryWatcher() { c.repoInformer = c.stashInformerFactory.Stash().V1alpha1().Repositories().Informer() c.repoQueue = queue.New(api_v1alpha1.ResourceKindRepository, c.MaxNumRequeues, c.NumThreads, c.runRepositoryReconciler) - if c.auditor != nil { - c.auditor.ForGVK(c.repoInformer, api_v1alpha1.SchemeGroupVersion.WithKind(api_v1alpha1.ResourceKindRepository)) - } _, _ = c.repoInformer.AddEventHandler(queue.NewReconcilableHandler(c.repoQueue.GetQueue(), core.NamespaceAll)) c.repoLister = c.stashInformerFactory.Stash().V1alpha1().Repositories().Lister() } diff --git a/pkg/controller/restore_session.go b/pkg/controller/restore_session.go index 520f416e2..bd87739f8 100644 --- a/pkg/controller/restore_session.go +++ b/pkg/controller/restore_session.go @@ -130,9 +130,6 @@ func (c *StashController) NewRestoreSessionMutator() hooks.AdmissionHook { func (c *StashController) initRestoreSessionWatcher() { c.restoreSessionInformer = c.stashInformerFactory.Stash().V1beta1().RestoreSessions().Informer() c.restoreSessionQueue = queue.New(api_v1beta1.ResourceKindRestoreSession, c.MaxNumRequeues, c.NumThreads, c.processRestoreSessionEvent) - if c.auditor != nil { - c.auditor.ForGVK(c.restoreSessionInformer, api_v1beta1.SchemeGroupVersion.WithKind(api_v1beta1.ResourceKindRestoreSession)) - } _, _ = c.restoreSessionInformer.AddEventHandler(queue.DefaultEventHandler(c.restoreSessionQueue.GetQueue(), core.NamespaceAll)) c.restoreSessionLister = c.stashInformerFactory.Stash().V1beta1().RestoreSessions().Lister() } @@ -676,16 +673,15 @@ func (c *StashController) newInitContainerExecutor(inv invoker.RestoreInvoker, w } e := &executor.InitContainer{ - KubeClient: c.kubeClient, - OpenshiftClient: c.ocClient, - StashClient: c.stashClient, - RBACOptions: rbacOptions, - Invoker: inv, - Index: index, - Image: c.getDockerImage(), - LicenseApiService: c.LicenseApiService, - Caller: caller, - Workload: w, + KubeClient: c.kubeClient, + OpenshiftClient: c.ocClient, + StashClient: c.stashClient, + RBACOptions: rbacOptions, + Invoker: inv, + Index: index, + Image: c.getDockerImage(), + Caller: caller, + Workload: w, } e.Repository, err = c.repoLister.Repositories(inv.GetRepoRef().Namespace).Get(inv.GetRepoRef().Name) @@ -737,14 +733,13 @@ func (c *StashController) newRestoreJobExecutor(inv invoker.RestoreInvoker, inde } e := &executor.RestoreJob{ - KubeClient: c.kubeClient, - StashClient: c.stashClient, - CatalogClient: c.appCatalogClient, - RBACOptions: rbacOptions, - Invoker: inv, - Index: index, - Image: c.getDockerImage(), - LicenseApiService: c.LicenseApiService, + KubeClient: c.kubeClient, + StashClient: c.stashClient, + CatalogClient: c.appCatalogClient, + RBACOptions: rbacOptions, + Invoker: inv, + Index: index, + Image: c.getDockerImage(), } e.Repository, err = c.repoLister.Repositories(inv.GetRepoRef().Namespace).Get(inv.GetRepoRef().Name) diff --git a/pkg/server/server.go b/pkg/server/server.go index 93fcb6317..9890041d3 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -29,7 +29,6 @@ import ( "stash.appscode.dev/stash/pkg/eventer" snapregistry "stash.appscode.dev/stash/pkg/registry/snapshot" - license "go.bytebuilders.dev/license-verifier/kubernetes" admission "k8s.io/api/admission/v1beta1" core "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -133,9 +132,6 @@ func (c completedConfig) New() (*StashServer, error) { return nil, err } - // Add license handler - license.MustLicenseEnforcer(c.ExtraConfig.ClientConfig, c.ExtraConfig.LicenseFile).Install(genericServer.Handler.NonGoRestfulMux) - var admissionHooks []hooks.AdmissionHook if c.ExtraConfig.EnableValidatingWebhook { admissionHooks = append(admissionHooks, diff --git a/vendor/github.com/PuerkitoBio/purell/.gitignore b/vendor/github.com/PuerkitoBio/purell/.gitignore deleted file mode 100644 index 748e4c807..000000000 --- a/vendor/github.com/PuerkitoBio/purell/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -*.sublime-* -.DS_Store -*.swp -*.swo -tags diff --git a/vendor/github.com/PuerkitoBio/purell/LICENSE b/vendor/github.com/PuerkitoBio/purell/LICENSE deleted file mode 100644 index 640c3ac58..000000000 --- a/vendor/github.com/PuerkitoBio/purell/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright (c) 2012-2022, The Go Authors -Copyright (c) 2012-2022, Martin Angers, Yuki Okushi & Contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -* Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/PuerkitoBio/purell/README.md b/vendor/github.com/PuerkitoBio/purell/README.md deleted file mode 100644 index 846127902..000000000 --- a/vendor/github.com/PuerkitoBio/purell/README.md +++ /dev/null @@ -1,188 +0,0 @@ -# Purell - -Purell is a tiny Go library to normalize URLs. It returns a pure URL. Pure-ell. Sanitizer and all. Yeah, I know... - -Based on the [wikipedia paper][wiki] and the [RFC 3986 document][rfc]. - -[![CI](https://github.com/PuerkitoBio/purell/actions/workflows/ci.yml/badge.svg)](https://github.com/PuerkitoBio/purell/actions/workflows/ci.yml) - -## Install - -`go get github.com/PuerkitoBio/purell` - -## Changelog - -* **v1.1.1** : Fix failing test due to Go1.12 changes (thanks to @ianlancetaylor). -* **2016-11-14 (v1.1.0)** : IDN: Conform to RFC 5895: Fold character width (thanks to @beeker1121). -* **2016-07-27 (v1.0.0)** : Normalize IDN to ASCII (thanks to @zenovich). -* **2015-02-08** : Add fix for relative paths issue ([PR #5][pr5]) and add fix for unnecessary encoding of reserved characters ([see issue #7][iss7]). -* **v0.2.0** : Add benchmarks, Attempt IDN support. -* **v0.1.0** : Initial release. - -## Examples - -From `example_test.go` (note that in your code, you would import "github.com/PuerkitoBio/purell", and would prefix references to its methods and constants with "purell."): - -```go -package purell - -import ( - "fmt" - "net/url" -) - -func ExampleNormalizeURLString() { - if normalized, err := NormalizeURLString("hTTp://someWEBsite.com:80/Amazing%3f/url/", - FlagLowercaseScheme|FlagLowercaseHost|FlagUppercaseEscapes); err != nil { - panic(err) - } else { - fmt.Print(normalized) - } - // Output: http://somewebsite.com:80/Amazing%3F/url/ -} - -func ExampleMustNormalizeURLString() { - normalized := MustNormalizeURLString("hTTpS://someWEBsite.com:443/Amazing%fa/url/", - FlagsUnsafeGreedy) - fmt.Print(normalized) - - // Output: http://somewebsite.com/Amazing%FA/url -} - -func ExampleNormalizeURL() { - if u, err := url.Parse("Http://SomeUrl.com:8080/a/b/.././c///g?c=3&a=1&b=9&c=0#target"); err != nil { - panic(err) - } else { - normalized := NormalizeURL(u, FlagsUsuallySafeGreedy|FlagRemoveDuplicateSlashes|FlagRemoveFragment) - fmt.Print(normalized) - } - - // Output: http://someurl.com:8080/a/c/g?c=3&a=1&b=9&c=0 -} -``` - -## API - -As seen in the examples above, purell offers three methods, `NormalizeURLString(string, NormalizationFlags) (string, error)`, `MustNormalizeURLString(string, NormalizationFlags) (string)` and `NormalizeURL(*url.URL, NormalizationFlags) (string)`. They all normalize the provided URL based on the specified flags. Here are the available flags: - -```go -const ( - // Safe normalizations - FlagLowercaseScheme NormalizationFlags = 1 << iota // HTTP://host -> http://host, applied by default in Go1.1 - FlagLowercaseHost // http://HOST -> http://host - FlagUppercaseEscapes // http://host/t%ef -> http://host/t%EF - FlagDecodeUnnecessaryEscapes // http://host/t%41 -> http://host/tA - FlagEncodeNecessaryEscapes // http://host/!"#$ -> http://host/%21%22#$ - FlagRemoveDefaultPort // http://host:80 -> http://host - FlagRemoveEmptyQuerySeparator // http://host/path? -> http://host/path - - // Usually safe normalizations - FlagRemoveTrailingSlash // http://host/path/ -> http://host/path - FlagAddTrailingSlash // http://host/path -> http://host/path/ (should choose only one of these add/remove trailing slash flags) - FlagRemoveDotSegments // http://host/path/./a/b/../c -> http://host/path/a/c - - // Unsafe normalizations - FlagRemoveDirectoryIndex // http://host/path/index.html -> http://host/path/ - FlagRemoveFragment // http://host/path#fragment -> http://host/path - FlagForceHTTP // https://host -> http://host - FlagRemoveDuplicateSlashes // http://host/path//a///b -> http://host/path/a/b - FlagRemoveWWW // http://www.host/ -> http://host/ - FlagAddWWW // http://host/ -> http://www.host/ (should choose only one of these add/remove WWW flags) - FlagSortQuery // http://host/path?c=3&b=2&a=1&b=1 -> http://host/path?a=1&b=1&b=2&c=3 - - // Normalizations not in the wikipedia article, required to cover tests cases - // submitted by jehiah - FlagDecodeDWORDHost // http://1113982867 -> http://66.102.7.147 - FlagDecodeOctalHost // http://0102.0146.07.0223 -> http://66.102.7.147 - FlagDecodeHexHost // http://0x42660793 -> http://66.102.7.147 - FlagRemoveUnnecessaryHostDots // http://.host../path -> http://host/path - FlagRemoveEmptyPortSeparator // http://host:/path -> http://host/path - - // Convenience set of safe normalizations - FlagsSafe NormalizationFlags = FlagLowercaseHost | FlagLowercaseScheme | FlagUppercaseEscapes | FlagDecodeUnnecessaryEscapes | FlagEncodeNecessaryEscapes | FlagRemoveDefaultPort | FlagRemoveEmptyQuerySeparator - - // For convenience sets, "greedy" uses the "remove trailing slash" and "remove www. prefix" flags, - // while "non-greedy" uses the "add (or keep) the trailing slash" and "add www. prefix". - - // Convenience set of usually safe normalizations (includes FlagsSafe) - FlagsUsuallySafeGreedy NormalizationFlags = FlagsSafe | FlagRemoveTrailingSlash | FlagRemoveDotSegments - FlagsUsuallySafeNonGreedy NormalizationFlags = FlagsSafe | FlagAddTrailingSlash | FlagRemoveDotSegments - - // Convenience set of unsafe normalizations (includes FlagsUsuallySafe) - FlagsUnsafeGreedy NormalizationFlags = FlagsUsuallySafeGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagRemoveWWW | FlagSortQuery - FlagsUnsafeNonGreedy NormalizationFlags = FlagsUsuallySafeNonGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagAddWWW | FlagSortQuery - - // Convenience set of all available flags - FlagsAllGreedy = FlagsUnsafeGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator - FlagsAllNonGreedy = FlagsUnsafeNonGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator -) -``` - -For convenience, the set of flags `FlagsSafe`, `FlagsUsuallySafe[Greedy|NonGreedy]`, `FlagsUnsafe[Greedy|NonGreedy]` and `FlagsAll[Greedy|NonGreedy]` are provided for the similarly grouped normalizations on [wikipedia's URL normalization page][wiki]. You can add (using the bitwise OR `|` operator) or remove (using the bitwise AND NOT `&^` operator) individual flags from the sets if required, to build your own custom set. - -The [full godoc reference is available on gopkgdoc][godoc]. - -Some things to note: - -* `FlagDecodeUnnecessaryEscapes`, `FlagEncodeNecessaryEscapes`, `FlagUppercaseEscapes` and `FlagRemoveEmptyQuerySeparator` are always implicitly set, because internally, the URL string is parsed as an URL object, which automatically decodes unnecessary escapes, uppercases and encodes necessary ones, and removes empty query separators (an unnecessary `?` at the end of the url). So this operation cannot **not** be done. For this reason, `FlagRemoveEmptyQuerySeparator` (as well as the other three) has been included in the `FlagsSafe` convenience set, instead of `FlagsUnsafe`, where Wikipedia puts it. - -* The `FlagDecodeUnnecessaryEscapes` decodes the following escapes (*from -> to*): - - %24 -> $ - - %26 -> & - - %2B-%3B -> +,-./0123456789:; - - %3D -> = - - %40-%5A -> @ABCDEFGHIJKLMNOPQRSTUVWXYZ - - %5F -> _ - - %61-%7A -> abcdefghijklmnopqrstuvwxyz - - %7E -> ~ - - -* When the `NormalizeURL` function is used (passing an URL object), this source URL object is modified (that is, after the call, the URL object will be modified to reflect the normalization). - -* The *replace IP with domain name* normalization (`http://208.77.188.166/ → http://www.example.com/`) is obviously not possible for a library without making some network requests. This is not implemented in purell. - -* The *remove unused query string parameters* and *remove default query parameters* are also not implemented, since this is a very case-specific normalization, and it is quite trivial to do with an URL object. - -### Safe vs Usually Safe vs Unsafe - -Purell allows you to control the level of risk you take while normalizing an URL. You can aggressively normalize, play it totally safe, or anything in between. - -Consider the following URL: - -`HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid` - -Normalizing with the `FlagsSafe` gives: - -`https://www.root.com/toto/tE%1F///a/./b/../c/?z=3&w=2&a=4&w=1#invalid` - -With the `FlagsUsuallySafeGreedy`: - -`https://www.root.com/toto/tE%1F///a/c?z=3&w=2&a=4&w=1#invalid` - -And with `FlagsUnsafeGreedy`: - -`http://root.com/toto/tE%1F/a/c?a=4&w=1&w=2&z=3` - -## TODOs - -* Add a class/default instance to allow specifying custom directory index names? At the moment, removing directory index removes `(^|/)((?:default|index)\.\w{1,4})$`. - -## Thanks / Contributions - -@rogpeppe -@jehiah -@opennota -@pchristopher1275 -@zenovich -@beeker1121 - -## License - -The [BSD 3-Clause license][bsd]. - -[bsd]: http://opensource.org/licenses/BSD-3-Clause -[wiki]: http://en.wikipedia.org/wiki/URL_normalization -[rfc]: http://tools.ietf.org/html/rfc3986#section-6 -[godoc]: http://go.pkgdoc.org/github.com/PuerkitoBio/purell -[pr5]: https://github.com/PuerkitoBio/purell/pull/5 -[iss7]: https://github.com/PuerkitoBio/purell/issues/7 diff --git a/vendor/github.com/PuerkitoBio/purell/purell.go b/vendor/github.com/PuerkitoBio/purell/purell.go deleted file mode 100644 index 3b086ce82..000000000 --- a/vendor/github.com/PuerkitoBio/purell/purell.go +++ /dev/null @@ -1,380 +0,0 @@ -/* -Package purell offers URL normalization as described on the wikipedia page: -http://en.wikipedia.org/wiki/URL_normalization -*/ -package purell - -import ( - "bytes" - "fmt" - "net/url" - "regexp" - "sort" - "strconv" - "strings" - - "golang.org/x/net/idna" - "golang.org/x/text/unicode/norm" - "golang.org/x/text/width" -) - -// A set of normalization flags determines how a URL will -// be normalized. -type NormalizationFlags uint - -const ( - // Safe normalizations - FlagLowercaseScheme NormalizationFlags = 1 << iota // HTTP://host -> http://host, applied by default in Go1.1 - FlagLowercaseHost // http://HOST -> http://host - FlagUppercaseEscapes // http://host/t%ef -> http://host/t%EF - FlagDecodeUnnecessaryEscapes // http://host/t%41 -> http://host/tA - FlagEncodeNecessaryEscapes // http://host/!"#$ -> http://host/%21%22#$ - FlagRemoveDefaultPort // http://host:80 -> http://host - FlagRemoveEmptyQuerySeparator // http://host/path? -> http://host/path - - // Usually safe normalizations - FlagRemoveTrailingSlash // http://host/path/ -> http://host/path - FlagAddTrailingSlash // http://host/path -> http://host/path/ (should choose only one of these add/remove trailing slash flags) - FlagRemoveDotSegments // http://host/path/./a/b/../c -> http://host/path/a/c - - // Unsafe normalizations - FlagRemoveDirectoryIndex // http://host/path/index.html -> http://host/path/ - FlagRemoveFragment // http://host/path#fragment -> http://host/path - FlagForceHTTP // https://host -> http://host - FlagRemoveDuplicateSlashes // http://host/path//a///b -> http://host/path/a/b - FlagRemoveWWW // http://www.host/ -> http://host/ - FlagAddWWW // http://host/ -> http://www.host/ (should choose only one of these add/remove WWW flags) - FlagSortQuery // http://host/path?c=3&b=2&a=1&b=1 -> http://host/path?a=1&b=1&b=2&c=3 - - // Normalizations not in the wikipedia article, required to cover tests cases - // submitted by jehiah - FlagDecodeDWORDHost // http://1113982867 -> http://66.102.7.147 - FlagDecodeOctalHost // http://0102.0146.07.0223 -> http://66.102.7.147 - FlagDecodeHexHost // http://0x42660793 -> http://66.102.7.147 - FlagRemoveUnnecessaryHostDots // http://.host../path -> http://host/path - FlagRemoveEmptyPortSeparator // http://host:/path -> http://host/path - - // Convenience set of safe normalizations - FlagsSafe NormalizationFlags = FlagLowercaseHost | FlagLowercaseScheme | FlagUppercaseEscapes | FlagDecodeUnnecessaryEscapes | FlagEncodeNecessaryEscapes | FlagRemoveDefaultPort | FlagRemoveEmptyQuerySeparator - - // For convenience sets, "greedy" uses the "remove trailing slash" and "remove www. prefix" flags, - // while "non-greedy" uses the "add (or keep) the trailing slash" and "add www. prefix". - - // Convenience set of usually safe normalizations (includes FlagsSafe) - FlagsUsuallySafeGreedy NormalizationFlags = FlagsSafe | FlagRemoveTrailingSlash | FlagRemoveDotSegments - FlagsUsuallySafeNonGreedy NormalizationFlags = FlagsSafe | FlagAddTrailingSlash | FlagRemoveDotSegments - - // Convenience set of unsafe normalizations (includes FlagsUsuallySafe) - FlagsUnsafeGreedy NormalizationFlags = FlagsUsuallySafeGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagRemoveWWW | FlagSortQuery - FlagsUnsafeNonGreedy NormalizationFlags = FlagsUsuallySafeNonGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagAddWWW | FlagSortQuery - - // Convenience set of all available flags - FlagsAllGreedy = FlagsUnsafeGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator - FlagsAllNonGreedy = FlagsUnsafeNonGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator -) - -const ( - defaultHttpPort = ":80" - defaultHttpsPort = ":443" -) - -// Regular expressions used by the normalizations -var rxPort = regexp.MustCompile(`(:\d+)/?$`) -var rxDirIndex = regexp.MustCompile(`(^|/)((?:default|index)\.\w{1,4})$`) -var rxDupSlashes = regexp.MustCompile(`/{2,}`) -var rxDWORDHost = regexp.MustCompile(`^(\d+)((?:\.+)?(?:\:\d*)?)$`) -var rxOctalHost = regexp.MustCompile(`^(0\d*)\.(0\d*)\.(0\d*)\.(0\d*)((?:\.+)?(?:\:\d*)?)$`) -var rxHexHost = regexp.MustCompile(`^0x([0-9A-Fa-f]+)((?:\.+)?(?:\:\d*)?)$`) -var rxHostDots = regexp.MustCompile(`^(.+?)(:\d+)?$`) -var rxHostInteriorDots = regexp.MustCompile(`\.+`) -var rxEmptyPort = regexp.MustCompile(`:+$`) - -// Map of flags to implementation function. -// FlagDecodeUnnecessaryEscapes has no action, since it is done automatically -// by parsing the string as an URL. Same for FlagUppercaseEscapes and FlagRemoveEmptyQuerySeparator. - -// Since maps have undefined traversing order, make a slice of ordered keys -var flagsOrder = []NormalizationFlags{ - FlagLowercaseScheme, - FlagLowercaseHost, - FlagRemoveDefaultPort, - FlagRemoveDirectoryIndex, - FlagRemoveDotSegments, - FlagRemoveFragment, - FlagForceHTTP, // Must be after remove default port (because https=443/http=80) - FlagRemoveDuplicateSlashes, - FlagRemoveWWW, - FlagAddWWW, - FlagSortQuery, - FlagDecodeDWORDHost, - FlagDecodeOctalHost, - FlagDecodeHexHost, - FlagRemoveUnnecessaryHostDots, - FlagRemoveEmptyPortSeparator, - FlagRemoveTrailingSlash, // These two (add/remove trailing slash) must be last - FlagAddTrailingSlash, -} - -// ... and then the map, where order is unimportant -var flags = map[NormalizationFlags]func(*url.URL){ - FlagLowercaseScheme: lowercaseScheme, - FlagLowercaseHost: lowercaseHost, - FlagRemoveDefaultPort: removeDefaultPort, - FlagRemoveDirectoryIndex: removeDirectoryIndex, - FlagRemoveDotSegments: removeDotSegments, - FlagRemoveFragment: removeFragment, - FlagForceHTTP: forceHTTP, - FlagRemoveDuplicateSlashes: removeDuplicateSlashes, - FlagRemoveWWW: removeWWW, - FlagAddWWW: addWWW, - FlagSortQuery: sortQuery, - FlagDecodeDWORDHost: decodeDWORDHost, - FlagDecodeOctalHost: decodeOctalHost, - FlagDecodeHexHost: decodeHexHost, - FlagRemoveUnnecessaryHostDots: removeUnncessaryHostDots, - FlagRemoveEmptyPortSeparator: removeEmptyPortSeparator, - FlagRemoveTrailingSlash: removeTrailingSlash, - FlagAddTrailingSlash: addTrailingSlash, -} - -// MustNormalizeURLString returns the normalized string, and panics if an error occurs. -// It takes an URL string as input, as well as the normalization flags. -func MustNormalizeURLString(u string, f NormalizationFlags) string { - result, e := NormalizeURLString(u, f) - if e != nil { - panic(e) - } - return result -} - -// NormalizeURLString returns the normalized string, or an error if it can't be parsed into an URL object. -// It takes an URL string as input, as well as the normalization flags. -func NormalizeURLString(u string, f NormalizationFlags) (string, error) { - parsed, err := url.Parse(u) - if err != nil { - return "", err - } - - if f&FlagLowercaseHost == FlagLowercaseHost { - parsed.Host = strings.ToLower(parsed.Host) - } - - // The idna package doesn't fully conform to RFC 5895 - // (https://tools.ietf.org/html/rfc5895), so we do it here. - // Taken from Go 1.8 cycle source, courtesy of bradfitz. - // TODO: Remove when (if?) idna package conforms to RFC 5895. - parsed.Host = width.Fold.String(parsed.Host) - parsed.Host = norm.NFC.String(parsed.Host) - if parsed.Host, err = idna.ToASCII(parsed.Host); err != nil { - return "", err - } - - return NormalizeURL(parsed, f), nil -} - -// NormalizeURL returns the normalized string. -// It takes a parsed URL object as input, as well as the normalization flags. -func NormalizeURL(u *url.URL, f NormalizationFlags) string { - for _, k := range flagsOrder { - if f&k == k { - flags[k](u) - } - } - return escapeURL(u) -} - -func lowercaseScheme(u *url.URL) { - if len(u.Scheme) > 0 { - u.Scheme = strings.ToLower(u.Scheme) - } -} - -func lowercaseHost(u *url.URL) { - if len(u.Host) > 0 { - u.Host = strings.ToLower(u.Host) - } -} - -func removeDefaultPort(u *url.URL) { - if len(u.Host) > 0 { - scheme := strings.ToLower(u.Scheme) - u.Host = rxPort.ReplaceAllStringFunc(u.Host, func(val string) string { - if (scheme == "http" && val == defaultHttpPort) || (scheme == "https" && val == defaultHttpsPort) { - return "" - } - return val - }) - } -} - -func removeTrailingSlash(u *url.URL) { - if l := len(u.Path); l > 0 { - if strings.HasSuffix(u.Path, "/") { - u.Path = u.Path[:l-1] - } - } else if l = len(u.Host); l > 0 { - if strings.HasSuffix(u.Host, "/") { - u.Host = u.Host[:l-1] - } - } -} - -func addTrailingSlash(u *url.URL) { - if l := len(u.Path); l > 0 { - if !strings.HasSuffix(u.Path, "/") { - u.Path += "/" - } - } else if l = len(u.Host); l > 0 { - if !strings.HasSuffix(u.Host, "/") { - u.Host += "/" - } - } -} - -func removeDotSegments(u *url.URL) { - if len(u.Path) > 0 { - var dotFree []string - var lastIsDot bool - - sections := strings.Split(u.Path, "/") - for _, s := range sections { - if s == ".." { - if len(dotFree) > 0 { - dotFree = dotFree[:len(dotFree)-1] - } - } else if s != "." { - dotFree = append(dotFree, s) - } - lastIsDot = (s == "." || s == "..") - } - // Special case if host does not end with / and new path does not begin with / - u.Path = strings.Join(dotFree, "/") - if u.Host != "" && !strings.HasSuffix(u.Host, "/") && !strings.HasPrefix(u.Path, "/") { - u.Path = "/" + u.Path - } - // Special case if the last segment was a dot, make sure the path ends with a slash - if lastIsDot && !strings.HasSuffix(u.Path, "/") { - u.Path += "/" - } - } -} - -func removeDirectoryIndex(u *url.URL) { - if len(u.Path) > 0 { - u.Path = rxDirIndex.ReplaceAllString(u.Path, "$1") - } -} - -func removeFragment(u *url.URL) { - u.Fragment = "" -} - -func forceHTTP(u *url.URL) { - if strings.ToLower(u.Scheme) == "https" { - u.Scheme = "http" - } -} - -func removeDuplicateSlashes(u *url.URL) { - if len(u.Path) > 0 { - u.Path = rxDupSlashes.ReplaceAllString(u.Path, "/") - } -} - -func removeWWW(u *url.URL) { - if len(u.Host) > 0 && strings.HasPrefix(strings.ToLower(u.Host), "www.") { - u.Host = u.Host[4:] - } -} - -func addWWW(u *url.URL) { - if len(u.Host) > 0 && !strings.HasPrefix(strings.ToLower(u.Host), "www.") { - u.Host = "www." + u.Host - } -} - -func sortQuery(u *url.URL) { - q := u.Query() - - if len(q) > 0 { - arKeys := make([]string, len(q)) - i := 0 - for k := range q { - arKeys[i] = k - i++ - } - sort.Strings(arKeys) - buf := new(bytes.Buffer) - for _, k := range arKeys { - sort.Strings(q[k]) - for _, v := range q[k] { - if buf.Len() > 0 { - buf.WriteRune('&') - } - buf.WriteString(fmt.Sprintf("%s=%s", k, url.QueryEscape(v))) - } - } - - // Rebuild the raw query string - u.RawQuery = buf.String() - } -} - -func decodeDWORDHost(u *url.URL) { - if len(u.Host) > 0 { - if matches := rxDWORDHost.FindStringSubmatch(u.Host); len(matches) > 2 { - var parts [4]int64 - - dword, _ := strconv.ParseInt(matches[1], 10, 0) - for i, shift := range []uint{24, 16, 8, 0} { - parts[i] = dword >> shift & 0xFF - } - u.Host = fmt.Sprintf("%d.%d.%d.%d%s", parts[0], parts[1], parts[2], parts[3], matches[2]) - } - } -} - -func decodeOctalHost(u *url.URL) { - if len(u.Host) > 0 { - if matches := rxOctalHost.FindStringSubmatch(u.Host); len(matches) > 5 { - var parts [4]int64 - - for i := 1; i <= 4; i++ { - parts[i-1], _ = strconv.ParseInt(matches[i], 8, 0) - } - u.Host = fmt.Sprintf("%d.%d.%d.%d%s", parts[0], parts[1], parts[2], parts[3], matches[5]) - } - } -} - -func decodeHexHost(u *url.URL) { - if len(u.Host) > 0 { - if matches := rxHexHost.FindStringSubmatch(u.Host); len(matches) > 2 { - // Conversion is safe because of regex validation - parsed, _ := strconv.ParseInt(matches[1], 16, 0) - // Set host as DWORD (base 10) encoded host - u.Host = fmt.Sprintf("%d%s", parsed, matches[2]) - // The rest is the same as decoding a DWORD host - decodeDWORDHost(u) - } - } -} - -func removeUnncessaryHostDots(u *url.URL) { - if len(u.Host) > 0 { - if matches := rxHostDots.FindStringSubmatch(u.Host); len(matches) > 1 { - // Trim the leading and trailing dots - u.Host = strings.Trim(matches[1], ".") - if len(matches) > 2 { - u.Host += matches[2] - } - } - u.Host = rxHostInteriorDots.ReplaceAllString(u.Host, ".") - } -} - -func removeEmptyPortSeparator(u *url.URL) { - if len(u.Host) > 0 { - u.Host = rxEmptyPort.ReplaceAllString(u.Host, "") - } -} diff --git a/vendor/github.com/PuerkitoBio/purell/urlesc.go b/vendor/github.com/PuerkitoBio/purell/urlesc.go deleted file mode 100644 index 53d815fd4..000000000 --- a/vendor/github.com/PuerkitoBio/purell/urlesc.go +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file implements query escaping as per RFC 3986. -// It contains some parts of the net/url package, modified so as to allow -// some reserved characters incorrectly escaped by net/url. -// See https://github.com/golang/go/issues/5684 -package purell - -import ( - "bytes" - "net/url" - "strings" -) - -type encoding int - -const ( - encodePath encoding = 1 + iota - encodeUserPassword - encodeQueryComponent - encodeFragment -) - -// Return true if the specified character should be escaped when -// appearing in a URL string, according to RFC 3986. -func shouldEscape(c byte, mode encoding) bool { - // §2.3 Unreserved characters (alphanum) - if 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' { - return false - } - - switch c { - case '-', '.', '_', '~': // §2.3 Unreserved characters (mark) - return false - - // §2.2 Reserved characters (reserved) - case ':', '/', '?', '#', '[', ']', '@', // gen-delims - '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=': // sub-delims - // Different sections of the URL allow a few of - // the reserved characters to appear unescaped. - switch mode { - case encodePath: // §3.3 - // The RFC allows sub-delims and : @. - // '/', '[' and ']' can be used to assign meaning to individual path - // segments. This package only manipulates the path as a whole, - // so we allow those as well. That leaves only ? and # to escape. - return c == '?' || c == '#' - - case encodeUserPassword: // §3.2.1 - // The RFC allows : and sub-delims in - // userinfo. The parsing of userinfo treats ':' as special so we must escape - // all the gen-delims. - return c == ':' || c == '/' || c == '?' || c == '#' || c == '[' || c == ']' || c == '@' - - case encodeQueryComponent: // §3.4 - // The RFC allows / and ?. - return c != '/' && c != '?' - - case encodeFragment: // §4.1 - // The RFC text is silent but the grammar allows - // everything, so escape nothing but # - return c == '#' - } - } - - // Everything else must be escaped. - return true -} - -func escape(s string, mode encoding) string { - spaceCount, hexCount := 0, 0 - for i := 0; i < len(s); i++ { - c := s[i] - if shouldEscape(c, mode) { - if c == ' ' && mode == encodeQueryComponent { - spaceCount++ - } else { - hexCount++ - } - } - } - - if spaceCount == 0 && hexCount == 0 { - return s - } - - t := make([]byte, len(s)+2*hexCount) - j := 0 - for i := 0; i < len(s); i++ { - switch c := s[i]; { - case c == ' ' && mode == encodeQueryComponent: - t[j] = '+' - j++ - case shouldEscape(c, mode): - t[j] = '%' - t[j+1] = "0123456789ABCDEF"[c>>4] - t[j+2] = "0123456789ABCDEF"[c&15] - j += 3 - default: - t[j] = s[i] - j++ - } - } - return string(t) -} - -var uiReplacer = strings.NewReplacer( - "%21", "!", - "%27", "'", - "%28", "(", - "%29", ")", - "%2A", "*", -) - -// unescapeUserinfo unescapes some characters that need not to be escaped as per RFC3986. -func unescapeUserinfo(s string) string { - return uiReplacer.Replace(s) -} - -// Escape reassembles the URL into a valid URL string. -// The general form of the result is one of: -// -// scheme:opaque -// scheme://userinfo@host/path?query#fragment -// -// If u.Opaque is non-empty, String uses the first form; -// otherwise it uses the second form. -// -// In the second form, the following rules apply: -// - if u.Scheme is empty, scheme: is omitted. -// - if u.User is nil, userinfo@ is omitted. -// - if u.Host is empty, host/ is omitted. -// - if u.Scheme and u.Host are empty and u.User is nil, -// the entire scheme://userinfo@host/ is omitted. -// - if u.Host is non-empty and u.Path begins with a /, -// the form host/path does not add its own /. -// - if u.RawQuery is empty, ?query is omitted. -// - if u.Fragment is empty, #fragment is omitted. -func escapeURL(u *url.URL) string { - var buf bytes.Buffer - if u.Scheme != "" { - buf.WriteString(u.Scheme) - buf.WriteByte(':') - } - if u.Opaque != "" { - buf.WriteString(u.Opaque) - } else { - if u.Scheme != "" || u.Host != "" || u.User != nil { - buf.WriteString("//") - if ui := u.User; ui != nil { - buf.WriteString(unescapeUserinfo(ui.String())) - buf.WriteByte('@') - } - if h := u.Host; h != "" { - buf.WriteString(h) - } - } - if u.Path != "" && u.Path[0] != '/' && u.Host != "" { - buf.WriteByte('/') - } - buf.WriteString(escape(u.Path, encodePath)) - } - if u.RawQuery != "" { - buf.WriteByte('?') - buf.WriteString(u.RawQuery) - } - if u.Fragment != "" { - buf.WriteByte('#') - buf.WriteString(escape(u.Fragment, encodeFragment)) - } - return buf.String() -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/LICENSE b/vendor/github.com/cloudevents/sdk-go/v2/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - 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 "[]" - 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 - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/cloudevents/sdk-go/v2/alias.go b/vendor/github.com/cloudevents/sdk-go/v2/alias.go deleted file mode 100644 index 2fbfaa9a7..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/alias.go +++ /dev/null @@ -1,187 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -// Package v2 reexports a subset of the SDK v2 API. -package v2 - -// Package cloudevents alias' common functions and types to improve discoverability and reduce -// the number of imports for simple HTTP clients. - -import ( - "github.com/cloudevents/sdk-go/v2/binding" - "github.com/cloudevents/sdk-go/v2/client" - "github.com/cloudevents/sdk-go/v2/context" - "github.com/cloudevents/sdk-go/v2/event" - "github.com/cloudevents/sdk-go/v2/protocol" - "github.com/cloudevents/sdk-go/v2/protocol/http" - "github.com/cloudevents/sdk-go/v2/types" -) - -// Client - -type ClientOption = client.Option -type Client = client.Client - -// Event - -type Event = event.Event -type Result = protocol.Result - -// Context - -type EventContext = event.EventContext -type EventContextV1 = event.EventContextV1 -type EventContextV03 = event.EventContextV03 - -// Custom Types - -type Timestamp = types.Timestamp -type URIRef = types.URIRef - -// HTTP Protocol - -type HTTPOption = http.Option - -type HTTPProtocol = http.Protocol - -// Encoding - -type Encoding = binding.Encoding - -// Message - -type Message = binding.Message - -const ( - // ReadEncoding - - ApplicationXML = event.ApplicationXML - ApplicationJSON = event.ApplicationJSON - TextPlain = event.TextPlain - ApplicationCloudEventsJSON = event.ApplicationCloudEventsJSON - ApplicationCloudEventsBatchJSON = event.ApplicationCloudEventsBatchJSON - Base64 = event.Base64 - - // Event Versions - - VersionV1 = event.CloudEventsVersionV1 - VersionV03 = event.CloudEventsVersionV03 - - // Encoding - - EncodingBinary = binding.EncodingBinary - EncodingStructured = binding.EncodingStructured -) - -var ( - - // ContentType Helpers - - StringOfApplicationJSON = event.StringOfApplicationJSON - StringOfApplicationXML = event.StringOfApplicationXML - StringOfTextPlain = event.StringOfTextPlain - StringOfApplicationCloudEventsJSON = event.StringOfApplicationCloudEventsJSON - StringOfApplicationCloudEventsBatchJSON = event.StringOfApplicationCloudEventsBatchJSON - StringOfBase64 = event.StringOfBase64 - - // Client Creation - - NewClient = client.New - NewClientHTTP = client.NewHTTP - // Deprecated: please use New with the observability options. - NewClientObserved = client.NewObserved - // Deprecated: Please use NewClientHTTP with the observability options. - NewDefaultClient = client.NewDefault - NewHTTPReceiveHandler = client.NewHTTPReceiveHandler - - // Client Options - - WithEventDefaulter = client.WithEventDefaulter - WithUUIDs = client.WithUUIDs - WithTimeNow = client.WithTimeNow - // Deprecated: this is now noop and will be removed in future releases. - WithTracePropagation = client.WithTracePropagation() - - // Event Creation - - NewEvent = event.New - - // Results - - NewResult = protocol.NewResult - ResultIs = protocol.ResultIs - ResultAs = protocol.ResultAs - - // Receipt helpers - - NewReceipt = protocol.NewReceipt - - ResultACK = protocol.ResultACK - ResultNACK = protocol.ResultNACK - - IsACK = protocol.IsACK - IsNACK = protocol.IsNACK - IsUndelivered = protocol.IsUndelivered - - // HTTP Results - - NewHTTPResult = http.NewResult - NewHTTPRetriesResult = http.NewRetriesResult - - // Message Creation - - ToMessage = binding.ToMessage - - // Event Creation - - NewEventFromHTTPRequest = http.NewEventFromHTTPRequest - NewEventFromHTTPResponse = http.NewEventFromHTTPResponse - NewEventsFromHTTPRequest = http.NewEventsFromHTTPRequest - NewEventsFromHTTPResponse = http.NewEventsFromHTTPResponse - NewHTTPRequestFromEvent = http.NewHTTPRequestFromEvent - NewHTTPRequestFromEvents = http.NewHTTPRequestFromEvents - IsHTTPBatch = http.IsHTTPBatch - - // HTTP Messages - - WriteHTTPRequest = http.WriteRequest - - // Context - - ContextWithTarget = context.WithTarget - TargetFromContext = context.TargetFrom - ContextWithRetriesConstantBackoff = context.WithRetriesConstantBackoff - ContextWithRetriesLinearBackoff = context.WithRetriesLinearBackoff - ContextWithRetriesExponentialBackoff = context.WithRetriesExponentialBackoff - - WithEncodingBinary = binding.WithForceBinary - WithEncodingStructured = binding.WithForceStructured - - // Custom Types - - ParseTimestamp = types.ParseTimestamp - ParseURIRef = types.ParseURIRef - ParseURI = types.ParseURI - - // HTTP Protocol - - NewHTTP = http.New - - // HTTP Protocol Options - - WithTarget = http.WithTarget - WithHeader = http.WithHeader - WithShutdownTimeout = http.WithShutdownTimeout - //WithEncoding = http.WithEncoding - //WithStructuredEncoding = http.WithStructuredEncoding // TODO: expose new way - WithPort = http.WithPort - WithPath = http.WithPath - WithMiddleware = http.WithMiddleware - WithListener = http.WithListener - WithRoundTripper = http.WithRoundTripper - WithGetHandlerFunc = http.WithGetHandlerFunc - WithOptionsHandlerFunc = http.WithOptionsHandlerFunc - WithDefaultOptionsHandlerFunc = http.WithDefaultOptionsHandlerFunc -) diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/binary_writer.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/binary_writer.go deleted file mode 100644 index 97f2c4dd7..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/binding/binary_writer.go +++ /dev/null @@ -1,52 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package binding - -import ( - "context" - "io" - - "github.com/cloudevents/sdk-go/v2/binding/spec" -) - -// MessageMetadataWriter is used to set metadata when a binary Message is visited. -type MessageMetadataWriter interface { - // Set a standard attribute. - // - // The value can either be the correct golang type for the attribute, or a canonical - // string encoding, or nil. If value is nil, then the attribute should be deleted. - // See package types to perform the needed conversions. - SetAttribute(attribute spec.Attribute, value interface{}) error - - // Set an extension attribute. - // - // The value can either be the correct golang type for the attribute, or a canonical - // string encoding, or nil. If value is nil, then the extension should be deleted. - // See package types to perform the needed conversions. - SetExtension(name string, value interface{}) error -} - -// BinaryWriter is used to visit a binary Message and generate a new representation. -// -// Protocols that supports binary encoding should implement this interface to implement direct -// binary to binary encoding and event to binary encoding. -// -// Start() and End() methods must be invoked by the caller of Message.ReadBinary() every time -// the BinaryWriter implementation is used to visit a Message. -type BinaryWriter interface { - MessageMetadataWriter - - // Method invoked at the beginning of the visit. Useful to perform initial memory allocations - Start(ctx context.Context) error - - // SetData receives an io.Reader for the data attribute. - // io.Reader is not invoked when the data attribute is empty - SetData(data io.Reader) error - - // End method is invoked only after the whole encoding process ends successfully. - // If it fails, it's never invoked. It can be used to finalize the message. - End(ctx context.Context) error -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/doc.go deleted file mode 100644 index ff92f6836..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/binding/doc.go +++ /dev/null @@ -1,66 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -/* -Package binding defines interfaces for protocol bindings. - -NOTE: Most applications that emit or consume events should use the ../client -package, which provides a simpler API to the underlying binding. - -The interfaces in this package provide extra encoding and protocol information -to allow efficient forwarding and end-to-end reliable delivery between a -Receiver and a Sender belonging to different bindings. This is useful for -intermediary applications that route or forward events, but not necessary for -most "endpoint" applications that emit or consume events. - -# Protocol Bindings - -A protocol binding usually implements a Message, a Sender and Receiver, a StructuredWriter and a BinaryWriter (depending on the supported encodings of the protocol) and an Write[ProtocolMessage] method. - -# Read and write events - -The core of this package is the binding.Message interface. -Through binding.MessageReader It defines how to read a protocol specific message for an -encoded event in structured mode or binary mode. -The entity who receives a protocol specific data structure representing a message -(e.g. an HttpRequest) encapsulates it in a binding.Message implementation using a NewMessage method (e.g. http.NewMessage). -Then the entity that wants to send the binding.Message back on the wire, -translates it back to the protocol specific data structure (e.g. a Kafka ConsumerMessage), using -the writers BinaryWriter and StructuredWriter specific to that protocol. -Binding implementations exposes their writers -through a specific Write[ProtocolMessage] function (e.g. kafka.EncodeProducerMessage), -in order to simplify the encoding process. - -The encoding process can be customized in order to mutate the final result with binding.TransformerFactory. -A bunch of these are provided directly by the binding/transformer module. - -Usually binding.Message implementations can be encoded only one time, because the encoding process drain the message itself. -In order to consume a message several times, the binding/buffering package provides several APIs to buffer the Message. - -A message can be converted to an event.Event using binding.ToEvent() method. -An event.Event can be used as Message casting it to binding.EventMessage. - -In order to simplify the encoding process for each protocol, this package provide several utility methods like binding.Write and binding.DirectWrite. -The binding.Write method tries to preserve the structured/binary encoding, in order to be as much efficient as possible. - -Messages can be eventually wrapped to change their behaviours and binding their lifecycle, like the binding.FinishMessage. -Every Message wrapper implements the MessageWrapper interface - -# Sender and Receiver - -A Receiver receives protocol specific messages and wraps them to into binding.Message implementations. - -A Sender converts arbitrary Message implementations to a protocol-specific form using the protocol specific Write method -and sends them. - -Message and ExactlyOnceMessage provide methods to allow acknowledgments to -propagate when a reliable messages is forwarded from a Receiver to a Sender. -QoS 0 (unreliable), 1 (at-least-once) and 2 (exactly-once) are supported. - -# Transport - -A binding implementation providing Sender and Receiver implementations can be used as a Transport through the BindingTransport adapter. -*/ -package binding diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/encoding.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/encoding.go deleted file mode 100644 index bb8f91424..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/binding/encoding.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package binding - -import "errors" - -// Encoding enum specifies the type of encodings supported by binding interfaces -type Encoding int - -const ( - // Binary encoding as specified in https://github.com/cloudevents/spec/blob/main/cloudevents/spec.md#message - EncodingBinary Encoding = iota - // Structured encoding as specified in https://github.com/cloudevents/spec/blob/main/cloudevents/spec.md#message - EncodingStructured - // Message is an instance of EventMessage or it contains EventMessage nested (through MessageWrapper) - EncodingEvent - // When the encoding is unknown (which means that the message is a non-event) - EncodingUnknown - - // EncodingBatch is an instance of JSON Batched Events - EncodingBatch -) - -func (e Encoding) String() string { - switch e { - case EncodingBinary: - return "binary" - case EncodingStructured: - return "structured" - case EncodingEvent: - return "event" - case EncodingBatch: - return "batch" - case EncodingUnknown: - return "unknown" - } - return "" -} - -// ErrUnknownEncoding specifies that the Message is not an event or it is encoded with an unknown encoding -var ErrUnknownEncoding = errors.New("unknown Message encoding") - -// ErrNotStructured returned by Message.Structured for non-structured messages. -var ErrNotStructured = errors.New("message is not in structured mode") - -// ErrNotBinary returned by Message.Binary for non-binary messages. -var ErrNotBinary = errors.New("message is not in binary mode") diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/event_message.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/event_message.go deleted file mode 100644 index 83d613af4..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/binding/event_message.go +++ /dev/null @@ -1,110 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package binding - -import ( - "bytes" - "context" - - "github.com/cloudevents/sdk-go/v2/binding/format" - "github.com/cloudevents/sdk-go/v2/binding/spec" - "github.com/cloudevents/sdk-go/v2/event" -) - -type eventFormatKey int - -const ( - formatEventStructured eventFormatKey = iota -) - -// EventMessage type-converts a event.Event object to implement Message. -// This allows local event.Event objects to be sent directly via Sender.Send() -// -// s.Send(ctx, binding.EventMessage(e)) -// -// When an event is wrapped into a EventMessage, the original event could be -// potentially mutated. If you need to use the Event again, after wrapping it into -// an Event message, you should copy it before -type EventMessage event.Event - -func ToMessage(e *event.Event) Message { - return (*EventMessage)(e) -} - -func (m *EventMessage) ReadEncoding() Encoding { - return EncodingEvent -} - -func (m *EventMessage) ReadStructured(ctx context.Context, builder StructuredWriter) error { - f := GetOrDefaultFromCtx(ctx, formatEventStructured, format.JSON).(format.Format) - b, err := f.Marshal((*event.Event)(m)) - if err != nil { - return err - } - return builder.SetStructuredEvent(ctx, f, bytes.NewReader(b)) -} - -func (m *EventMessage) ReadBinary(ctx context.Context, b BinaryWriter) (err error) { - err = eventContextToBinaryWriter(m.Context, b) - if err != nil { - return err - } - // Pass the body - body := (*event.Event)(m).Data() - if len(body) > 0 { - err = b.SetData(bytes.NewBuffer(body)) - if err != nil { - return err - } - } - return nil -} - -func (m *EventMessage) GetAttribute(k spec.Kind) (spec.Attribute, interface{}) { - sv := spec.VS.Version(m.Context.GetSpecVersion()) - a := sv.AttributeFromKind(k) - if a != nil { - return a, a.Get(m.Context) - } - return nil, nil -} - -func (m *EventMessage) GetExtension(name string) interface{} { - ext, _ := m.Context.GetExtension(name) - return ext -} - -func eventContextToBinaryWriter(c event.EventContext, b BinaryWriter) (err error) { - // Pass all attributes - sv := spec.VS.Version(c.GetSpecVersion()) - for _, a := range sv.Attributes() { - value := a.Get(c) - if value != nil { - err = b.SetAttribute(a, value) - } - if err != nil { - return err - } - } - // Pass all extensions - for k, v := range c.GetExtensions() { - err = b.SetExtension(k, v) - if err != nil { - return err - } - } - return nil -} - -func (*EventMessage) Finish(error) error { return nil } - -var _ Message = (*EventMessage)(nil) // Test it conforms to the interface -var _ MessageMetadataReader = (*EventMessage)(nil) // Test it conforms to the interface - -// UseFormatForEvent configures which format to use when marshalling the event to structured mode -func UseFormatForEvent(ctx context.Context, f format.Format) context.Context { - return context.WithValue(ctx, formatEventStructured, f) -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/finish_message.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/finish_message.go deleted file mode 100644 index 8b51c4c61..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/binding/finish_message.go +++ /dev/null @@ -1,42 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package binding - -import "github.com/cloudevents/sdk-go/v2/binding/spec" - -type finishMessage struct { - Message - finish func(error) -} - -func (m *finishMessage) GetAttribute(k spec.Kind) (spec.Attribute, interface{}) { - return m.Message.(MessageMetadataReader).GetAttribute(k) -} - -func (m *finishMessage) GetExtension(s string) interface{} { - return m.Message.(MessageMetadataReader).GetExtension(s) -} - -func (m *finishMessage) GetWrappedMessage() Message { - return m.Message -} - -func (m *finishMessage) Finish(err error) error { - err2 := m.Message.Finish(err) // Finish original message first - if m.finish != nil { - m.finish(err) // Notify callback - } - return err2 -} - -var _ MessageWrapper = (*finishMessage)(nil) - -// WithFinish returns a wrapper for m that calls finish() and -// m.Finish() in its Finish(). -// Allows code to be notified when a message is Finished. -func WithFinish(m Message, finish func(error)) Message { - return &finishMessage{Message: m, finish: finish} -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/format/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/format/doc.go deleted file mode 100644 index 54c3f1a8c..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/binding/format/doc.go +++ /dev/null @@ -1,12 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -/* -Package format formats structured events. - -The "application/cloudevents+json" format is built-in and always -available. Other formats may be added. -*/ -package format diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/format/format.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/format/format.go deleted file mode 100644 index 6bdd1842b..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/binding/format/format.go +++ /dev/null @@ -1,105 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package format - -import ( - "encoding/json" - "errors" - "fmt" - "strings" - - "github.com/cloudevents/sdk-go/v2/event" -) - -// Format marshals and unmarshals structured events to bytes. -type Format interface { - // MediaType identifies the format - MediaType() string - // Marshal event to bytes - Marshal(*event.Event) ([]byte, error) - // Unmarshal bytes to event - Unmarshal([]byte, *event.Event) error -} - -// Prefix for event-format media types. -const Prefix = "application/cloudevents" - -// IsFormat returns true if mediaType begins with "application/cloudevents" -func IsFormat(mediaType string) bool { return strings.HasPrefix(mediaType, Prefix) } - -// JSON is the built-in "application/cloudevents+json" format. -var JSON = jsonFmt{} - -type jsonFmt struct{} - -func (jsonFmt) MediaType() string { return event.ApplicationCloudEventsJSON } - -func (jsonFmt) Marshal(e *event.Event) ([]byte, error) { return json.Marshal(e) } -func (jsonFmt) Unmarshal(b []byte, e *event.Event) error { - return json.Unmarshal(b, e) -} - -// JSONBatch is the built-in "application/cloudevents-batch+json" format. -var JSONBatch = jsonBatchFmt{} - -type jsonBatchFmt struct{} - -func (jb jsonBatchFmt) MediaType() string { - return event.ApplicationCloudEventsBatchJSON -} - -// Marshal will return an error for jsonBatchFmt since the Format interface doesn't support batch Marshalling, and we -// know it's structured batch json, we'll go direct to the json.UnMarshall() (see `ToEvents()`) since that is the best -// way to support batch operations for now. -func (jb jsonBatchFmt) Marshal(e *event.Event) ([]byte, error) { - return nil, errors.New("not supported for batch events") -} - -func (jb jsonBatchFmt) Unmarshal(b []byte, e *event.Event) error { - return errors.New("not supported for batch events") -} - -// built-in formats -var formats map[string]Format - -func init() { - formats = map[string]Format{} - Add(JSON) - Add(JSONBatch) -} - -// Lookup returns the format for contentType, or nil if not found. -func Lookup(contentType string) Format { - i := strings.IndexRune(contentType, ';') - if i == -1 { - i = len(contentType) - } - contentType = strings.TrimSpace(strings.ToLower(contentType[0:i])) - return formats[contentType] -} - -func unknown(mediaType string) error { - return fmt.Errorf("unknown event format media-type %#v", mediaType) -} - -// Add a new Format. It can be retrieved by Lookup(f.MediaType()) -func Add(f Format) { formats[f.MediaType()] = f } - -// Marshal an event to bytes using the mediaType event format. -func Marshal(mediaType string, e *event.Event) ([]byte, error) { - if f := formats[mediaType]; f != nil { - return f.Marshal(e) - } - return nil, unknown(mediaType) -} - -// Unmarshal bytes to an event using the mediaType event format. -func Unmarshal(mediaType string, b []byte, e *event.Event) error { - if f := formats[mediaType]; f != nil { - return f.Unmarshal(b, e) - } - return unknown(mediaType) -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/message.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/message.go deleted file mode 100644 index 2fb136c62..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/binding/message.go +++ /dev/null @@ -1,153 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package binding - -import ( - "context" - - "github.com/cloudevents/sdk-go/v2/binding/spec" -) - -// MessageReader defines the read-related portion of the Message interface. -// -// The ReadStructured and ReadBinary methods allows to perform an optimized encoding of a Message to a specific data structure. -// -// If MessageReader.ReadEncoding() can be equal to EncodingBinary, then the implementation of MessageReader -// MUST also implement MessageMetadataReader. -// -// A Sender should try each method of interest and fall back to binding.ToEvent() if none are supported. -// An out of the box algorithm is provided for writing a message: binding.Write(). -type MessageReader interface { - // Return the type of the message Encoding. - // The encoding should be preferably computed when the message is constructed. - ReadEncoding() Encoding - - // ReadStructured transfers a structured-mode event to a StructuredWriter. - // It must return ErrNotStructured if message is not in structured mode. - // - // Returns a different err if something wrong happened while trying to read the structured event. - // In this case, the caller must Finish the message with appropriate error. - // - // This allows Senders to avoid re-encoding messages that are - // already in suitable structured form. - ReadStructured(context.Context, StructuredWriter) error - - // ReadBinary transfers a binary-mode event to an BinaryWriter. - // It must return ErrNotBinary if message is not in binary mode. - // - // The implementation of ReadBinary must not control the lifecycle with BinaryWriter.Start() and BinaryWriter.End(), - // because the caller must control the lifecycle. - // - // Returns a different err if something wrong happened while trying to read the binary event - // In this case, the caller must Finish the message with appropriate error - // - // This allows Senders to avoid re-encoding messages that are - // already in suitable binary form. - ReadBinary(context.Context, BinaryWriter) error -} - -// MessageMetadataReader defines how to read metadata from a binary/event message -// -// If a message implementing MessageReader is encoded as binary (MessageReader.ReadEncoding() == EncodingBinary) -// or it's an EventMessage, then it's safe to assume that it also implements this interface -type MessageMetadataReader interface { - // GetAttribute returns: - // - // * attribute, value: if the message contains an attribute of that attribute kind - // * attribute, nil: if the message spec version supports the attribute kind, but doesn't have any value - // * nil, nil: if the message spec version doesn't support the attribute kind - GetAttribute(attributeKind spec.Kind) (spec.Attribute, interface{}) - // GetExtension returns the value of that extension, if any. - GetExtension(name string) interface{} -} - -// Message is the interface to a binding-specific message containing an event. -// -// # Reliable Delivery -// -// There are 3 reliable qualities of service for messages: -// -// 0/at-most-once/unreliable: messages can be dropped silently. -// -// 1/at-least-once: messages are not dropped without signaling an error -// to the sender, but they may be duplicated in the event of a re-send. -// -// 2/exactly-once: messages are never dropped (without error) or -// duplicated, as long as both sending and receiving ends maintain -// some binding-specific delivery state. Whether this is persisted -// depends on the configuration of the binding implementations. -// -// The Message interface supports QoS 0 and 1, the ExactlyOnceMessage interface -// supports QoS 2 -// -// Message includes the MessageReader interface to read messages. Every binding.Message implementation *must* specify if the message can be accessed one or more times. -// -// When a Message can be forgotten by the entity who produced the message, Message.Finish() *must* be invoked. -type Message interface { - MessageReader - - // Finish *must* be called when message from a Receiver can be forgotten by - // the receiver. A QoS 1 sender should not call Finish() until it gets an acknowledgment of - // receipt on the underlying transport. For QoS 2 see ExactlyOnceMessage. - // - // Note that, depending on the Message implementation, forgetting to Finish the message - // could produce memory/resources leaks! - // - // Passing a non-nil err indicates sending or processing failed. - // A non-nil return indicates that the message was not accepted - // by the receivers peer. - Finish(error) error -} - -// ExactlyOnceMessage is implemented by received Messages -// that support QoS 2. Only transports that support QoS 2 need to -// implement or use this interface. -type ExactlyOnceMessage interface { - Message - - // Received is called by a forwarding QoS2 Sender when it gets - // acknowledgment of receipt (e.g. AMQP 'accept' or MQTT PUBREC) - // - // The receiver must call settle(nil) when it get's the ack-of-ack - // (e.g. AMQP 'settle' or MQTT PUBCOMP) or settle(err) if the - // transfer fails. - // - // Finally the Sender calls Finish() to indicate the message can be - // discarded. - // - // If sending fails, or if the sender does not support QoS 2, then - // Finish() may be called without any call to Received() - Received(settle func(error)) -} - -// MessageContext interface exposes the internal context that a message might contain -// Only some Message implementations implement this interface. -type MessageContext interface { - // Get the context associated with this message - Context() context.Context -} - -// MessageWrapper interface is used to walk through a decorated Message and unwrap it. -type MessageWrapper interface { - Message - MessageMetadataReader - - // Method to get the wrapped message - GetWrappedMessage() Message -} - -func UnwrapMessage(message Message) Message { - m := message - for m != nil { - switch mt := m.(type) { - case MessageWrapper: - m = mt.GetWrappedMessage() - default: - return m - } - } - return m -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/attributes.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/attributes.go deleted file mode 100644 index 3c3021d46..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/attributes.go +++ /dev/null @@ -1,141 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package spec - -import ( - "fmt" - "time" - - "github.com/cloudevents/sdk-go/v2/event" - - "github.com/cloudevents/sdk-go/v2/types" -) - -// Kind is a version-independent identifier for a CloudEvent context attribute. -type Kind uint8 - -const ( - // Required cloudevents attributes - ID Kind = iota - Source - SpecVersion - Type - // Optional cloudevents attributes - DataContentType - DataSchema - Subject - Time -) -const nAttrs = int(Time) + 1 - -var kindNames = [nAttrs]string{ - "id", - "source", - "specversion", - "type", - "datacontenttype", - "dataschema", - "subject", - "time", -} - -// String is a human-readable string, for a valid attribute name use Attribute.Name -func (k Kind) String() string { return kindNames[k] } - -// IsRequired returns true for attributes defined as "required" by the CE spec. -func (k Kind) IsRequired() bool { return k < DataContentType } - -// Attribute is a named attribute accessor. -// The attribute name is specific to a Version. -type Attribute interface { - Kind() Kind - // Name of the attribute with respect to the current spec Version() with prefix - PrefixedName() string - // Name of the attribute with respect to the current spec Version() - Name() string - // Version of the spec that this attribute belongs to - Version() Version - // Get the value of this attribute from an event context - Get(event.EventContextReader) interface{} - // Set the value of this attribute on an event context - Set(event.EventContextWriter, interface{}) error - // Delete this attribute from and event context, when possible - Delete(event.EventContextWriter) error -} - -// accessor provides Kind, Get, Set. -type accessor interface { - Kind() Kind - Get(event.EventContextReader) interface{} - Set(event.EventContextWriter, interface{}) error - Delete(event.EventContextWriter) error -} - -var acc = [nAttrs]accessor{ - &aStr{aKind(ID), event.EventContextReader.GetID, event.EventContextWriter.SetID}, - &aStr{aKind(Source), event.EventContextReader.GetSource, event.EventContextWriter.SetSource}, - &aStr{aKind(SpecVersion), event.EventContextReader.GetSpecVersion, func(writer event.EventContextWriter, s string) error { return nil }}, - &aStr{aKind(Type), event.EventContextReader.GetType, event.EventContextWriter.SetType}, - &aStr{aKind(DataContentType), event.EventContextReader.GetDataContentType, event.EventContextWriter.SetDataContentType}, - &aStr{aKind(DataSchema), event.EventContextReader.GetDataSchema, event.EventContextWriter.SetDataSchema}, - &aStr{aKind(Subject), event.EventContextReader.GetSubject, event.EventContextWriter.SetSubject}, - &aTime{aKind(Time), event.EventContextReader.GetTime, event.EventContextWriter.SetTime}, -} - -// aKind implements Kind() -type aKind Kind - -func (kind aKind) Kind() Kind { return Kind(kind) } - -type aStr struct { - aKind - get func(event.EventContextReader) string - set func(event.EventContextWriter, string) error -} - -func (a *aStr) Get(c event.EventContextReader) interface{} { - if s := a.get(c); s != "" { - return s - } - return nil // Treat blank as missing -} - -func (a *aStr) Set(c event.EventContextWriter, v interface{}) error { - s, err := types.ToString(v) - if err != nil { - return fmt.Errorf("invalid value for %s: %#v", a.Kind(), v) - } - return a.set(c, s) -} - -func (a *aStr) Delete(c event.EventContextWriter) error { - return a.set(c, "") -} - -type aTime struct { - aKind - get func(event.EventContextReader) time.Time - set func(event.EventContextWriter, time.Time) error -} - -func (a *aTime) Get(c event.EventContextReader) interface{} { - if v := a.get(c); !v.IsZero() { - return v - } - return nil // Treat zero time as missing. -} - -func (a *aTime) Set(c event.EventContextWriter, v interface{}) error { - t, err := types.ToTime(v) - if err != nil { - return fmt.Errorf("invalid value for %s: %#v", a.Kind(), v) - } - return a.set(c, t) -} - -func (a *aTime) Delete(c event.EventContextWriter) error { - return a.set(c, time.Time{}) -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/doc.go deleted file mode 100644 index da5bc9f85..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/doc.go +++ /dev/null @@ -1,12 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -/* -Package spec provides spec-version metadata. - -For use by code that maps events using (prefixed) attribute name strings. -Supports handling multiple spec versions uniformly. -*/ -package spec diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/match_exact_version.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/match_exact_version.go deleted file mode 100644 index 110787ddc..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/match_exact_version.go +++ /dev/null @@ -1,81 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package spec - -import ( - "github.com/cloudevents/sdk-go/v2/event" -) - -type matchExactVersion struct { - version -} - -func (v *matchExactVersion) Attribute(name string) Attribute { return v.attrMap[name] } - -var _ Version = (*matchExactVersion)(nil) - -func newMatchExactVersionVersion( - prefix string, - attributeNameMatchMapper func(string) string, - context event.EventContext, - convert func(event.EventContextConverter) event.EventContext, - attrs ...*attribute, -) *matchExactVersion { - v := &matchExactVersion{ - version: version{ - prefix: prefix, - context: context, - convert: convert, - attrMap: map[string]Attribute{}, - attrs: make([]Attribute, len(attrs)), - }, - } - for i, a := range attrs { - a.version = v - v.attrs[i] = a - v.attrMap[attributeNameMatchMapper(a.name)] = a - } - return v -} - -// WithPrefixMatchExact returns a set of versions with prefix added to all attribute names. -func WithPrefixMatchExact(attributeNameMatchMapper func(string) string, prefix string) *Versions { - attr := func(name string, kind Kind) *attribute { - return &attribute{accessor: acc[kind], name: name} - } - vs := &Versions{ - m: map[string]Version{}, - prefix: prefix, - all: []Version{ - newMatchExactVersionVersion(prefix, attributeNameMatchMapper, event.EventContextV1{}.AsV1(), - func(c event.EventContextConverter) event.EventContext { return c.AsV1() }, - attr("id", ID), - attr("source", Source), - attr("specversion", SpecVersion), - attr("type", Type), - attr("datacontenttype", DataContentType), - attr("dataschema", DataSchema), - attr("subject", Subject), - attr("time", Time), - ), - newMatchExactVersionVersion(prefix, attributeNameMatchMapper, event.EventContextV03{}.AsV03(), - func(c event.EventContextConverter) event.EventContext { return c.AsV03() }, - attr("specversion", SpecVersion), - attr("type", Type), - attr("source", Source), - attr("schemaurl", DataSchema), - attr("subject", Subject), - attr("id", ID), - attr("time", Time), - attr("datacontenttype", DataContentType), - ), - }, - } - for _, v := range vs.all { - vs.m[v.String()] = v - } - return vs -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/spec.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/spec.go deleted file mode 100644 index 7fa0f5840..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/binding/spec/spec.go +++ /dev/null @@ -1,189 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package spec - -import ( - "strings" - - "github.com/cloudevents/sdk-go/v2/event" -) - -// Version provides meta-data for a single spec-version. -type Version interface { - // String name of the version, e.g. "1.0" - String() string - // Prefix for attribute names. - Prefix() string - // Attribute looks up a prefixed attribute name (case insensitive). - // Returns nil if not found. - Attribute(prefixedName string) Attribute - // Attribute looks up the attribute from kind. - // Returns nil if not found. - AttributeFromKind(kind Kind) Attribute - // Attributes returns all the context attributes for this version. - Attributes() []Attribute - // Convert translates a context to this version. - Convert(event.EventContextConverter) event.EventContext - // NewContext returns a new context for this version. - NewContext() event.EventContext - // SetAttribute sets named attribute to value. - // - // Name is case insensitive. - // Does nothing if name does not start with prefix. - SetAttribute(context event.EventContextWriter, name string, value interface{}) error -} - -// Versions contains all known versions with the same attribute prefix. -type Versions struct { - prefix string - all []Version - m map[string]Version -} - -// Versions returns the list of all known versions, most recent first. -func (vs *Versions) Versions() []Version { return vs.all } - -// Version returns the named version. -func (vs *Versions) Version(name string) Version { - return vs.m[name] -} - -// Latest returns the latest Version -func (vs *Versions) Latest() Version { return vs.all[0] } - -// PrefixedSpecVersionName returns the specversion attribute PrefixedName -func (vs *Versions) PrefixedSpecVersionName() string { return vs.prefix + "specversion" } - -// Prefix is the lowercase attribute name prefix. -func (vs *Versions) Prefix() string { return vs.prefix } - -type attribute struct { - accessor - name string - version Version -} - -func (a *attribute) PrefixedName() string { return a.version.Prefix() + a.name } -func (a *attribute) Name() string { return a.name } -func (a *attribute) Version() Version { return a.version } - -type version struct { - prefix string - context event.EventContext - convert func(event.EventContextConverter) event.EventContext - attrMap map[string]Attribute - attrs []Attribute -} - -func (v *version) Attribute(name string) Attribute { return v.attrMap[strings.ToLower(name)] } -func (v *version) Attributes() []Attribute { return v.attrs } -func (v *version) String() string { return v.context.GetSpecVersion() } -func (v *version) Prefix() string { return v.prefix } -func (v *version) NewContext() event.EventContext { return v.context.Clone() } - -// HasPrefix is a case-insensitive prefix check. -func (v *version) HasPrefix(name string) bool { - return strings.HasPrefix(strings.ToLower(name), v.prefix) -} - -func (v *version) Convert(c event.EventContextConverter) event.EventContext { return v.convert(c) } - -func (v *version) SetAttribute(c event.EventContextWriter, name string, value interface{}) error { - if a := v.Attribute(name); a != nil { // Standard attribute - return a.Set(c, value) - } - name = strings.ToLower(name) - var err error - if v.HasPrefix(name) { // Extension attribute - return c.SetExtension(strings.TrimPrefix(name, v.prefix), value) - } - return err -} - -func (v *version) AttributeFromKind(kind Kind) Attribute { - for _, a := range v.Attributes() { - if a.Kind() == kind { - return a - } - } - return nil -} - -func newVersion( - prefix string, - context event.EventContext, - convert func(event.EventContextConverter) event.EventContext, - attrs ...*attribute, -) *version { - v := &version{ - prefix: strings.ToLower(prefix), - context: context, - convert: convert, - attrMap: map[string]Attribute{}, - attrs: make([]Attribute, len(attrs)), - } - for i, a := range attrs { - a.version = v - v.attrs[i] = a - v.attrMap[strings.ToLower(a.PrefixedName())] = a - } - return v -} - -// WithPrefix returns a set of versions with prefix added to all attribute names. -func WithPrefix(prefix string) *Versions { - attr := func(name string, kind Kind) *attribute { - return &attribute{accessor: acc[kind], name: name} - } - vs := &Versions{ - m: map[string]Version{}, - prefix: prefix, - all: []Version{ - newVersion(prefix, event.EventContextV1{}.AsV1(), - func(c event.EventContextConverter) event.EventContext { return c.AsV1() }, - attr("id", ID), - attr("source", Source), - attr("specversion", SpecVersion), - attr("type", Type), - attr("datacontenttype", DataContentType), - attr("dataschema", DataSchema), - attr("subject", Subject), - attr("time", Time), - ), - newVersion(prefix, event.EventContextV03{}.AsV03(), - func(c event.EventContextConverter) event.EventContext { return c.AsV03() }, - attr("specversion", SpecVersion), - attr("type", Type), - attr("source", Source), - attr("schemaurl", DataSchema), - attr("subject", Subject), - attr("id", ID), - attr("time", Time), - attr("datacontenttype", DataContentType), - ), - }, - } - for _, v := range vs.all { - vs.m[v.String()] = v - } - return vs -} - -// New returns a set of versions -func New() *Versions { return WithPrefix("") } - -// Built-in un-prefixed versions. -var ( - VS *Versions - V03 Version - V1 Version -) - -func init() { - VS = New() - V03 = VS.Version("0.3") - V1 = VS.Version("1.0") -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/structured_writer.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/structured_writer.go deleted file mode 100644 index 60256f2b3..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/binding/structured_writer.go +++ /dev/null @@ -1,22 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package binding - -import ( - "context" - "io" - - "github.com/cloudevents/sdk-go/v2/binding/format" -) - -// StructuredWriter is used to visit a structured Message and generate a new representation. -// -// Protocols that supports structured encoding should implement this interface to implement direct -// structured to structured encoding and event to structured encoding. -type StructuredWriter interface { - // Event receives an io.Reader for the whole event. - SetStructuredEvent(ctx context.Context, format format.Format, event io.Reader) error -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/to_event.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/to_event.go deleted file mode 100644 index d3332c158..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/binding/to_event.go +++ /dev/null @@ -1,153 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package binding - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - - "github.com/cloudevents/sdk-go/v2/binding/format" - "github.com/cloudevents/sdk-go/v2/binding/spec" - "github.com/cloudevents/sdk-go/v2/event" - "github.com/cloudevents/sdk-go/v2/types" -) - -// ErrCannotConvertToEvent is a generic error when a conversion of a Message to an Event fails -var ErrCannotConvertToEvent = errors.New("cannot convert message to event") - -// ErrCannotConvertToEvents is a generic error when a conversion of a Message to a Batched Event fails -var ErrCannotConvertToEvents = errors.New("cannot convert message to batched events") - -// ToEvent translates a Message with a valid Structured or Binary representation to an Event. -// This function returns the Event generated from the Message and the original encoding of the message or -// an error that points the conversion error. -// transformers can be nil and this function guarantees that they are invoked only once during the encoding process. -func ToEvent(ctx context.Context, message MessageReader, transformers ...Transformer) (*event.Event, error) { - if message == nil { - return nil, nil - } - - messageEncoding := message.ReadEncoding() - if messageEncoding == EncodingEvent { - m := message - for m != nil { - switch mt := m.(type) { - case *EventMessage: - e := (*event.Event)(mt) - return e, Transformers(transformers).Transform(mt, (*messageToEventBuilder)(e)) - case MessageWrapper: - m = mt.GetWrappedMessage() - default: - break - } - } - return nil, ErrCannotConvertToEvent - } - - e := event.New() - encoder := (*messageToEventBuilder)(&e) - _, err := DirectWrite( - context.Background(), - message, - encoder, - encoder, - ) - if err != nil { - return nil, err - } - return &e, Transformers(transformers).Transform((*EventMessage)(&e), encoder) -} - -// ToEvents translates a Batch Message and corresponding Reader data to a slice of Events. -// This function returns the Events generated from the body data, or an error that points -// to the conversion issue. -func ToEvents(ctx context.Context, message MessageReader, body io.Reader) ([]event.Event, error) { - messageEncoding := message.ReadEncoding() - if messageEncoding != EncodingBatch { - return nil, ErrCannotConvertToEvents - } - - // Since Format doesn't support batch Marshalling, and we know it's structured batch json, we'll go direct to the - // json.UnMarshall(), since that is the best way to support batch operations for now. - var events []event.Event - return events, json.NewDecoder(body).Decode(&events) -} - -type messageToEventBuilder event.Event - -var _ StructuredWriter = (*messageToEventBuilder)(nil) -var _ BinaryWriter = (*messageToEventBuilder)(nil) - -func (b *messageToEventBuilder) SetStructuredEvent(ctx context.Context, format format.Format, ev io.Reader) error { - var buf bytes.Buffer - _, err := io.Copy(&buf, ev) - if err != nil { - return err - } - return format.Unmarshal(buf.Bytes(), (*event.Event)(b)) -} - -func (b *messageToEventBuilder) Start(ctx context.Context) error { - return nil -} - -func (b *messageToEventBuilder) End(ctx context.Context) error { - return nil -} - -func (b *messageToEventBuilder) SetData(data io.Reader) error { - buf, ok := data.(*bytes.Buffer) - if !ok { - buf = new(bytes.Buffer) - _, err := io.Copy(buf, data) - if err != nil { - return err - } - } - if buf.Len() > 0 { - b.DataEncoded = buf.Bytes() - } - return nil -} - -func (b *messageToEventBuilder) SetAttribute(attribute spec.Attribute, value interface{}) error { - if value == nil { - _ = attribute.Delete(b.Context) - return nil - } - // If spec version we need to change to right context struct - if attribute.Kind() == spec.SpecVersion { - str, err := types.ToString(value) - if err != nil { - return err - } - switch str { - case event.CloudEventsVersionV03: - b.Context = b.Context.AsV03() - case event.CloudEventsVersionV1: - b.Context = b.Context.AsV1() - default: - return fmt.Errorf("unrecognized event version %s", str) - } - return nil - } - return attribute.Set(b.Context, value) -} - -func (b *messageToEventBuilder) SetExtension(name string, value interface{}) error { - if value == nil { - return b.Context.SetExtension(name, nil) - } - value, err := types.Validate(value) - if err != nil { - return err - } - return b.Context.SetExtension(name, value) -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/transformer.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/transformer.go deleted file mode 100644 index de3bec44f..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/binding/transformer.go +++ /dev/null @@ -1,42 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package binding - -// Transformer is an interface that implements a transformation -// process while transferring the event from the Message -// implementation to the provided encoder -// -// When a write function (binding.Write, binding.ToEvent, buffering.CopyMessage, etc.) -// takes Transformer(s) as parameter, it eventually converts the message to a form -// which correctly implements MessageMetadataReader, in order to guarantee that transformation -// is applied -type Transformer interface { - Transform(MessageMetadataReader, MessageMetadataWriter) error -} - -// TransformerFunc is a type alias to implement a Transformer through a function pointer -type TransformerFunc func(MessageMetadataReader, MessageMetadataWriter) error - -func (t TransformerFunc) Transform(r MessageMetadataReader, w MessageMetadataWriter) error { - return t(r, w) -} - -var _ Transformer = (TransformerFunc)(nil) - -// Transformers is a utility alias to run several Transformer -type Transformers []Transformer - -func (t Transformers) Transform(r MessageMetadataReader, w MessageMetadataWriter) error { - for _, transformer := range t { - err := transformer.Transform(r, w) - if err != nil { - return err - } - } - return nil -} - -var _ Transformer = (Transformers)(nil) diff --git a/vendor/github.com/cloudevents/sdk-go/v2/binding/write.go b/vendor/github.com/cloudevents/sdk-go/v2/binding/write.go deleted file mode 100644 index cb498e62d..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/binding/write.go +++ /dev/null @@ -1,179 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package binding - -import ( - "context" - - "github.com/cloudevents/sdk-go/v2/event" -) - -type eventEncodingKey int - -const ( - skipDirectStructuredEncoding eventEncodingKey = iota - skipDirectBinaryEncoding - preferredEventEncoding -) - -// DirectWrite invokes the encoders. structuredWriter and binaryWriter could be nil if the protocol doesn't support it. -// transformers can be nil and this function guarantees that they are invoked only once during the encoding process. -// This function MUST be invoked only if message.ReadEncoding() == EncodingBinary or message.ReadEncoding() == EncodingStructured -// -// Returns: -// * EncodingStructured, nil if message is correctly encoded in structured encoding -// * EncodingBinary, nil if message is correctly encoded in binary encoding -// * EncodingStructured, err if message was structured but error happened during the encoding -// * EncodingBinary, err if message was binary but error happened during the encoding -// * EncodingUnknown, ErrUnknownEncoding if message is not a structured or a binary Message -func DirectWrite( - ctx context.Context, - message MessageReader, - structuredWriter StructuredWriter, - binaryWriter BinaryWriter, - transformers ...Transformer, -) (Encoding, error) { - if structuredWriter != nil && len(transformers) == 0 && !GetOrDefaultFromCtx(ctx, skipDirectStructuredEncoding, false).(bool) { - if err := message.ReadStructured(ctx, structuredWriter); err == nil { - return EncodingStructured, nil - } else if err != ErrNotStructured { - return EncodingStructured, err - } - } - - if binaryWriter != nil && !GetOrDefaultFromCtx(ctx, skipDirectBinaryEncoding, false).(bool) && message.ReadEncoding() == EncodingBinary { - return EncodingBinary, writeBinaryWithTransformer(ctx, message, binaryWriter, transformers) - } - - return EncodingUnknown, ErrUnknownEncoding -} - -// Write executes the full algorithm to encode a Message using transformers: -// 1. It first tries direct encoding using DirectWrite -// 2. If no direct encoding is possible, it uses ToEvent to generate an Event representation -// 3. From the Event, the message is encoded back to the provided structured or binary encoders -// You can tweak the encoding process using the context decorators WithForceStructured, WithForceStructured, etc. -// transformers can be nil and this function guarantees that they are invoked only once during the encoding process. -// Returns: -// * EncodingStructured, nil if message is correctly encoded in structured encoding -// * EncodingBinary, nil if message is correctly encoded in binary encoding -// * EncodingUnknown, ErrUnknownEncoding if message.ReadEncoding() == EncodingUnknown -// * _, err if error happened during the encoding -func Write( - ctx context.Context, - message MessageReader, - structuredWriter StructuredWriter, - binaryWriter BinaryWriter, - transformers ...Transformer, -) (Encoding, error) { - enc := message.ReadEncoding() - var err error - // Skip direct encoding if the event is an event message - if enc != EncodingEvent { - enc, err = DirectWrite(ctx, message, structuredWriter, binaryWriter, transformers...) - if enc != EncodingUnknown { - // Message directly encoded, nothing else to do here - return enc, err - } - } - - var e *event.Event - e, err = ToEvent(ctx, message, transformers...) - if err != nil { - return enc, err - } - - message = (*EventMessage)(e) - - if GetOrDefaultFromCtx(ctx, preferredEventEncoding, EncodingBinary).(Encoding) == EncodingStructured { - if structuredWriter != nil { - return EncodingStructured, message.ReadStructured(ctx, structuredWriter) - } - if binaryWriter != nil { - return EncodingBinary, writeBinary(ctx, message, binaryWriter) - } - } else { - if binaryWriter != nil { - return EncodingBinary, writeBinary(ctx, message, binaryWriter) - } - if structuredWriter != nil { - return EncodingStructured, message.ReadStructured(ctx, structuredWriter) - } - } - - return EncodingUnknown, ErrUnknownEncoding -} - -// WithSkipDirectStructuredEncoding skips direct structured to structured encoding during the encoding process -func WithSkipDirectStructuredEncoding(ctx context.Context, skip bool) context.Context { - return context.WithValue(ctx, skipDirectStructuredEncoding, skip) -} - -// WithSkipDirectBinaryEncoding skips direct binary to binary encoding during the encoding process -func WithSkipDirectBinaryEncoding(ctx context.Context, skip bool) context.Context { - return context.WithValue(ctx, skipDirectBinaryEncoding, skip) -} - -// WithPreferredEventEncoding defines the preferred encoding from event to message during the encoding process -func WithPreferredEventEncoding(ctx context.Context, enc Encoding) context.Context { - return context.WithValue(ctx, preferredEventEncoding, enc) -} - -// WithForceStructured forces structured encoding during the encoding process -func WithForceStructured(ctx context.Context) context.Context { - return context.WithValue(context.WithValue(ctx, preferredEventEncoding, EncodingStructured), skipDirectBinaryEncoding, true) -} - -// WithForceBinary forces binary encoding during the encoding process -func WithForceBinary(ctx context.Context) context.Context { - return context.WithValue(context.WithValue(ctx, preferredEventEncoding, EncodingBinary), skipDirectStructuredEncoding, true) -} - -// GetOrDefaultFromCtx gets a configuration value from the provided context -func GetOrDefaultFromCtx(ctx context.Context, key interface{}, def interface{}) interface{} { - if val := ctx.Value(key); val != nil { - return val - } else { - return def - } -} - -func writeBinaryWithTransformer( - ctx context.Context, - message MessageReader, - binaryWriter BinaryWriter, - transformers Transformers, -) error { - err := binaryWriter.Start(ctx) - if err != nil { - return err - } - err = message.ReadBinary(ctx, binaryWriter) - if err != nil { - return err - } - err = transformers.Transform(message.(MessageMetadataReader), binaryWriter) - if err != nil { - return err - } - return binaryWriter.End(ctx) -} - -func writeBinary( - ctx context.Context, - message MessageReader, - binaryWriter BinaryWriter, -) error { - err := binaryWriter.Start(ctx) - if err != nil { - return err - } - err = message.ReadBinary(ctx, binaryWriter) - if err != nil { - return err - } - return binaryWriter.End(ctx) -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/client/client.go b/vendor/github.com/cloudevents/sdk-go/v2/client/client.go deleted file mode 100644 index 452304ffd..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/client/client.go +++ /dev/null @@ -1,295 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package client - -import ( - "context" - "errors" - "fmt" - "io" - "runtime" - "sync" - - "go.uber.org/zap" - - "github.com/cloudevents/sdk-go/v2/binding" - cecontext "github.com/cloudevents/sdk-go/v2/context" - "github.com/cloudevents/sdk-go/v2/event" - "github.com/cloudevents/sdk-go/v2/protocol" -) - -// Client interface defines the runtime contract the CloudEvents client supports. -type Client interface { - // Send will transmit the given event over the client's configured transport. - Send(ctx context.Context, event event.Event) protocol.Result - - // Request will transmit the given event over the client's configured - // transport and return any response event. - Request(ctx context.Context, event event.Event) (*event.Event, protocol.Result) - - // StartReceiver will register the provided function for callback on receipt - // of a cloudevent. It will also start the underlying protocol as it has - // been configured. - // This call is blocking. - // Valid fn signatures are: - // * func() - // * func() error - // * func(context.Context) - // * func(context.Context) protocol.Result - // * func(event.Event) - // * func(event.Event) protocol.Result - // * func(context.Context, event.Event) - // * func(context.Context, event.Event) protocol.Result - // * func(event.Event) *event.Event - // * func(event.Event) (*event.Event, protocol.Result) - // * func(context.Context, event.Event) *event.Event - // * func(context.Context, event.Event) (*event.Event, protocol.Result) - StartReceiver(ctx context.Context, fn interface{}) error -} - -// New produces a new client with the provided transport object and applied -// client options. -func New(obj interface{}, opts ...Option) (Client, error) { - c := &ceClient{ - // Running runtime.GOMAXPROCS(0) doesn't update the value, just returns the current one - pollGoroutines: runtime.GOMAXPROCS(0), - observabilityService: noopObservabilityService{}, - } - - if p, ok := obj.(protocol.Sender); ok { - c.sender = p - } - if p, ok := obj.(protocol.Requester); ok { - c.requester = p - } - if p, ok := obj.(protocol.Responder); ok { - c.responder = p - } - if p, ok := obj.(protocol.Receiver); ok { - c.receiver = p - } - if p, ok := obj.(protocol.Opener); ok { - c.opener = p - } - - if err := c.applyOptions(opts...); err != nil { - return nil, err - } - return c, nil -} - -type ceClient struct { - sender protocol.Sender - requester protocol.Requester - receiver protocol.Receiver - responder protocol.Responder - // Optional. - opener protocol.Opener - - observabilityService ObservabilityService - - inboundContextDecorators []func(context.Context, binding.Message) context.Context - outboundContextDecorators []func(context.Context) context.Context - invoker Invoker - receiverMu sync.Mutex - eventDefaulterFns []EventDefaulter - pollGoroutines int - blockingCallback bool - ackMalformedEvent bool -} - -func (c *ceClient) applyOptions(opts ...Option) error { - for _, fn := range opts { - if err := fn(c); err != nil { - return err - } - } - return nil -} - -func (c *ceClient) Send(ctx context.Context, e event.Event) protocol.Result { - var err error - if c.sender == nil { - err = errors.New("sender not set") - return err - } - - for _, f := range c.outboundContextDecorators { - ctx = f(ctx) - } - - if len(c.eventDefaulterFns) > 0 { - for _, fn := range c.eventDefaulterFns { - e = fn(ctx, e) - } - } - if err = e.Validate(); err != nil { - return err - } - - // Event has been defaulted and validated, record we are going to perform send. - ctx, cb := c.observabilityService.RecordSendingEvent(ctx, e) - err = c.sender.Send(ctx, (*binding.EventMessage)(&e)) - defer cb(err) - return err -} - -func (c *ceClient) Request(ctx context.Context, e event.Event) (*event.Event, protocol.Result) { - var resp *event.Event - var err error - - if c.requester == nil { - err = errors.New("requester not set") - return nil, err - } - for _, f := range c.outboundContextDecorators { - ctx = f(ctx) - } - - if len(c.eventDefaulterFns) > 0 { - for _, fn := range c.eventDefaulterFns { - e = fn(ctx, e) - } - } - - if err = e.Validate(); err != nil { - return nil, err - } - - // Event has been defaulted and validated, record we are going to perform request. - ctx, cb := c.observabilityService.RecordRequestEvent(ctx, e) - - // If provided a requester, use it to do request/response. - var msg binding.Message - msg, err = c.requester.Request(ctx, (*binding.EventMessage)(&e)) - if msg != nil { - defer func() { - if err := msg.Finish(err); err != nil { - cecontext.LoggerFrom(ctx).Warnw("failed calling message.Finish", zap.Error(err)) - } - }() - } - if protocol.IsUndelivered(err) { - return nil, err - } - - // try to turn msg into an event, it might not work and that is ok. - if rs, rserr := binding.ToEvent(ctx, msg); rserr != nil { - cecontext.LoggerFrom(ctx).Debugw("response: failed calling ToEvent", zap.Error(rserr), zap.Any("resp", msg)) - // If the protocol returns no error, it is an ACK on the request, but we had - // issues turning the response into an event, so make an ACK Result and pass - // down the ToEvent error as well. - err = protocol.NewReceipt(true, "failed to convert response into event: %v\n%w", rserr, err) - } else { - resp = rs - } - defer cb(err, resp) - return resp, err -} - -// StartReceiver sets up the given fn to handle Receive. -// See Client.StartReceiver for details. This is a blocking call. -func (c *ceClient) StartReceiver(ctx context.Context, fn interface{}) error { - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - c.receiverMu.Lock() - defer c.receiverMu.Unlock() - - if c.invoker != nil { - return fmt.Errorf("client already has a receiver") - } - - invoker, err := newReceiveInvoker( - fn, - c.observabilityService, - c.inboundContextDecorators, - c.eventDefaulterFns, - c.ackMalformedEvent, - ) - if err != nil { - return err - } - if invoker.IsReceiver() && c.receiver == nil { - return fmt.Errorf("mismatched receiver callback without protocol.Receiver supported by protocol") - } - if invoker.IsResponder() && c.responder == nil { - return fmt.Errorf("mismatched receiver callback without protocol.Responder supported by protocol") - } - c.invoker = invoker - - if c.responder == nil && c.receiver == nil { - return errors.New("responder nor receiver set") - } - - defer func() { - c.invoker = nil - }() - - // Start Polling. - wg := sync.WaitGroup{} - for i := 0; i < c.pollGoroutines; i++ { - wg.Add(1) - go func() { - defer wg.Done() - for { - var msg binding.Message - var respFn protocol.ResponseFn - var err error - - if c.responder != nil { - msg, respFn, err = c.responder.Respond(ctx) - } else if c.receiver != nil { - msg, err = c.receiver.Receive(ctx) - respFn = noRespFn - } - - if err == io.EOF { // Normal close - return - } - - if err != nil { - cecontext.LoggerFrom(ctx).Warn("Error while receiving a message: ", err) - continue - } - - callback := func() { - if err := c.invoker.Invoke(ctx, msg, respFn); err != nil { - cecontext.LoggerFrom(ctx).Warn("Error while handling a message: ", err) - } - } - - if c.blockingCallback { - callback() - } else { - // Do not block on the invoker. - wg.Add(1) - go func() { - defer wg.Done() - callback() - }() - } - } - }() - } - - // Start the opener, if set. - if c.opener != nil { - if err = c.opener.OpenInbound(ctx); err != nil { - err = fmt.Errorf("error while opening the inbound connection: %w", err) - cancel() - } - } - - wg.Wait() - - return err -} - -// noRespFn is used to simply forward the protocol.Result for receivers that aren't responders -func noRespFn(_ context.Context, _ binding.Message, r protocol.Result, _ ...binding.Transformer) error { - return r -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/client/client_http.go b/vendor/github.com/cloudevents/sdk-go/v2/client/client_http.go deleted file mode 100644 index d48cc2042..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/client/client_http.go +++ /dev/null @@ -1,35 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package client - -import ( - "github.com/cloudevents/sdk-go/v2/protocol/http" -) - -// NewHTTP provides the good defaults for the common case using an HTTP -// Protocol client. -// The WithTimeNow, and WithUUIDs client options are also applied to the -// client, all outbound events will have a time and id set if not already -// present. -func NewHTTP(opts ...http.Option) (Client, error) { - p, err := http.New(opts...) - if err != nil { - return nil, err - } - - c, err := New(p, WithTimeNow(), WithUUIDs()) - if err != nil { - return nil, err - } - - return c, nil -} - -// NewDefault has been replaced by NewHTTP -// Deprecated. To get the same as NewDefault provided, please use NewHTTP with -// the observability service passed as an option, or client.NewClientHTTP from -// package github.com/cloudevents/sdk-go/observability/opencensus/v2/client -var NewDefault = NewHTTP diff --git a/vendor/github.com/cloudevents/sdk-go/v2/client/client_observed.go b/vendor/github.com/cloudevents/sdk-go/v2/client/client_observed.go deleted file mode 100644 index 82985b8a7..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/client/client_observed.go +++ /dev/null @@ -1,12 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package client - -// NewObserved produces a new client with the provided transport object and applied -// client options. -// Deprecated: This now has the same behaviour of New, and will be removed in future releases. -// As New, you must provide the observability service to use. -var NewObserved = New diff --git a/vendor/github.com/cloudevents/sdk-go/v2/client/defaulters.go b/vendor/github.com/cloudevents/sdk-go/v2/client/defaulters.go deleted file mode 100644 index 7bfebf35c..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/client/defaulters.go +++ /dev/null @@ -1,57 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package client - -import ( - "context" - "time" - - "github.com/cloudevents/sdk-go/v2/event" - - "github.com/google/uuid" -) - -// EventDefaulter is the function signature for extensions that are able -// to perform event defaulting. -type EventDefaulter func(ctx context.Context, event event.Event) event.Event - -// DefaultIDToUUIDIfNotSet will inspect the provided event and assign a UUID to -// context.ID if it is found to be empty. -func DefaultIDToUUIDIfNotSet(ctx context.Context, event event.Event) event.Event { - if event.Context != nil { - if event.ID() == "" { - event.Context = event.Context.Clone() - event.SetID(uuid.New().String()) - } - } - return event -} - -// DefaultTimeToNowIfNotSet will inspect the provided event and assign a new -// Timestamp to context.Time if it is found to be nil or zero. -func DefaultTimeToNowIfNotSet(ctx context.Context, event event.Event) event.Event { - if event.Context != nil { - if event.Time().IsZero() { - event.Context = event.Context.Clone() - event.SetTime(time.Now()) - } - } - return event -} - -// NewDefaultDataContentTypeIfNotSet returns a defaulter that will inspect the -// provided event and set the provided content type if content type is found -// to be empty. -func NewDefaultDataContentTypeIfNotSet(contentType string) EventDefaulter { - return func(ctx context.Context, event event.Event) event.Event { - if event.Context != nil { - if event.DataContentType() == "" { - event.SetDataContentType(contentType) - } - } - return event - } -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/client/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/client/doc.go deleted file mode 100644 index e09962ce6..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/client/doc.go +++ /dev/null @@ -1,11 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -/* -Package client holds the recommended entry points for interacting with the CloudEvents Golang SDK. The client wraps -a selected transport. The client adds validation and defaulting for sending events, and flexible receiver method -registration. For full details, read the `client.Client` documentation. -*/ -package client diff --git a/vendor/github.com/cloudevents/sdk-go/v2/client/http_receiver.go b/vendor/github.com/cloudevents/sdk-go/v2/client/http_receiver.go deleted file mode 100644 index 672581b58..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/client/http_receiver.go +++ /dev/null @@ -1,45 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package client - -import ( - "context" - cecontext "github.com/cloudevents/sdk-go/v2/context" - thttp "github.com/cloudevents/sdk-go/v2/protocol/http" - "go.uber.org/zap" - "net/http" -) - -func NewHTTPReceiveHandler(ctx context.Context, p *thttp.Protocol, fn interface{}) (*EventReceiver, error) { - invoker, err := newReceiveInvoker(fn, noopObservabilityService{}, nil, nil, false) //TODO(slinkydeveloper) maybe not nil? - if err != nil { - return nil, err - } - - return &EventReceiver{ - p: p, - invoker: invoker, - }, nil -} - -type EventReceiver struct { - p *thttp.Protocol - invoker Invoker -} - -func (r *EventReceiver) ServeHTTP(rw http.ResponseWriter, req *http.Request) { - // Prepare to handle the message if there's one (context cancellation will ensure this closes) - go func() { - ctx := req.Context() - msg, respFn, err := r.p.Respond(ctx) - if err != nil { - cecontext.LoggerFrom(context.TODO()).Debugw("failed to call Respond", zap.Error(err)) - } else if err := r.invoker.Invoke(ctx, msg, respFn); err != nil { - cecontext.LoggerFrom(context.TODO()).Debugw("failed to call Invoke", zap.Error(err)) - } - }() - r.p.ServeHTTP(rw, req) -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/client/invoker.go b/vendor/github.com/cloudevents/sdk-go/v2/client/invoker.go deleted file mode 100644 index a3080b007..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/client/invoker.go +++ /dev/null @@ -1,145 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package client - -import ( - "context" - "fmt" - - "github.com/cloudevents/sdk-go/v2/binding" - cecontext "github.com/cloudevents/sdk-go/v2/context" - "github.com/cloudevents/sdk-go/v2/event" - "github.com/cloudevents/sdk-go/v2/protocol" -) - -type Invoker interface { - Invoke(context.Context, binding.Message, protocol.ResponseFn) error - IsReceiver() bool - IsResponder() bool -} - -var _ Invoker = (*receiveInvoker)(nil) - -func newReceiveInvoker( - fn interface{}, - observabilityService ObservabilityService, - inboundContextDecorators []func(context.Context, binding.Message) context.Context, - fns []EventDefaulter, - ackMalformedEvent bool, -) (Invoker, error) { - r := &receiveInvoker{ - eventDefaulterFns: fns, - observabilityService: observabilityService, - inboundContextDecorators: inboundContextDecorators, - ackMalformedEvent: ackMalformedEvent, - } - - if fn, err := receiver(fn); err != nil { - return nil, err - } else { - r.fn = fn - } - - return r, nil -} - -type receiveInvoker struct { - fn *receiverFn - observabilityService ObservabilityService - eventDefaulterFns []EventDefaulter - inboundContextDecorators []func(context.Context, binding.Message) context.Context - ackMalformedEvent bool -} - -func (r *receiveInvoker) Invoke(ctx context.Context, m binding.Message, respFn protocol.ResponseFn) (err error) { - defer func() { - err = m.Finish(err) - }() - - var respMsg binding.Message - var result protocol.Result - - e, eventErr := binding.ToEvent(ctx, m) - switch { - case eventErr != nil && r.fn.hasEventIn: - r.observabilityService.RecordReceivedMalformedEvent(ctx, eventErr) - return respFn(ctx, nil, protocol.NewReceipt(r.ackMalformedEvent, "failed to convert Message to Event: %w", eventErr)) - case r.fn != nil: - // Check if event is valid before invoking the receiver function - if e != nil { - if validationErr := e.Validate(); validationErr != nil { - r.observabilityService.RecordReceivedMalformedEvent(ctx, validationErr) - return respFn(ctx, nil, protocol.NewReceipt(r.ackMalformedEvent, "validation error in incoming event: %w", validationErr)) - } - } - - // Let's invoke the receiver fn - var resp *event.Event - resp, result = func() (resp *event.Event, result protocol.Result) { - defer func() { - if r := recover(); r != nil { - result = fmt.Errorf("call to Invoker.Invoke(...) has panicked: %v", r) - cecontext.LoggerFrom(ctx).Error(result) - } - }() - ctx = computeInboundContext(m, ctx, r.inboundContextDecorators) - - var cb func(error) - ctx, cb = r.observabilityService.RecordCallingInvoker(ctx, e) - - resp, result = r.fn.invoke(ctx, e) - defer cb(result) - return - }() - - if respFn == nil { - break - } - - // Apply the defaulter chain to the outgoing event. - if resp != nil && len(r.eventDefaulterFns) > 0 { - for _, fn := range r.eventDefaulterFns { - *resp = fn(ctx, *resp) - } - // Validate the event conforms to the CloudEvents Spec. - if vErr := resp.Validate(); vErr != nil { - cecontext.LoggerFrom(ctx).Errorf("cloudevent validation failed on response event: %v", vErr) - } - } - - // because binding.Message is an interface, casting a nil resp - // here would make future comparisons to nil false - if resp != nil { - respMsg = (*binding.EventMessage)(resp) - } - } - - if respFn == nil { - // let the protocol ACK based on the result - return result - } - - return respFn(ctx, respMsg, result) -} - -func (r *receiveInvoker) IsReceiver() bool { - return !r.fn.hasEventOut -} - -func (r *receiveInvoker) IsResponder() bool { - return r.fn.hasEventOut -} - -func computeInboundContext(message binding.Message, fallback context.Context, inboundContextDecorators []func(context.Context, binding.Message) context.Context) context.Context { - result := fallback - if mctx, ok := message.(binding.MessageContext); ok { - result = cecontext.ValuesDelegating(mctx.Context(), fallback) - } - for _, f := range inboundContextDecorators { - result = f(result, message) - } - return result -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/client/observability.go b/vendor/github.com/cloudevents/sdk-go/v2/client/observability.go deleted file mode 100644 index 75005d3bb..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/client/observability.go +++ /dev/null @@ -1,54 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package client - -import ( - "context" - - "github.com/cloudevents/sdk-go/v2/binding" - "github.com/cloudevents/sdk-go/v2/event" -) - -// ObservabilityService is an interface users can implement to record metrics, create tracing spans, and plug other observability tools in the Client -type ObservabilityService interface { - // InboundContextDecorators is a method that returns the InboundContextDecorators that must be mounted in the Client to properly propagate some tracing informations. - InboundContextDecorators() []func(context.Context, binding.Message) context.Context - - // RecordReceivedMalformedEvent is invoked when an event was received but it's malformed or invalid. - RecordReceivedMalformedEvent(ctx context.Context, err error) - // RecordCallingInvoker is invoked before the user function is invoked. - // The returned callback will be invoked after the user finishes to process the event with the eventual processing error - // The error provided to the callback could be both a processing error, or a result - RecordCallingInvoker(ctx context.Context, event *event.Event) (context.Context, func(errOrResult error)) - // RecordSendingEvent is invoked before the event is sent. - // The returned callback will be invoked when the response is received - // The error provided to the callback could be both a processing error, or a result - RecordSendingEvent(ctx context.Context, event event.Event) (context.Context, func(errOrResult error)) - - // RecordRequestEvent is invoked before the event is requested. - // The returned callback will be invoked when the response is received - RecordRequestEvent(ctx context.Context, event event.Event) (context.Context, func(errOrResult error, event *event.Event)) -} - -type noopObservabilityService struct{} - -func (n noopObservabilityService) InboundContextDecorators() []func(context.Context, binding.Message) context.Context { - return nil -} - -func (n noopObservabilityService) RecordReceivedMalformedEvent(ctx context.Context, err error) {} - -func (n noopObservabilityService) RecordCallingInvoker(ctx context.Context, event *event.Event) (context.Context, func(errOrResult error)) { - return ctx, func(errOrResult error) {} -} - -func (n noopObservabilityService) RecordSendingEvent(ctx context.Context, event event.Event) (context.Context, func(errOrResult error)) { - return ctx, func(errOrResult error) {} -} - -func (n noopObservabilityService) RecordRequestEvent(ctx context.Context, e event.Event) (context.Context, func(errOrResult error, event *event.Event)) { - return ctx, func(errOrResult error, event *event.Event) {} -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/client/options.go b/vendor/github.com/cloudevents/sdk-go/v2/client/options.go deleted file mode 100644 index 44394be34..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/client/options.go +++ /dev/null @@ -1,141 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package client - -import ( - "context" - "fmt" - - "github.com/cloudevents/sdk-go/v2/binding" -) - -// Option is the function signature required to be considered an client.Option. -type Option func(interface{}) error - -// WithEventDefaulter adds an event defaulter to the end of the defaulter chain. -func WithEventDefaulter(fn EventDefaulter) Option { - return func(i interface{}) error { - if c, ok := i.(*ceClient); ok { - if fn == nil { - return fmt.Errorf("client option was given an nil event defaulter") - } - c.eventDefaulterFns = append(c.eventDefaulterFns, fn) - } - return nil - } -} - -func WithForceBinary() Option { - return func(i interface{}) error { - if c, ok := i.(*ceClient); ok { - c.outboundContextDecorators = append(c.outboundContextDecorators, binding.WithForceBinary) - } - return nil - } -} - -func WithForceStructured() Option { - return func(i interface{}) error { - if c, ok := i.(*ceClient); ok { - c.outboundContextDecorators = append(c.outboundContextDecorators, binding.WithForceStructured) - } - return nil - } -} - -// WithUUIDs adds DefaultIDToUUIDIfNotSet event defaulter to the end of the -// defaulter chain. -func WithUUIDs() Option { - return func(i interface{}) error { - if c, ok := i.(*ceClient); ok { - c.eventDefaulterFns = append(c.eventDefaulterFns, DefaultIDToUUIDIfNotSet) - } - return nil - } -} - -// WithTimeNow adds DefaultTimeToNowIfNotSet event defaulter to the end of the -// defaulter chain. -func WithTimeNow() Option { - return func(i interface{}) error { - if c, ok := i.(*ceClient); ok { - c.eventDefaulterFns = append(c.eventDefaulterFns, DefaultTimeToNowIfNotSet) - } - return nil - } -} - -// WithTracePropagation enables trace propagation via the distributed tracing -// extension. -// Deprecated: this is now noop and will be removed in future releases. -// Don't use distributed tracing extension to propagate traces: -// https://github.com/cloudevents/spec/blob/v1.0.1/extensions/distributed-tracing.md#using-the-distributed-tracing-extension -func WithTracePropagation() Option { - return func(i interface{}) error { - return nil - } -} - -// WithPollGoroutines configures how much goroutines should be used to -// poll the Receiver/Responder/Protocol implementations. -// Default value is GOMAXPROCS -func WithPollGoroutines(pollGoroutines int) Option { - return func(i interface{}) error { - if c, ok := i.(*ceClient); ok { - c.pollGoroutines = pollGoroutines - } - return nil - } -} - -// WithObservabilityService configures the observability service to use -// to record traces and metrics -func WithObservabilityService(service ObservabilityService) Option { - return func(i interface{}) error { - if c, ok := i.(*ceClient); ok { - c.observabilityService = service - c.inboundContextDecorators = append(c.inboundContextDecorators, service.InboundContextDecorators()...) - } - return nil - } -} - -// WithInboundContextDecorator configures a new inbound context decorator. -// Inbound context decorators are invoked to wrap additional informations from the binding.Message -// and propagate these informations in the context passed to the event receiver. -func WithInboundContextDecorator(dec func(context.Context, binding.Message) context.Context) Option { - return func(i interface{}) error { - if c, ok := i.(*ceClient); ok { - c.inboundContextDecorators = append(c.inboundContextDecorators, dec) - } - return nil - } -} - -// WithBlockingCallback makes the callback passed into StartReceiver is executed as a blocking call, -// i.e. in each poll go routine, the next event will not be received until the callback on current event completes. -// To make event processing serialized (no concurrency), use this option along with WithPollGoroutines(1) -func WithBlockingCallback() Option { - return func(i interface{}) error { - if c, ok := i.(*ceClient); ok { - c.blockingCallback = true - } - return nil - } -} - -// WithAckMalformedevents causes malformed events received within StartReceiver to be acknowledged -// rather than being permanently not-acknowledged. This can be useful when a protocol does not -// provide a responder implementation and would otherwise cause the receiver to be partially or -// fully stuck. -func WithAckMalformedEvent() Option { - return func(i interface{}) error { - if c, ok := i.(*ceClient); ok { - c.ackMalformedEvent = true - } - return nil - } -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/client/receiver.go b/vendor/github.com/cloudevents/sdk-go/v2/client/receiver.go deleted file mode 100644 index 2cc0e6497..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/client/receiver.go +++ /dev/null @@ -1,193 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package client - -import ( - "context" - "errors" - "fmt" - "reflect" - - "github.com/cloudevents/sdk-go/v2/event" - "github.com/cloudevents/sdk-go/v2/protocol" -) - -// ReceiveFull is the signature of a fn to be invoked for incoming cloudevents. -type ReceiveFull func(context.Context, event.Event) protocol.Result - -type receiverFn struct { - numIn int - numOut int - fnValue reflect.Value - - hasContextIn bool - hasEventIn bool - - hasEventOut bool - hasResultOut bool -} - -const ( - inParamUsage = "expected a function taking either no parameters, one or more of (context.Context, event.Event) ordered" - outParamUsage = "expected a function returning one or mode of (*event.Event, protocol.Result) ordered" -) - -var ( - contextType = reflect.TypeOf((*context.Context)(nil)).Elem() - eventType = reflect.TypeOf((*event.Event)(nil)).Elem() - eventPtrType = reflect.TypeOf((*event.Event)(nil)) // want the ptr type - resultType = reflect.TypeOf((*protocol.Result)(nil)).Elem() -) - -// receiver creates a receiverFn wrapper class that is used by the client to -// validate and invoke the provided function. -// Valid fn signatures are: -// * func() -// * func() protocol.Result -// * func(context.Context) -// * func(context.Context) protocol.Result -// * func(event.Event) -// * func(event.Event) transport.Result -// * func(context.Context, event.Event) -// * func(context.Context, event.Event) protocol.Result -// * func(event.Event) *event.Event -// * func(event.Event) (*event.Event, protocol.Result) -// * func(context.Context, event.Event) *event.Event -// * func(context.Context, event.Event) (*event.Event, protocol.Result) -func receiver(fn interface{}) (*receiverFn, error) { - fnType := reflect.TypeOf(fn) - if fnType.Kind() != reflect.Func { - return nil, errors.New("must pass a function to handle events") - } - - r := &receiverFn{ - fnValue: reflect.ValueOf(fn), - numIn: fnType.NumIn(), - numOut: fnType.NumOut(), - } - - if err := r.validate(fnType); err != nil { - return nil, err - } - - return r, nil -} - -func (r *receiverFn) invoke(ctx context.Context, e *event.Event) (*event.Event, protocol.Result) { - args := make([]reflect.Value, 0, r.numIn) - - if r.numIn > 0 { - if r.hasContextIn { - args = append(args, reflect.ValueOf(ctx)) - } - if r.hasEventIn { - args = append(args, reflect.ValueOf(*e)) - } - } - v := r.fnValue.Call(args) - var respOut protocol.Result - var eOut *event.Event - if r.numOut > 0 { - i := 0 - if r.hasEventOut { - if eo, ok := v[i].Interface().(*event.Event); ok { - eOut = eo - } - i++ // <-- note, need to inc i. - } - if r.hasResultOut { - if resp, ok := v[i].Interface().(protocol.Result); ok { - respOut = resp - } - } - } - return eOut, respOut -} - -// Verifies that the inputs to a function have a valid signature -// Valid input is to be [0, all] of -// context.Context, event.Event in this order. -func (r *receiverFn) validateInParamSignature(fnType reflect.Type) error { - r.hasContextIn = false - r.hasEventIn = false - - switch fnType.NumIn() { - case 2: - // has to be (context.Context, event.Event) - if !eventType.ConvertibleTo(fnType.In(1)) { - return fmt.Errorf("%s; cannot convert parameter 2 to %s from event.Event", inParamUsage, fnType.In(1)) - } else { - r.hasEventIn = true - } - fallthrough - case 1: - if !contextType.ConvertibleTo(fnType.In(0)) { - if !eventType.ConvertibleTo(fnType.In(0)) { - return fmt.Errorf("%s; cannot convert parameter 1 to %s from context.Context or event.Event", inParamUsage, fnType.In(0)) - } else if r.hasEventIn { - return fmt.Errorf("%s; duplicate parameter of type event.Event", inParamUsage) - } else { - r.hasEventIn = true - } - } else { - r.hasContextIn = true - } - fallthrough - case 0: - return nil - - default: - return fmt.Errorf("%s; function has too many parameters (%d)", inParamUsage, fnType.NumIn()) - } -} - -// Verifies that the outputs of a function have a valid signature -// Valid output signatures to be [0, all] of -// *event.Event, transport.Result in this order -func (r *receiverFn) validateOutParamSignature(fnType reflect.Type) error { - r.hasEventOut = false - r.hasResultOut = false - - switch fnType.NumOut() { - case 2: - // has to be (*event.Event, transport.Result) - if !fnType.Out(1).ConvertibleTo(resultType) { - return fmt.Errorf("%s; cannot convert parameter 2 from %s to event.Response", outParamUsage, fnType.Out(1)) - } else { - r.hasResultOut = true - } - fallthrough - case 1: - if !fnType.Out(0).ConvertibleTo(resultType) { - if !fnType.Out(0).ConvertibleTo(eventPtrType) { - return fmt.Errorf("%s; cannot convert parameter 1 from %s to *event.Event or transport.Result", outParamUsage, fnType.Out(0)) - } else { - r.hasEventOut = true - } - } else if r.hasResultOut { - return fmt.Errorf("%s; duplicate parameter of type event.Response", outParamUsage) - } else { - r.hasResultOut = true - } - fallthrough - case 0: - return nil - default: - return fmt.Errorf("%s; function has too many return types (%d)", outParamUsage, fnType.NumOut()) - } -} - -// validateReceiverFn validates that a function has the right number of in and -// out params and that they are of allowed types. -func (r *receiverFn) validate(fnType reflect.Type) error { - if err := r.validateInParamSignature(fnType); err != nil { - return err - } - if err := r.validateOutParamSignature(fnType); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/context/context.go b/vendor/github.com/cloudevents/sdk-go/v2/context/context.go deleted file mode 100644 index fc9ef0315..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/context/context.go +++ /dev/null @@ -1,110 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package context - -import ( - "context" - "net/url" - "time" -) - -// Opaque key type used to store target -type targetKeyType struct{} - -var targetKey = targetKeyType{} - -// WithTarget returns back a new context with the given target. Target is intended to be transport dependent. -// For http transport, `target` should be a full URL and will be injected into the outbound http request. -func WithTarget(ctx context.Context, target string) context.Context { - return context.WithValue(ctx, targetKey, target) -} - -// TargetFrom looks in the given context and returns `target` as a parsed url if found and valid, otherwise nil. -func TargetFrom(ctx context.Context) *url.URL { - c := ctx.Value(targetKey) - if c != nil { - if s, ok := c.(string); ok && s != "" { - if target, err := url.Parse(s); err == nil { - return target - } - } - } - return nil -} - -// Opaque key type used to store topic -type topicKeyType struct{} - -var topicKey = topicKeyType{} - -// WithTopic returns back a new context with the given topic. Topic is intended to be transport dependent. -// For pubsub transport, `topic` should be a Pub/Sub Topic ID. -func WithTopic(ctx context.Context, topic string) context.Context { - return context.WithValue(ctx, topicKey, topic) -} - -// TopicFrom looks in the given context and returns `topic` as a string if found and valid, otherwise "". -func TopicFrom(ctx context.Context) string { - c := ctx.Value(topicKey) - if c != nil { - if s, ok := c.(string); ok { - return s - } - } - return "" -} - -// Opaque key type used to store retry parameters -type retriesKeyType struct{} - -var retriesKey = retriesKeyType{} - -// WithRetriesConstantBackoff returns back a new context with retries parameters using constant backoff strategy. -// MaxTries is the maximum number for retries and delay is the time interval between retries -func WithRetriesConstantBackoff(ctx context.Context, delay time.Duration, maxTries int) context.Context { - return WithRetryParams(ctx, &RetryParams{ - Strategy: BackoffStrategyConstant, - Period: delay, - MaxTries: maxTries, - }) -} - -// WithRetriesLinearBackoff returns back a new context with retries parameters using linear backoff strategy. -// MaxTries is the maximum number for retries and delay*tries is the time interval between retries -func WithRetriesLinearBackoff(ctx context.Context, delay time.Duration, maxTries int) context.Context { - return WithRetryParams(ctx, &RetryParams{ - Strategy: BackoffStrategyLinear, - Period: delay, - MaxTries: maxTries, - }) -} - -// WithRetriesExponentialBackoff returns back a new context with retries parameters using exponential backoff strategy. -// MaxTries is the maximum number for retries and period is the amount of time to wait, used as `period * 2^retries`. -func WithRetriesExponentialBackoff(ctx context.Context, period time.Duration, maxTries int) context.Context { - return WithRetryParams(ctx, &RetryParams{ - Strategy: BackoffStrategyExponential, - Period: period, - MaxTries: maxTries, - }) -} - -// WithRetryParams returns back a new context with retries parameters. -func WithRetryParams(ctx context.Context, rp *RetryParams) context.Context { - return context.WithValue(ctx, retriesKey, rp) -} - -// RetriesFrom looks in the given context and returns the retries parameters if found. -// Otherwise returns the default retries configuration (ie. no retries). -func RetriesFrom(ctx context.Context) *RetryParams { - c := ctx.Value(retriesKey) - if c != nil { - if s, ok := c.(*RetryParams); ok { - return s - } - } - return &DefaultRetryParams -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/context/delegating.go b/vendor/github.com/cloudevents/sdk-go/v2/context/delegating.go deleted file mode 100644 index 434a4da7a..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/context/delegating.go +++ /dev/null @@ -1,25 +0,0 @@ -package context - -import "context" - -type valuesDelegating struct { - context.Context - parent context.Context -} - -// ValuesDelegating wraps a child and parent context. It will perform Value() -// lookups first on the child, and then fall back to the child. All other calls -// go solely to the child context. -func ValuesDelegating(child, parent context.Context) context.Context { - return &valuesDelegating{ - Context: child, - parent: parent, - } -} - -func (c *valuesDelegating) Value(key interface{}) interface{} { - if val := c.Context.Value(key); val != nil { - return val - } - return c.parent.Value(key) -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/context/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/context/doc.go deleted file mode 100644 index 0b2dcaf70..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/context/doc.go +++ /dev/null @@ -1,10 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -/* -Package context holds the last resort overrides and fyi objects that can be passed to clients and transports added to -context.Context objects. -*/ -package context diff --git a/vendor/github.com/cloudevents/sdk-go/v2/context/logger.go b/vendor/github.com/cloudevents/sdk-go/v2/context/logger.go deleted file mode 100644 index b3087a79f..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/context/logger.go +++ /dev/null @@ -1,48 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package context - -import ( - "context" - - "go.uber.org/zap" -) - -// Opaque key type used to store logger -type loggerKeyType struct{} - -var loggerKey = loggerKeyType{} - -// fallbackLogger is the logger is used when there is no logger attached to the context. -var fallbackLogger *zap.SugaredLogger - -func init() { - if logger, err := zap.NewProduction(); err != nil { - // We failed to create a fallback logger. - fallbackLogger = zap.NewNop().Sugar() - } else { - fallbackLogger = logger.Named("fallback").Sugar() - } -} - -// WithLogger returns a new context with the logger injected into the given context. -func WithLogger(ctx context.Context, logger *zap.SugaredLogger) context.Context { - if logger == nil { - return context.WithValue(ctx, loggerKey, fallbackLogger) - } - return context.WithValue(ctx, loggerKey, logger) -} - -// LoggerFrom returns the logger stored in context. -func LoggerFrom(ctx context.Context) *zap.SugaredLogger { - l := ctx.Value(loggerKey) - if l != nil { - if logger, ok := l.(*zap.SugaredLogger); ok { - return logger - } - } - return fallbackLogger -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/context/retry.go b/vendor/github.com/cloudevents/sdk-go/v2/context/retry.go deleted file mode 100644 index ec17df72e..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/context/retry.go +++ /dev/null @@ -1,76 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package context - -import ( - "context" - "errors" - "math" - "time" -) - -type BackoffStrategy string - -const ( - BackoffStrategyNone = "none" - BackoffStrategyConstant = "constant" - BackoffStrategyLinear = "linear" - BackoffStrategyExponential = "exponential" -) - -var DefaultRetryParams = RetryParams{Strategy: BackoffStrategyNone} - -// RetryParams holds parameters applied to retries -type RetryParams struct { - // Strategy is the backoff strategy to applies between retries - Strategy BackoffStrategy - - // MaxTries is the maximum number of times to retry request before giving up - MaxTries int - - // Period is - // - for none strategy: no delay - // - for constant strategy: the delay interval between retries - // - for linear strategy: interval between retries = Period * retries - // - for exponential strategy: interval between retries = Period * retries^2 - Period time.Duration -} - -// BackoffFor tries will return the time duration that should be used for this -// current try count. -// `tries` is assumed to be the number of times the caller has already retried. -func (r *RetryParams) BackoffFor(tries int) time.Duration { - switch r.Strategy { - case BackoffStrategyConstant: - return r.Period - case BackoffStrategyLinear: - return r.Period * time.Duration(tries) - case BackoffStrategyExponential: - exp := math.Exp2(float64(tries)) - return r.Period * time.Duration(exp) - case BackoffStrategyNone: - fallthrough // default - default: - return r.Period - } -} - -// Backoff is a blocking call to wait for the correct amount of time for the retry. -// `tries` is assumed to be the number of times the caller has already retried. -func (r *RetryParams) Backoff(ctx context.Context, tries int) error { - if tries > r.MaxTries { - return errors.New("too many retries") - } - ticker := time.NewTicker(r.BackoffFor(tries)) - select { - case <-ctx.Done(): - ticker.Stop() - return errors.New("context has been cancelled") - case <-ticker.C: - ticker.Stop() - } - return nil -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/content_type.go b/vendor/github.com/cloudevents/sdk-go/v2/event/content_type.go deleted file mode 100644 index a49522f82..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/content_type.go +++ /dev/null @@ -1,47 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package event - -const ( - TextPlain = "text/plain" - TextJSON = "text/json" - ApplicationJSON = "application/json" - ApplicationXML = "application/xml" - ApplicationCloudEventsJSON = "application/cloudevents+json" - ApplicationCloudEventsBatchJSON = "application/cloudevents-batch+json" -) - -// StringOfApplicationJSON returns a string pointer to "application/json" -func StringOfApplicationJSON() *string { - a := ApplicationJSON - return &a -} - -// StringOfApplicationXML returns a string pointer to "application/xml" -func StringOfApplicationXML() *string { - a := ApplicationXML - return &a -} - -// StringOfTextPlain returns a string pointer to "text/plain" -func StringOfTextPlain() *string { - a := TextPlain - return &a -} - -// StringOfApplicationCloudEventsJSON returns a string pointer to -// "application/cloudevents+json" -func StringOfApplicationCloudEventsJSON() *string { - a := ApplicationCloudEventsJSON - return &a -} - -// StringOfApplicationCloudEventsBatchJSON returns a string pointer to -// "application/cloudevents-batch+json" -func StringOfApplicationCloudEventsBatchJSON() *string { - a := ApplicationCloudEventsBatchJSON - return &a -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/data_content_encoding.go b/vendor/github.com/cloudevents/sdk-go/v2/event/data_content_encoding.go deleted file mode 100644 index cf2152693..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/data_content_encoding.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package event - -const ( - Base64 = "base64" -) - -// StringOfBase64 returns a string pointer to "Base64" -func StringOfBase64() *string { - a := Base64 - return &a -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/codec.go b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/codec.go deleted file mode 100644 index 3e077740b..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/codec.go +++ /dev/null @@ -1,78 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package datacodec - -import ( - "context" - "fmt" - - "github.com/cloudevents/sdk-go/v2/event/datacodec/json" - "github.com/cloudevents/sdk-go/v2/event/datacodec/text" - "github.com/cloudevents/sdk-go/v2/event/datacodec/xml" -) - -// Decoder is the expected function signature for decoding `in` to `out`. -// If Event sent the payload as base64, Decoder assumes that `in` is the -// decoded base64 byte array. -type Decoder func(ctx context.Context, in []byte, out interface{}) error - -// Encoder is the expected function signature for encoding `in` to bytes. -// Returns an error if the encoder has an issue encoding `in`. -type Encoder func(ctx context.Context, in interface{}) ([]byte, error) - -var decoder map[string]Decoder -var encoder map[string]Encoder - -func init() { - decoder = make(map[string]Decoder, 10) - encoder = make(map[string]Encoder, 10) - - AddDecoder("", json.Decode) - AddDecoder("application/json", json.Decode) - AddDecoder("text/json", json.Decode) - AddDecoder("application/xml", xml.Decode) - AddDecoder("text/xml", xml.Decode) - AddDecoder("text/plain", text.Decode) - - AddEncoder("", json.Encode) - AddEncoder("application/json", json.Encode) - AddEncoder("text/json", json.Encode) - AddEncoder("application/xml", xml.Encode) - AddEncoder("text/xml", xml.Encode) - AddEncoder("text/plain", text.Encode) -} - -// AddDecoder registers a decoder for a given content type. The codecs will use -// these to decode the data payload from a cloudevent.Event object. -func AddDecoder(contentType string, fn Decoder) { - decoder[contentType] = fn -} - -// AddEncoder registers an encoder for a given content type. The codecs will -// use these to encode the data payload for a cloudevent.Event object. -func AddEncoder(contentType string, fn Encoder) { - encoder[contentType] = fn -} - -// Decode looks up and invokes the decoder registered for the given content -// type. An error is returned if no decoder is registered for the given -// content type. -func Decode(ctx context.Context, contentType string, in []byte, out interface{}) error { - if fn, ok := decoder[contentType]; ok { - return fn(ctx, in, out) - } - return fmt.Errorf("[decode] unsupported content type: %q", contentType) -} - -// Encode looks up and invokes the encoder registered for the given content -// type. An error is returned if no encoder is registered for the given -// content type. -func Encode(ctx context.Context, contentType string, in interface{}) ([]byte, error) { - if fn, ok := encoder[contentType]; ok { - return fn(ctx, in) - } - return nil, fmt.Errorf("[encode] unsupported content type: %q", contentType) -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/doc.go deleted file mode 100644 index b681af887..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/doc.go +++ /dev/null @@ -1,10 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -/* -Package datacodec holds the data codec registry and adds known encoders and decoders supporting media types such as -`application/json` and `application/xml`. -*/ -package datacodec diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/json/data.go b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/json/data.go deleted file mode 100644 index 734ade59f..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/json/data.go +++ /dev/null @@ -1,56 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package json - -import ( - "context" - "encoding/json" - "fmt" - "reflect" -) - -// Decode takes `in` as []byte. -// If Event sent the payload as base64, Decoder assumes that `in` is the -// decoded base64 byte array. -func Decode(ctx context.Context, in []byte, out interface{}) error { - if in == nil { - return nil - } - if out == nil { - return fmt.Errorf("out is nil") - } - - if err := json.Unmarshal(in, out); err != nil { - return fmt.Errorf("[json] found bytes \"%s\", but failed to unmarshal: %s", string(in), err.Error()) - } - return nil -} - -// Encode attempts to json.Marshal `in` into bytes. Encode will inspect `in` -// and returns `in` unmodified if it is detected that `in` is already a []byte; -// Or json.Marshal errors. -func Encode(ctx context.Context, in interface{}) ([]byte, error) { - if in == nil { - return nil, nil - } - - it := reflect.TypeOf(in) - switch it.Kind() { - case reflect.Slice: - if it.Elem().Kind() == reflect.Uint8 { - - if b, ok := in.([]byte); ok && len(b) > 0 { - // check to see if it is a pre-encoded byte string. - if b[0] == byte('"') || b[0] == byte('{') || b[0] == byte('[') { - return b, nil - } - } - - } - } - - return json.Marshal(in) -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/json/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/json/doc.go deleted file mode 100644 index 33e1323c7..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/json/doc.go +++ /dev/null @@ -1,9 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -/* -Package json holds the encoder/decoder implementation for `application/json`. -*/ -package json diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/text/data.go b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/text/data.go deleted file mode 100644 index 761a10113..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/text/data.go +++ /dev/null @@ -1,30 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package text - -import ( - "context" - "fmt" -) - -// Text codec converts []byte or string to string and vice-versa. - -func Decode(_ context.Context, in []byte, out interface{}) error { - p, _ := out.(*string) - if p == nil { - return fmt.Errorf("text.Decode out: want *string, got %T", out) - } - *p = string(in) - return nil -} - -func Encode(_ context.Context, in interface{}) ([]byte, error) { - s, ok := in.(string) - if !ok { - return nil, fmt.Errorf("text.Encode in: want string, got %T", in) - } - return []byte(s), nil -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/text/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/text/doc.go deleted file mode 100644 index af10577aa..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/text/doc.go +++ /dev/null @@ -1,9 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -/* -Package text holds the encoder/decoder implementation for `text/plain`. -*/ -package text diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/xml/data.go b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/xml/data.go deleted file mode 100644 index de68ec3dc..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/xml/data.go +++ /dev/null @@ -1,40 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package xml - -import ( - "context" - "encoding/xml" - "fmt" -) - -// Decode takes `in` as []byte. -// If Event sent the payload as base64, Decoder assumes that `in` is the -// decoded base64 byte array. -func Decode(ctx context.Context, in []byte, out interface{}) error { - if in == nil { - return nil - } - - if err := xml.Unmarshal(in, out); err != nil { - return fmt.Errorf("[xml] found bytes, but failed to unmarshal: %s %s", err.Error(), string(in)) - } - return nil -} - -// Encode attempts to xml.Marshal `in` into bytes. Encode will inspect `in` -// and returns `in` unmodified if it is detected that `in` is already a []byte; -// Or xml.Marshal errors. -func Encode(ctx context.Context, in interface{}) ([]byte, error) { - if b, ok := in.([]byte); ok { - // check to see if it is a pre-encoded byte string. - if len(b) > 0 && b[0] == byte('"') { - return b, nil - } - } - - return xml.Marshal(in) -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/xml/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/xml/doc.go deleted file mode 100644 index c8d73213f..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/datacodec/xml/doc.go +++ /dev/null @@ -1,9 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -/* -Package xml holds the encoder/decoder implementation for `application/xml`. -*/ -package xml diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/event/doc.go deleted file mode 100644 index 31c22ce67..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/doc.go +++ /dev/null @@ -1,9 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -/* -Package event provides primitives to work with CloudEvents specification: https://github.com/cloudevents/spec. -*/ -package event diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/event.go b/vendor/github.com/cloudevents/sdk-go/v2/event/event.go deleted file mode 100644 index 52495f9a3..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/event.go +++ /dev/null @@ -1,125 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package event - -import ( - "bytes" - "encoding/json" - "strings" -) - -// Event represents the canonical representation of a CloudEvent. -type Event struct { - Context EventContext - DataEncoded []byte - // DataBase64 indicates if the event, when serialized, represents - // the data field using the base64 encoding. - // In v0.3, this field is superseded by DataContentEncoding - DataBase64 bool - FieldErrors map[string]error -} - -const ( - defaultEventVersion = CloudEventsVersionV1 -) - -func (e *Event) fieldError(field string, err error) { - if e.FieldErrors == nil { - e.FieldErrors = make(map[string]error) - } - e.FieldErrors[field] = err -} - -func (e *Event) fieldOK(field string) { - if e.FieldErrors != nil { - delete(e.FieldErrors, field) - } -} - -// New returns a new Event, an optional version can be passed to change the -// default spec version from 1.0 to the provided version. -func New(version ...string) Event { - specVersion := defaultEventVersion - if len(version) >= 1 { - specVersion = version[0] - } - e := &Event{} - e.SetSpecVersion(specVersion) - return *e -} - -// ExtensionAs is deprecated: access extensions directly via the e.Extensions() map. -// Use functions in the types package to convert extension values. -// For example replace this: -// -// var i int -// err := e.ExtensionAs("foo", &i) -// -// With this: -// -// i, err := types.ToInteger(e.Extensions["foo"]) -func (e Event) ExtensionAs(name string, obj interface{}) error { - return e.Context.ExtensionAs(name, obj) -} - -// String returns a pretty-printed representation of the Event. -func (e Event) String() string { - b := strings.Builder{} - - b.WriteString(e.Context.String()) - - if e.DataEncoded != nil { - if e.DataBase64 { - b.WriteString("Data (binary),\n ") - } else { - b.WriteString("Data,\n ") - } - switch e.DataMediaType() { - case ApplicationJSON: - var prettyJSON bytes.Buffer - err := json.Indent(&prettyJSON, e.DataEncoded, " ", " ") - if err != nil { - b.Write(e.DataEncoded) - } else { - b.Write(prettyJSON.Bytes()) - } - default: - b.Write(e.DataEncoded) - } - b.WriteString("\n") - } - - return b.String() -} - -func (e Event) Clone() Event { - out := Event{} - out.Context = e.Context.Clone() - out.DataEncoded = cloneBytes(e.DataEncoded) - out.DataBase64 = e.DataBase64 - out.FieldErrors = e.cloneFieldErrors() - return out -} - -func cloneBytes(in []byte) []byte { - if in == nil { - return nil - } - out := make([]byte, len(in)) - copy(out, in) - return out -} - -func (e Event) cloneFieldErrors() map[string]error { - if e.FieldErrors == nil { - return nil - } - newFE := make(map[string]error, len(e.FieldErrors)) - for k, v := range e.FieldErrors { - newFE[k] = v - } - return newFE -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/event_data.go b/vendor/github.com/cloudevents/sdk-go/v2/event/event_data.go deleted file mode 100644 index 8fc449ed9..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/event_data.go +++ /dev/null @@ -1,118 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package event - -import ( - "context" - "encoding/base64" - "fmt" - "strconv" - - "github.com/cloudevents/sdk-go/v2/event/datacodec" -) - -// SetData encodes the given payload with the given content type. -// If the provided payload is a byte array, when marshalled to json it will be encoded as base64. -// If the provided payload is different from byte array, datacodec.Encode is invoked to attempt a -// marshalling to byte array. -func (e *Event) SetData(contentType string, obj interface{}) error { - e.SetDataContentType(contentType) - - if e.SpecVersion() != CloudEventsVersionV1 { - return e.legacySetData(obj) - } - - // Version 1.0 and above. - switch obj := obj.(type) { - case []byte: - e.DataEncoded = obj - e.DataBase64 = true - default: - data, err := datacodec.Encode(context.Background(), e.DataMediaType(), obj) - if err != nil { - return err - } - e.DataEncoded = data - e.DataBase64 = false - } - - return nil -} - -// Deprecated: Delete when we do not have to support Spec v0.3. -func (e *Event) legacySetData(obj interface{}) error { - data, err := datacodec.Encode(context.Background(), e.DataMediaType(), obj) - if err != nil { - return err - } - if e.DeprecatedDataContentEncoding() == Base64 { - buf := make([]byte, base64.StdEncoding.EncodedLen(len(data))) - base64.StdEncoding.Encode(buf, data) - e.DataEncoded = buf - e.DataBase64 = false - } else { - data, err := datacodec.Encode(context.Background(), e.DataMediaType(), obj) - if err != nil { - return err - } - e.DataEncoded = data - e.DataBase64 = false - } - return nil -} - -const ( - quotes = `"'` -) - -func (e Event) Data() []byte { - return e.DataEncoded -} - -// DataAs attempts to populate the provided data object with the event payload. -// obj should be a pointer type. -func (e Event) DataAs(obj interface{}) error { - data := e.Data() - - if len(data) == 0 { - // No data. - return nil - } - - if e.SpecVersion() != CloudEventsVersionV1 { - var err error - if data, err = e.legacyConvertData(data); err != nil { - return err - } - } - - return datacodec.Decode(context.Background(), e.DataMediaType(), data, obj) -} - -func (e Event) legacyConvertData(data []byte) ([]byte, error) { - if e.Context.DeprecatedGetDataContentEncoding() == Base64 { - var bs []byte - // test to see if we need to unquote the data. - if data[0] == quotes[0] || data[0] == quotes[1] { - str, err := strconv.Unquote(string(data)) - if err != nil { - return nil, err - } - bs = []byte(str) - } else { - bs = data - } - - buf := make([]byte, base64.StdEncoding.DecodedLen(len(bs))) - n, err := base64.StdEncoding.Decode(buf, bs) - if err != nil { - return nil, fmt.Errorf("failed to decode data from base64: %s", err.Error()) - } - data = buf[:n] - } - - return data, nil -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/event_interface.go b/vendor/github.com/cloudevents/sdk-go/v2/event/event_interface.go deleted file mode 100644 index 2809fed57..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/event_interface.go +++ /dev/null @@ -1,102 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package event - -import ( - "time" -) - -// EventReader is the interface for reading through an event from attributes. -type EventReader interface { - // SpecVersion returns event.Context.GetSpecVersion(). - SpecVersion() string - // Type returns event.Context.GetType(). - Type() string - // Source returns event.Context.GetSource(). - Source() string - // Subject returns event.Context.GetSubject(). - Subject() string - // ID returns event.Context.GetID(). - ID() string - // Time returns event.Context.GetTime(). - Time() time.Time - // DataSchema returns event.Context.GetDataSchema(). - DataSchema() string - // DataContentType returns event.Context.GetDataContentType(). - DataContentType() string - // DataMediaType returns event.Context.GetDataMediaType(). - DataMediaType() string - // DeprecatedDataContentEncoding returns event.Context.DeprecatedGetDataContentEncoding(). - DeprecatedDataContentEncoding() string - - // Extension Attributes - - // Extensions returns the event.Context.GetExtensions(). - // Extensions use the CloudEvents type system, details in package cloudevents/types. - Extensions() map[string]interface{} - - // ExtensionAs returns event.Context.ExtensionAs(name, obj). - // - // DEPRECATED: Access extensions directly via the e.Extensions() map. - // Use functions in the types package to convert extension values. - // For example replace this: - // - // var i int - // err := e.ExtensionAs("foo", &i) - // - // With this: - // - // i, err := types.ToInteger(e.Extensions["foo"]) - // - ExtensionAs(string, interface{}) error - - // Data Attribute - - // Data returns the raw data buffer - // If the event was encoded with base64 encoding, Data returns the already decoded - // byte array - Data() []byte - - // DataAs attempts to populate the provided data object with the event payload. - DataAs(interface{}) error -} - -// EventWriter is the interface for writing through an event onto attributes. -// If an error is thrown by a sub-component, EventWriter caches the error -// internally and exposes errors with a call to event.Validate(). -type EventWriter interface { - // Context Attributes - - // SetSpecVersion performs event.Context.SetSpecVersion. - SetSpecVersion(string) - // SetType performs event.Context.SetType. - SetType(string) - // SetSource performs event.Context.SetSource. - SetSource(string) - // SetSubject( performs event.Context.SetSubject. - SetSubject(string) - // SetID performs event.Context.SetID. - SetID(string) - // SetTime performs event.Context.SetTime. - SetTime(time.Time) - // SetDataSchema performs event.Context.SetDataSchema. - SetDataSchema(string) - // SetDataContentType performs event.Context.SetDataContentType. - SetDataContentType(string) - // DeprecatedSetDataContentEncoding performs event.Context.DeprecatedSetDataContentEncoding. - SetDataContentEncoding(string) - - // Extension Attributes - - // SetExtension performs event.Context.SetExtension. - SetExtension(string, interface{}) - - // SetData encodes the given payload with the given content type. - // If the provided payload is a byte array, when marshalled to json it will be encoded as base64. - // If the provided payload is different from byte array, datacodec.Encode is invoked to attempt a - // marshalling to byte array. - SetData(string, interface{}) error -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/event_marshal.go b/vendor/github.com/cloudevents/sdk-go/v2/event/event_marshal.go deleted file mode 100644 index c5f2dc03c..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/event_marshal.go +++ /dev/null @@ -1,203 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package event - -import ( - "bytes" - "encoding/base64" - "fmt" - "io" - "strings" - - jsoniter "github.com/json-iterator/go" -) - -// WriteJson writes the in event in the provided writer. -// Note: this function assumes the input event is valid. -func WriteJson(in *Event, writer io.Writer) error { - stream := jsoniter.ConfigFastest.BorrowStream(writer) - defer jsoniter.ConfigFastest.ReturnStream(stream) - stream.WriteObjectStart() - - var ext map[string]interface{} - var dct *string - var isBase64 bool - - // Write the context (without the extensions) - switch eventContext := in.Context.(type) { - case *EventContextV03: - // Set a bunch of variables we need later - ext = eventContext.Extensions - dct = eventContext.DataContentType - - stream.WriteObjectField("specversion") - stream.WriteString(CloudEventsVersionV03) - stream.WriteMore() - - stream.WriteObjectField("id") - stream.WriteString(eventContext.ID) - stream.WriteMore() - - stream.WriteObjectField("source") - stream.WriteString(eventContext.Source.String()) - stream.WriteMore() - - stream.WriteObjectField("type") - stream.WriteString(eventContext.Type) - - if eventContext.Subject != nil { - stream.WriteMore() - stream.WriteObjectField("subject") - stream.WriteString(*eventContext.Subject) - } - - if eventContext.DataContentEncoding != nil { - isBase64 = true - stream.WriteMore() - stream.WriteObjectField("datacontentencoding") - stream.WriteString(*eventContext.DataContentEncoding) - } - - if eventContext.DataContentType != nil { - stream.WriteMore() - stream.WriteObjectField("datacontenttype") - stream.WriteString(*eventContext.DataContentType) - } - - if eventContext.SchemaURL != nil { - stream.WriteMore() - stream.WriteObjectField("schemaurl") - stream.WriteString(eventContext.SchemaURL.String()) - } - - if eventContext.Time != nil { - stream.WriteMore() - stream.WriteObjectField("time") - stream.WriteString(eventContext.Time.String()) - } - case *EventContextV1: - // Set a bunch of variables we need later - ext = eventContext.Extensions - dct = eventContext.DataContentType - isBase64 = in.DataBase64 - - stream.WriteObjectField("specversion") - stream.WriteString(CloudEventsVersionV1) - stream.WriteMore() - - stream.WriteObjectField("id") - stream.WriteString(eventContext.ID) - stream.WriteMore() - - stream.WriteObjectField("source") - stream.WriteString(eventContext.Source.String()) - stream.WriteMore() - - stream.WriteObjectField("type") - stream.WriteString(eventContext.Type) - - if eventContext.Subject != nil { - stream.WriteMore() - stream.WriteObjectField("subject") - stream.WriteString(*eventContext.Subject) - } - - if eventContext.DataContentType != nil { - stream.WriteMore() - stream.WriteObjectField("datacontenttype") - stream.WriteString(*eventContext.DataContentType) - } - - if eventContext.DataSchema != nil { - stream.WriteMore() - stream.WriteObjectField("dataschema") - stream.WriteString(eventContext.DataSchema.String()) - } - - if eventContext.Time != nil { - stream.WriteMore() - stream.WriteObjectField("time") - stream.WriteString(eventContext.Time.String()) - } - default: - return fmt.Errorf("missing event context") - } - - // Let's do a check on the error - if stream.Error != nil { - return fmt.Errorf("error while writing the event attributes: %w", stream.Error) - } - - // Let's write the body - if in.DataEncoded != nil { - stream.WriteMore() - - // We need to figure out the media type first - var mediaType string - if dct == nil { - mediaType = ApplicationJSON - } else { - // This code is required to extract the media type from the full content type string (which might contain encoding and stuff) - contentType := *dct - i := strings.IndexRune(contentType, ';') - if i == -1 { - i = len(contentType) - } - mediaType = strings.TrimSpace(strings.ToLower(contentType[0:i])) - } - - isJson := mediaType == "" || mediaType == ApplicationJSON || mediaType == TextJSON - - // If isJson and no encoding to base64, we don't need to perform additional steps - if isJson && !isBase64 { - stream.WriteObjectField("data") - _, err := stream.Write(in.DataEncoded) - if err != nil { - return fmt.Errorf("error while writing data: %w", err) - } - } else { - if in.Context.GetSpecVersion() == CloudEventsVersionV1 && isBase64 { - stream.WriteObjectField("data_base64") - } else { - stream.WriteObjectField("data") - } - // At this point of we need to write to base 64 string, or we just need to write the plain string - if isBase64 { - stream.WriteString(base64.StdEncoding.EncodeToString(in.DataEncoded)) - } else { - stream.WriteString(string(in.DataEncoded)) - } - } - - } - - // Let's do a check on the error - if stream.Error != nil { - return fmt.Errorf("error while writing the event data: %w", stream.Error) - } - - for k, v := range ext { - stream.WriteMore() - stream.WriteObjectField(k) - stream.WriteVal(v) - } - - stream.WriteObjectEnd() - - // Let's do a check on the error - if stream.Error != nil { - return fmt.Errorf("error while writing the event extensions: %w", stream.Error) - } - return stream.Flush() -} - -// MarshalJSON implements a custom json marshal method used when this type is -// marshaled using json.Marshal. -func (e Event) MarshalJSON() ([]byte, error) { - var buf bytes.Buffer - err := WriteJson(&e, &buf) - return buf.Bytes(), err -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/event_reader.go b/vendor/github.com/cloudevents/sdk-go/v2/event/event_reader.go deleted file mode 100644 index 9d1aeeb65..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/event_reader.go +++ /dev/null @@ -1,103 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package event - -import ( - "time" -) - -var _ EventReader = (*Event)(nil) - -// SpecVersion implements EventReader.SpecVersion -func (e Event) SpecVersion() string { - if e.Context != nil { - return e.Context.GetSpecVersion() - } - return "" -} - -// Type implements EventReader.Type -func (e Event) Type() string { - if e.Context != nil { - return e.Context.GetType() - } - return "" -} - -// Source implements EventReader.Source -func (e Event) Source() string { - if e.Context != nil { - return e.Context.GetSource() - } - return "" -} - -// Subject implements EventReader.Subject -func (e Event) Subject() string { - if e.Context != nil { - return e.Context.GetSubject() - } - return "" -} - -// ID implements EventReader.ID -func (e Event) ID() string { - if e.Context != nil { - return e.Context.GetID() - } - return "" -} - -// Time implements EventReader.Time -func (e Event) Time() time.Time { - if e.Context != nil { - return e.Context.GetTime() - } - return time.Time{} -} - -// DataSchema implements EventReader.DataSchema -func (e Event) DataSchema() string { - if e.Context != nil { - return e.Context.GetDataSchema() - } - return "" -} - -// DataContentType implements EventReader.DataContentType -func (e Event) DataContentType() string { - if e.Context != nil { - return e.Context.GetDataContentType() - } - return "" -} - -// DataMediaType returns the parsed DataMediaType of the event. If parsing -// fails, the empty string is returned. To retrieve the parsing error, use -// `Context.GetDataMediaType` instead. -func (e Event) DataMediaType() string { - if e.Context != nil { - mediaType, _ := e.Context.GetDataMediaType() - return mediaType - } - return "" -} - -// DeprecatedDataContentEncoding implements EventReader.DeprecatedDataContentEncoding -func (e Event) DeprecatedDataContentEncoding() string { - if e.Context != nil { - return e.Context.DeprecatedGetDataContentEncoding() - } - return "" -} - -// Extensions implements EventReader.Extensions -func (e Event) Extensions() map[string]interface{} { - if e.Context != nil { - return e.Context.GetExtensions() - } - return map[string]interface{}(nil) -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/event_unmarshal.go b/vendor/github.com/cloudevents/sdk-go/v2/event/event_unmarshal.go deleted file mode 100644 index 0dd88ae5a..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/event_unmarshal.go +++ /dev/null @@ -1,480 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package event - -import ( - "encoding/base64" - "errors" - "fmt" - "io" - "sync" - - jsoniter "github.com/json-iterator/go" - - "github.com/cloudevents/sdk-go/v2/types" -) - -const specVersionV03Flag uint8 = 1 << 4 -const specVersionV1Flag uint8 = 1 << 5 -const dataBase64Flag uint8 = 1 << 6 -const dataContentTypeFlag uint8 = 1 << 7 - -func checkFlag(state uint8, flag uint8) bool { - return state&flag != 0 -} - -func appendFlag(state *uint8, flag uint8) { - *state = (*state) | flag -} - -var iterPool = sync.Pool{ - New: func() interface{} { - return jsoniter.Parse(jsoniter.ConfigFastest, nil, 1024) - }, -} - -func borrowIterator(reader io.Reader) *jsoniter.Iterator { - iter := iterPool.Get().(*jsoniter.Iterator) - iter.Reset(reader) - return iter -} - -func returnIterator(iter *jsoniter.Iterator) { - iter.Error = nil - iter.Attachment = nil - iterPool.Put(iter) -} - -func ReadJson(out *Event, reader io.Reader) error { - iterator := borrowIterator(reader) - defer returnIterator(iterator) - - return readJsonFromIterator(out, iterator) -} - -// ReadJson allows you to read the bytes reader as an event -func readJsonFromIterator(out *Event, iterator *jsoniter.Iterator) error { - // Parsing dependency graph: - // SpecVersion - // ^ ^ - // | +--------------+ - // + + - // All Attributes datacontenttype (and datacontentencoding for v0.3) - // (except datacontenttype) ^ - // | - // | - // + - // Data - - var state uint8 = 0 - var cachedData []byte - - var ( - // Universally parseable fields. - id string - typ string - source types.URIRef - subject *string - time *types.Timestamp - datacontenttype *string - extensions = make(map[string]interface{}) - - // These fields require knowledge about the specversion to be parsed. - schemaurl jsoniter.Any - datacontentencoding jsoniter.Any - dataschema jsoniter.Any - dataBase64 jsoniter.Any - ) - - for key := iterator.ReadObject(); key != ""; key = iterator.ReadObject() { - // Check if we have some error in our error cache - if iterator.Error != nil { - return iterator.Error - } - - // We have a key, now we need to figure out what to do - // depending on the parsing state - - // If it's a specversion, trigger state change - if key == "specversion" { - if checkFlag(state, specVersionV1Flag|specVersionV03Flag) { - return fmt.Errorf("specversion was already provided") - } - sv := iterator.ReadString() - - // Check proper specversion - switch sv { - case CloudEventsVersionV1: - con := &EventContextV1{ - ID: id, - Type: typ, - Source: source, - Subject: subject, - Time: time, - DataContentType: datacontenttype, - } - - // Add the fields relevant for the version ... - if dataschema != nil { - var err error - con.DataSchema, err = toUriPtr(dataschema) - if err != nil { - return err - } - } - if dataBase64 != nil { - stream := jsoniter.ConfigFastest.BorrowStream(nil) - defer jsoniter.ConfigFastest.ReturnStream(stream) - dataBase64.WriteTo(stream) - cachedData = stream.Buffer() - if stream.Error != nil { - return stream.Error - } - appendFlag(&state, dataBase64Flag) - } - - // ... add all remaining fields as extensions. - if schemaurl != nil { - extensions["schemaurl"] = schemaurl.GetInterface() - } - if datacontentencoding != nil { - extensions["datacontentencoding"] = datacontentencoding.GetInterface() - } - - out.Context = con - appendFlag(&state, specVersionV1Flag) - case CloudEventsVersionV03: - con := &EventContextV03{ - ID: id, - Type: typ, - Source: source, - Subject: subject, - Time: time, - DataContentType: datacontenttype, - } - var err error - // Add the fields relevant for the version ... - if schemaurl != nil { - con.SchemaURL, err = toUriRefPtr(schemaurl) - if err != nil { - return err - } - } - if datacontentencoding != nil { - con.DataContentEncoding, err = toStrPtr(datacontentencoding) - if *con.DataContentEncoding != Base64 { - err = ValidationError{"datacontentencoding": errors.New("invalid datacontentencoding value, the only allowed value is 'base64'")} - } - if err != nil { - return err - } - appendFlag(&state, dataBase64Flag) - } - - // ... add all remaining fields as extensions. - if dataschema != nil { - extensions["dataschema"] = dataschema.GetInterface() - } - if dataBase64 != nil { - extensions["data_base64"] = dataBase64.GetInterface() - } - - out.Context = con - appendFlag(&state, specVersionV03Flag) - default: - return ValidationError{"specversion": errors.New("unknown value: " + sv)} - } - - // Apply all extensions to the context object. - for key, val := range extensions { - if err := out.Context.SetExtension(key, val); err != nil { - return err - } - } - continue - } - - // If no specversion ... - if !checkFlag(state, specVersionV03Flag|specVersionV1Flag) { - switch key { - case "id": - id = iterator.ReadString() - case "type": - typ = iterator.ReadString() - case "source": - source = readUriRef(iterator) - case "subject": - subject = readStrPtr(iterator) - case "time": - time = readTimestamp(iterator) - case "datacontenttype": - datacontenttype = readStrPtr(iterator) - appendFlag(&state, dataContentTypeFlag) - case "data": - cachedData = iterator.SkipAndReturnBytes() - case "data_base64": - dataBase64 = iterator.ReadAny() - case "dataschema": - dataschema = iterator.ReadAny() - case "schemaurl": - schemaurl = iterator.ReadAny() - case "datacontentencoding": - datacontentencoding = iterator.ReadAny() - default: - extensions[key] = iterator.Read() - } - continue - } - - // From this point downward -> we can assume the event has a context pointer non nil - - // If it's a datacontenttype, trigger state change - if key == "datacontenttype" { - if checkFlag(state, dataContentTypeFlag) { - return fmt.Errorf("datacontenttype was already provided") - } - - dct := iterator.ReadString() - - switch ctx := out.Context.(type) { - case *EventContextV03: - ctx.DataContentType = &dct - case *EventContextV1: - ctx.DataContentType = &dct - } - appendFlag(&state, dataContentTypeFlag) - continue - } - - // If it's a datacontentencoding and it's v0.3, trigger state change - if checkFlag(state, specVersionV03Flag) && key == "datacontentencoding" { - if checkFlag(state, dataBase64Flag) { - return ValidationError{"datacontentencoding": errors.New("datacontentencoding was specified twice")} - } - - dce := iterator.ReadString() - - if dce != Base64 { - return ValidationError{"datacontentencoding": errors.New("invalid datacontentencoding value, the only allowed value is 'base64'")} - } - - out.Context.(*EventContextV03).DataContentEncoding = &dce - appendFlag(&state, dataBase64Flag) - continue - } - - // We can parse all attributes, except data. - // If it's data or data_base64 and we don't have the attributes to process it, then we cache it - // The expanded form of this condition is: - // (checkFlag(state, specVersionV1Flag) && !checkFlag(state, dataContentTypeFlag) && (key == "data" || key == "data_base64")) || - // (checkFlag(state, specVersionV03Flag) && !(checkFlag(state, dataContentTypeFlag) && checkFlag(state, dataBase64Flag)) && key == "data") - if (state&(specVersionV1Flag|dataContentTypeFlag) == specVersionV1Flag && (key == "data" || key == "data_base64")) || - ((state&specVersionV03Flag == specVersionV03Flag) && (state&(dataContentTypeFlag|dataBase64Flag) != (dataContentTypeFlag | dataBase64Flag)) && key == "data") { - if key == "data_base64" { - appendFlag(&state, dataBase64Flag) - } - cachedData = iterator.SkipAndReturnBytes() - continue - } - - // At this point or this value is an attribute (excluding datacontenttype and datacontentencoding), or this value is data and this condition is valid: - // (specVersionV1Flag & dataContentTypeFlag) || (specVersionV03Flag & dataContentTypeFlag & dataBase64Flag) - switch eventContext := out.Context.(type) { - case *EventContextV03: - switch key { - case "id": - eventContext.ID = iterator.ReadString() - case "type": - eventContext.Type = iterator.ReadString() - case "source": - eventContext.Source = readUriRef(iterator) - case "subject": - eventContext.Subject = readStrPtr(iterator) - case "time": - eventContext.Time = readTimestamp(iterator) - case "schemaurl": - eventContext.SchemaURL = readUriRefPtr(iterator) - case "data": - iterator.Error = consumeData(out, checkFlag(state, dataBase64Flag), iterator) - default: - if eventContext.Extensions == nil { - eventContext.Extensions = make(map[string]interface{}, 1) - } - iterator.Error = eventContext.SetExtension(key, iterator.Read()) - } - case *EventContextV1: - switch key { - case "id": - eventContext.ID = iterator.ReadString() - case "type": - eventContext.Type = iterator.ReadString() - case "source": - eventContext.Source = readUriRef(iterator) - case "subject": - eventContext.Subject = readStrPtr(iterator) - case "time": - eventContext.Time = readTimestamp(iterator) - case "dataschema": - eventContext.DataSchema = readUriPtr(iterator) - case "data": - iterator.Error = consumeData(out, false, iterator) - case "data_base64": - iterator.Error = consumeData(out, true, iterator) - default: - if eventContext.Extensions == nil { - eventContext.Extensions = make(map[string]interface{}, 1) - } - iterator.Error = eventContext.SetExtension(key, iterator.Read()) - } - } - } - - if state&(specVersionV03Flag|specVersionV1Flag) == 0 { - return ValidationError{"specversion": errors.New("no specversion")} - } - - if iterator.Error != nil { - return iterator.Error - } - - // If there is a dataToken cached, we always defer at the end the processing - // because nor datacontenttype or datacontentencoding are mandatory. - if cachedData != nil { - return consumeDataAsBytes(out, checkFlag(state, dataBase64Flag), cachedData) - } - return nil -} - -func consumeDataAsBytes(e *Event, isBase64 bool, b []byte) error { - if isBase64 { - e.DataBase64 = true - - // Allocate payload byte buffer - base64Encoded := b[1 : len(b)-1] // remove quotes - e.DataEncoded = make([]byte, base64.StdEncoding.DecodedLen(len(base64Encoded))) - length, err := base64.StdEncoding.Decode(e.DataEncoded, base64Encoded) - if err != nil { - return err - } - e.DataEncoded = e.DataEncoded[0:length] - return nil - } - - mt, _ := e.Context.GetDataMediaType() - // Empty content type assumes json - if mt != "" && mt != ApplicationJSON && mt != TextJSON { - // If not json, then data is encoded as string - iter := jsoniter.ParseBytes(jsoniter.ConfigFastest, b) - src := iter.ReadString() // handles escaping - e.DataEncoded = []byte(src) - if iter.Error != nil { - return fmt.Errorf("unexpected data payload for media type %q, expected a string: %w", mt, iter.Error) - } - return nil - } - - e.DataEncoded = b - return nil -} - -func consumeData(e *Event, isBase64 bool, iter *jsoniter.Iterator) error { - if isBase64 { - e.DataBase64 = true - - // Allocate payload byte buffer - base64Encoded := iter.ReadStringAsSlice() - e.DataEncoded = make([]byte, base64.StdEncoding.DecodedLen(len(base64Encoded))) - length, err := base64.StdEncoding.Decode(e.DataEncoded, base64Encoded) - if err != nil { - return err - } - e.DataEncoded = e.DataEncoded[0:length] - return nil - } - - mt, _ := e.Context.GetDataMediaType() - if mt != ApplicationJSON && mt != TextJSON { - // If not json, then data is encoded as string - src := iter.ReadString() // handles escaping - e.DataEncoded = []byte(src) - if iter.Error != nil { - return fmt.Errorf("unexpected data payload for media type %q, expected a string: %w", mt, iter.Error) - } - return nil - } - - e.DataEncoded = iter.SkipAndReturnBytes() - return nil -} - -func readUriRef(iter *jsoniter.Iterator) types.URIRef { - str := iter.ReadString() - uriRef := types.ParseURIRef(str) - if uriRef == nil { - iter.Error = fmt.Errorf("cannot parse uri ref: %v", str) - return types.URIRef{} - } - return *uriRef -} - -func readStrPtr(iter *jsoniter.Iterator) *string { - str := iter.ReadString() - if str == "" { - return nil - } - return &str -} - -func readUriRefPtr(iter *jsoniter.Iterator) *types.URIRef { - return types.ParseURIRef(iter.ReadString()) -} - -func readUriPtr(iter *jsoniter.Iterator) *types.URI { - return types.ParseURI(iter.ReadString()) -} - -func readTimestamp(iter *jsoniter.Iterator) *types.Timestamp { - t, err := types.ParseTimestamp(iter.ReadString()) - if err != nil { - iter.Error = err - } - return t -} - -func toStrPtr(val jsoniter.Any) (*string, error) { - str := val.ToString() - if val.LastError() != nil { - return nil, val.LastError() - } - if str == "" { - return nil, nil - } - return &str, nil -} - -func toUriRefPtr(val jsoniter.Any) (*types.URIRef, error) { - str := val.ToString() - if val.LastError() != nil { - return nil, val.LastError() - } - return types.ParseURIRef(str), nil -} - -func toUriPtr(val jsoniter.Any) (*types.URI, error) { - str := val.ToString() - if val.LastError() != nil { - return nil, val.LastError() - } - return types.ParseURI(str), nil -} - -// UnmarshalJSON implements the json unmarshal method used when this type is -// unmarshaled using json.Unmarshal. -func (e *Event) UnmarshalJSON(b []byte) error { - iterator := jsoniter.ConfigFastest.BorrowIterator(b) - defer jsoniter.ConfigFastest.ReturnIterator(iterator) - return readJsonFromIterator(e, iterator) -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/event_validation.go b/vendor/github.com/cloudevents/sdk-go/v2/event/event_validation.go deleted file mode 100644 index 958ecc47d..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/event_validation.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package event - -import ( - "fmt" - "strings" -) - -type ValidationError map[string]error - -func (e ValidationError) Error() string { - b := strings.Builder{} - for k, v := range e { - b.WriteString(k) - b.WriteString(": ") - b.WriteString(v.Error()) - b.WriteRune('\n') - } - return b.String() -} - -// Validate performs a spec based validation on this event. -// Validation is dependent on the spec version specified in the event context. -func (e Event) Validate() error { - if e.Context == nil { - return ValidationError{"specversion": fmt.Errorf("missing Event.Context")} - } - - errs := map[string]error{} - if e.FieldErrors != nil { - for k, v := range e.FieldErrors { - errs[k] = v - } - } - - if fieldErrors := e.Context.Validate(); fieldErrors != nil { - for k, v := range fieldErrors { - errs[k] = v - } - } - - if len(errs) > 0 { - return ValidationError(errs) - } - return nil -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/event_writer.go b/vendor/github.com/cloudevents/sdk-go/v2/event/event_writer.go deleted file mode 100644 index ddfb1be38..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/event_writer.go +++ /dev/null @@ -1,117 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package event - -import ( - "fmt" - "time" -) - -var _ EventWriter = (*Event)(nil) - -// SetSpecVersion implements EventWriter.SetSpecVersion -func (e *Event) SetSpecVersion(v string) { - switch v { - case CloudEventsVersionV03: - if e.Context == nil { - e.Context = &EventContextV03{} - } else { - e.Context = e.Context.AsV03() - } - case CloudEventsVersionV1: - if e.Context == nil { - e.Context = &EventContextV1{} - } else { - e.Context = e.Context.AsV1() - } - default: - e.fieldError("specversion", fmt.Errorf("a valid spec version is required: [%s, %s]", - CloudEventsVersionV03, CloudEventsVersionV1)) - return - } - e.fieldOK("specversion") -} - -// SetType implements EventWriter.SetType -func (e *Event) SetType(t string) { - if err := e.Context.SetType(t); err != nil { - e.fieldError("type", err) - } else { - e.fieldOK("type") - } -} - -// SetSource implements EventWriter.SetSource -func (e *Event) SetSource(s string) { - if err := e.Context.SetSource(s); err != nil { - e.fieldError("source", err) - } else { - e.fieldOK("source") - } -} - -// SetSubject implements EventWriter.SetSubject -func (e *Event) SetSubject(s string) { - if err := e.Context.SetSubject(s); err != nil { - e.fieldError("subject", err) - } else { - e.fieldOK("subject") - } -} - -// SetID implements EventWriter.SetID -func (e *Event) SetID(id string) { - if err := e.Context.SetID(id); err != nil { - e.fieldError("id", err) - } else { - e.fieldOK("id") - } -} - -// SetTime implements EventWriter.SetTime -func (e *Event) SetTime(t time.Time) { - if err := e.Context.SetTime(t); err != nil { - e.fieldError("time", err) - } else { - e.fieldOK("time") - } -} - -// SetDataSchema implements EventWriter.SetDataSchema -func (e *Event) SetDataSchema(s string) { - if err := e.Context.SetDataSchema(s); err != nil { - e.fieldError("dataschema", err) - } else { - e.fieldOK("dataschema") - } -} - -// SetDataContentType implements EventWriter.SetDataContentType -func (e *Event) SetDataContentType(ct string) { - if err := e.Context.SetDataContentType(ct); err != nil { - e.fieldError("datacontenttype", err) - } else { - e.fieldOK("datacontenttype") - } -} - -// SetDataContentEncoding is deprecated. Implements EventWriter.SetDataContentEncoding. -func (e *Event) SetDataContentEncoding(enc string) { - if err := e.Context.DeprecatedSetDataContentEncoding(enc); err != nil { - e.fieldError("datacontentencoding", err) - } else { - e.fieldOK("datacontentencoding") - } -} - -// SetExtension implements EventWriter.SetExtension -func (e *Event) SetExtension(name string, obj interface{}) { - if err := e.Context.SetExtension(name, obj); err != nil { - e.fieldError("extension:"+name, err) - } else { - e.fieldOK("extension:" + name) - } -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext.go b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext.go deleted file mode 100644 index a39565afa..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext.go +++ /dev/null @@ -1,125 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package event - -import "time" - -// EventContextReader are the methods required to be a reader of context -// attributes. -type EventContextReader interface { - // GetSpecVersion returns the native CloudEvents Spec version of the event - // context. - GetSpecVersion() string - // GetType returns the CloudEvents type from the context. - GetType() string - // GetSource returns the CloudEvents source from the context. - GetSource() string - // GetSubject returns the CloudEvents subject from the context. - GetSubject() string - // GetID returns the CloudEvents ID from the context. - GetID() string - // GetTime returns the CloudEvents creation time from the context. - GetTime() time.Time - // GetDataSchema returns the CloudEvents schema URL (if any) from the - // context. - GetDataSchema() string - // GetDataContentType returns content type on the context. - GetDataContentType() string - // DeprecatedGetDataContentEncoding returns content encoding on the context. - DeprecatedGetDataContentEncoding() string - - // GetDataMediaType returns the MIME media type for encoded data, which is - // needed by both encoding and decoding. This is a processed form of - // GetDataContentType and it may return an error. - GetDataMediaType() (string, error) - - // DEPRECATED: Access extensions directly via the GetExtensions() - // For example replace this: - // - // var i int - // err := ec.ExtensionAs("foo", &i) - // - // With this: - // - // i, err := types.ToInteger(ec.GetExtensions["foo"]) - // - ExtensionAs(string, interface{}) error - - // GetExtensions returns the full extensions map. - // - // Extensions use the CloudEvents type system, details in package cloudevents/types. - GetExtensions() map[string]interface{} - - // GetExtension returns the extension associated with with the given key. - // The given key is case insensitive. If the extension can not be found, - // an error will be returned. - GetExtension(string) (interface{}, error) -} - -// EventContextWriter are the methods required to be a writer of context -// attributes. -type EventContextWriter interface { - // SetType sets the type of the context. - SetType(string) error - // SetSource sets the source of the context. - SetSource(string) error - // SetSubject sets the subject of the context. - SetSubject(string) error - // SetID sets the ID of the context. - SetID(string) error - // SetTime sets the time of the context. - SetTime(time time.Time) error - // SetDataSchema sets the schema url of the context. - SetDataSchema(string) error - // SetDataContentType sets the data content type of the context. - SetDataContentType(string) error - // DeprecatedSetDataContentEncoding sets the data context encoding of the context. - DeprecatedSetDataContentEncoding(string) error - - // SetExtension sets the given interface onto the extension attributes - // determined by the provided name. - // - // This function fails in V1 if the name doesn't respect the regex ^[a-zA-Z0-9]+$ - // - // Package ./types documents the types that are allowed as extension values. - SetExtension(string, interface{}) error -} - -// EventContextConverter are the methods that allow for event version -// conversion. -type EventContextConverter interface { - // AsV03 provides a translation from whatever the "native" encoding of the - // CloudEvent was to the equivalent in v0.3 field names, moving fields to or - // from extensions as necessary. - AsV03() *EventContextV03 - - // AsV1 provides a translation from whatever the "native" encoding of the - // CloudEvent was to the equivalent in v1.0 field names, moving fields to or - // from extensions as necessary. - AsV1() *EventContextV1 -} - -// EventContext is conical interface for a CloudEvents Context. -type EventContext interface { - // EventContextConverter allows for conversion between versions. - EventContextConverter - - // EventContextReader adds methods for reading context. - EventContextReader - - // EventContextWriter adds methods for writing to context. - EventContextWriter - - // Validate the event based on the specifics of the CloudEvents spec version - // represented by this event context. - Validate() ValidationError - - // Clone clones the event context. - Clone() EventContext - - // String returns a pretty-printed representation of the EventContext. - String() string -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03.go b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03.go deleted file mode 100644 index 3f0505547..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03.go +++ /dev/null @@ -1,330 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package event - -import ( - "encoding/json" - "fmt" - "mime" - "sort" - "strings" - - "github.com/cloudevents/sdk-go/v2/types" -) - -const ( - // CloudEventsVersionV03 represents the version 0.3 of the CloudEvents spec. - CloudEventsVersionV03 = "0.3" -) - -var specV03Attributes = map[string]struct{}{ - "type": {}, - "source": {}, - "subject": {}, - "id": {}, - "time": {}, - "schemaurl": {}, - "datacontenttype": {}, - "datacontentencoding": {}, -} - -// EventContextV03 represents the non-data attributes of a CloudEvents v0.3 -// event. -type EventContextV03 struct { - // Type - The type of the occurrence which has happened. - Type string `json:"type"` - // Source - A URI describing the event producer. - Source types.URIRef `json:"source"` - // Subject - The subject of the event in the context of the event producer - // (identified by `source`). - Subject *string `json:"subject,omitempty"` - // ID of the event; must be non-empty and unique within the scope of the producer. - ID string `json:"id"` - // Time - A Timestamp when the event happened. - Time *types.Timestamp `json:"time,omitempty"` - // DataSchema - A link to the schema that the `data` attribute adheres to. - SchemaURL *types.URIRef `json:"schemaurl,omitempty"` - // GetDataMediaType - A MIME (RFC2046) string describing the media type of `data`. - DataContentType *string `json:"datacontenttype,omitempty"` - // DeprecatedDataContentEncoding describes the content encoding for the `data` attribute. Valid: nil, `Base64`. - DataContentEncoding *string `json:"datacontentencoding,omitempty"` - // Extensions - Additional extension metadata beyond the base spec. - Extensions map[string]interface{} `json:"-"` -} - -// Adhere to EventContext -var _ EventContext = (*EventContextV03)(nil) - -// ExtensionAs implements EventContext.ExtensionAs -func (ec EventContextV03) ExtensionAs(name string, obj interface{}) error { - value, ok := ec.Extensions[name] - if !ok { - return fmt.Errorf("extension %q does not exist", name) - } - - // Try to unmarshal extension if we find it as a RawMessage. - switch v := value.(type) { - case json.RawMessage: - if err := json.Unmarshal(v, obj); err == nil { - // if that worked, return with obj set. - return nil - } - } - // else try as a string ptr. - - // Only support *string for now. - switch v := obj.(type) { - case *string: - if valueAsString, ok := value.(string); ok { - *v = valueAsString - return nil - } else { - return fmt.Errorf("invalid type for extension %q", name) - } - default: - return fmt.Errorf("unknown extension type %T", obj) - } -} - -// SetExtension adds the extension 'name' with value 'value' to the CloudEvents -// context. This function fails if the name uses a reserved event context key. -func (ec *EventContextV03) SetExtension(name string, value interface{}) error { - if ec.Extensions == nil { - ec.Extensions = make(map[string]interface{}) - } - - if _, ok := specV03Attributes[strings.ToLower(name)]; ok { - return fmt.Errorf("bad key %q: CloudEvents spec attribute MUST NOT be overwritten by extension", name) - } - - if value == nil { - delete(ec.Extensions, name) - if len(ec.Extensions) == 0 { - ec.Extensions = nil - } - return nil - } else { - v, err := types.Validate(value) - if err == nil { - ec.Extensions[name] = v - } - return err - } -} - -// Clone implements EventContextConverter.Clone -func (ec EventContextV03) Clone() EventContext { - ec03 := ec.AsV03() - ec03.Source = types.Clone(ec.Source).(types.URIRef) - if ec.Time != nil { - ec03.Time = types.Clone(ec.Time).(*types.Timestamp) - } - if ec.SchemaURL != nil { - ec03.SchemaURL = types.Clone(ec.SchemaURL).(*types.URIRef) - } - ec03.Extensions = ec.cloneExtensions() - return ec03 -} - -func (ec *EventContextV03) cloneExtensions() map[string]interface{} { - old := ec.Extensions - if old == nil { - return nil - } - new := make(map[string]interface{}, len(ec.Extensions)) - for k, v := range old { - new[k] = types.Clone(v) - } - return new -} - -// AsV03 implements EventContextConverter.AsV03 -func (ec EventContextV03) AsV03() *EventContextV03 { - return &ec -} - -// AsV1 implements EventContextConverter.AsV1 -func (ec EventContextV03) AsV1() *EventContextV1 { - ret := EventContextV1{ - ID: ec.ID, - Time: ec.Time, - Type: ec.Type, - DataContentType: ec.DataContentType, - Source: types.URIRef{URL: ec.Source.URL}, - Subject: ec.Subject, - Extensions: make(map[string]interface{}), - } - if ec.SchemaURL != nil { - ret.DataSchema = &types.URI{URL: ec.SchemaURL.URL} - } - - // DataContentEncoding was removed in 1.0, so put it in an extension for 1.0. - if ec.DataContentEncoding != nil { - _ = ret.SetExtension(DataContentEncodingKey, *ec.DataContentEncoding) - } - - if ec.Extensions != nil { - for k, v := range ec.Extensions { - k = strings.ToLower(k) - ret.Extensions[k] = v - } - } - if len(ret.Extensions) == 0 { - ret.Extensions = nil - } - return &ret -} - -// Validate returns errors based on requirements from the CloudEvents spec. -// For more details, see -// https://github.com/cloudevents/spec/blob/main/cloudevents/spec.md -// As of Feb 26, 2019, commit 17c32ea26baf7714ad027d9917d03d2fff79fc7e -// + https://github.com/cloudevents/spec/pull/387 -> datacontentencoding -// + https://github.com/cloudevents/spec/pull/406 -> subject -func (ec EventContextV03) Validate() ValidationError { - errors := map[string]error{} - - // type - // Type: String - // Constraints: - // REQUIRED - // MUST be a non-empty string - // SHOULD be prefixed with a reverse-DNS name. The prefixed domain dictates the organization which defines the semantics of this event type. - eventType := strings.TrimSpace(ec.Type) - if eventType == "" { - errors["type"] = fmt.Errorf("MUST be a non-empty string") - } - - // source - // Type: URI-reference - // Constraints: - // REQUIRED - source := strings.TrimSpace(ec.Source.String()) - if source == "" { - errors["source"] = fmt.Errorf("REQUIRED") - } - - // subject - // Type: String - // Constraints: - // OPTIONAL - // MUST be a non-empty string - if ec.Subject != nil { - subject := strings.TrimSpace(*ec.Subject) - if subject == "" { - errors["subject"] = fmt.Errorf("if present, MUST be a non-empty string") - } - } - - // id - // Type: String - // Constraints: - // REQUIRED - // MUST be a non-empty string - // MUST be unique within the scope of the producer - id := strings.TrimSpace(ec.ID) - if id == "" { - errors["id"] = fmt.Errorf("MUST be a non-empty string") - - // no way to test "MUST be unique within the scope of the producer" - } - - // time - // Type: Timestamp - // Constraints: - // OPTIONAL - // If present, MUST adhere to the format specified in RFC 3339 - // --> no need to test this, no way to set the time without it being valid. - - // schemaurl - // Type: URI - // Constraints: - // OPTIONAL - // If present, MUST adhere to the format specified in RFC 3986 - if ec.SchemaURL != nil { - schemaURL := strings.TrimSpace(ec.SchemaURL.String()) - // empty string is not RFC 3986 compatible. - if schemaURL == "" { - errors["schemaurl"] = fmt.Errorf("if present, MUST adhere to the format specified in RFC 3986") - } - } - - // datacontenttype - // Type: String per RFC 2046 - // Constraints: - // OPTIONAL - // If present, MUST adhere to the format specified in RFC 2046 - if ec.DataContentType != nil { - dataContentType := strings.TrimSpace(*ec.DataContentType) - if dataContentType == "" { - errors["datacontenttype"] = fmt.Errorf("if present, MUST adhere to the format specified in RFC 2046") - } else { - _, _, err := mime.ParseMediaType(dataContentType) - if err != nil { - errors["datacontenttype"] = fmt.Errorf("if present, MUST adhere to the format specified in RFC 2046") - } - } - } - - // datacontentencoding - // Type: String per RFC 2045 Section 6.1 - // Constraints: - // The attribute MUST be set if the data attribute contains string-encoded binary data. - // Otherwise the attribute MUST NOT be set. - // If present, MUST adhere to RFC 2045 Section 6.1 - if ec.DataContentEncoding != nil { - dataContentEncoding := strings.ToLower(strings.TrimSpace(*ec.DataContentEncoding)) - if dataContentEncoding != Base64 { - errors["datacontentencoding"] = fmt.Errorf("if present, MUST adhere to RFC 2045 Section 6.1") - } - } - - if len(errors) > 0 { - return errors - } - return nil -} - -// String returns a pretty-printed representation of the EventContext. -func (ec EventContextV03) String() string { - b := strings.Builder{} - - b.WriteString("Context Attributes,\n") - - b.WriteString(" specversion: " + CloudEventsVersionV03 + "\n") - b.WriteString(" type: " + ec.Type + "\n") - b.WriteString(" source: " + ec.Source.String() + "\n") - if ec.Subject != nil { - b.WriteString(" subject: " + *ec.Subject + "\n") - } - b.WriteString(" id: " + ec.ID + "\n") - if ec.Time != nil { - b.WriteString(" time: " + ec.Time.String() + "\n") - } - if ec.SchemaURL != nil { - b.WriteString(" schemaurl: " + ec.SchemaURL.String() + "\n") - } - if ec.DataContentType != nil { - b.WriteString(" datacontenttype: " + *ec.DataContentType + "\n") - } - if ec.DataContentEncoding != nil { - b.WriteString(" datacontentencoding: " + *ec.DataContentEncoding + "\n") - } - - if ec.Extensions != nil && len(ec.Extensions) > 0 { - b.WriteString("Extensions,\n") - keys := make([]string, 0, len(ec.Extensions)) - for k := range ec.Extensions { - keys = append(keys, k) - } - sort.Strings(keys) - for _, key := range keys { - b.WriteString(fmt.Sprintf(" %s: %v\n", key, ec.Extensions[key])) - } - } - - return b.String() -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03_reader.go b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03_reader.go deleted file mode 100644 index 2cd27a705..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03_reader.go +++ /dev/null @@ -1,99 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package event - -import ( - "fmt" - "strings" - "time" -) - -// GetSpecVersion implements EventContextReader.GetSpecVersion -func (ec EventContextV03) GetSpecVersion() string { - return CloudEventsVersionV03 -} - -// GetDataContentType implements EventContextReader.GetDataContentType -func (ec EventContextV03) GetDataContentType() string { - if ec.DataContentType != nil { - return *ec.DataContentType - } - return "" -} - -// GetDataMediaType implements EventContextReader.GetDataMediaType -func (ec EventContextV03) GetDataMediaType() (string, error) { - if ec.DataContentType != nil { - dct := *ec.DataContentType - i := strings.IndexRune(dct, ';') - if i == -1 { - return dct, nil - } - return strings.TrimSpace(dct[0:i]), nil - } - return "", nil -} - -// GetType implements EventContextReader.GetType -func (ec EventContextV03) GetType() string { - return ec.Type -} - -// GetSource implements EventContextReader.GetSource -func (ec EventContextV03) GetSource() string { - return ec.Source.String() -} - -// GetSubject implements EventContextReader.GetSubject -func (ec EventContextV03) GetSubject() string { - if ec.Subject != nil { - return *ec.Subject - } - return "" -} - -// GetTime implements EventContextReader.GetTime -func (ec EventContextV03) GetTime() time.Time { - if ec.Time != nil { - return ec.Time.Time - } - return time.Time{} -} - -// GetID implements EventContextReader.GetID -func (ec EventContextV03) GetID() string { - return ec.ID -} - -// GetDataSchema implements EventContextReader.GetDataSchema -func (ec EventContextV03) GetDataSchema() string { - if ec.SchemaURL != nil { - return ec.SchemaURL.String() - } - return "" -} - -// DeprecatedGetDataContentEncoding implements EventContextReader.DeprecatedGetDataContentEncoding -func (ec EventContextV03) DeprecatedGetDataContentEncoding() string { - if ec.DataContentEncoding != nil { - return *ec.DataContentEncoding - } - return "" -} - -// GetExtensions implements EventContextReader.GetExtensions -func (ec EventContextV03) GetExtensions() map[string]interface{} { - return ec.Extensions -} - -// GetExtension implements EventContextReader.GetExtension -func (ec EventContextV03) GetExtension(key string) (interface{}, error) { - v, ok := caseInsensitiveSearch(key, ec.Extensions) - if !ok { - return "", fmt.Errorf("%q not found", key) - } - return v, nil -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03_writer.go b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03_writer.go deleted file mode 100644 index 5d664635e..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v03_writer.go +++ /dev/null @@ -1,103 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package event - -import ( - "errors" - "net/url" - "strings" - "time" - - "github.com/cloudevents/sdk-go/v2/types" -) - -// Adhere to EventContextWriter -var _ EventContextWriter = (*EventContextV03)(nil) - -// SetDataContentType implements EventContextWriter.SetDataContentType -func (ec *EventContextV03) SetDataContentType(ct string) error { - ct = strings.TrimSpace(ct) - if ct == "" { - ec.DataContentType = nil - } else { - ec.DataContentType = &ct - } - return nil -} - -// SetType implements EventContextWriter.SetType -func (ec *EventContextV03) SetType(t string) error { - t = strings.TrimSpace(t) - ec.Type = t - return nil -} - -// SetSource implements EventContextWriter.SetSource -func (ec *EventContextV03) SetSource(u string) error { - pu, err := url.Parse(u) - if err != nil { - return err - } - ec.Source = types.URIRef{URL: *pu} - return nil -} - -// SetSubject implements EventContextWriter.SetSubject -func (ec *EventContextV03) SetSubject(s string) error { - s = strings.TrimSpace(s) - if s == "" { - ec.Subject = nil - } else { - ec.Subject = &s - } - return nil -} - -// SetID implements EventContextWriter.SetID -func (ec *EventContextV03) SetID(id string) error { - id = strings.TrimSpace(id) - if id == "" { - return errors.New("id is required to be a non-empty string") - } - ec.ID = id - return nil -} - -// SetTime implements EventContextWriter.SetTime -func (ec *EventContextV03) SetTime(t time.Time) error { - if t.IsZero() { - ec.Time = nil - } else { - ec.Time = &types.Timestamp{Time: t} - } - return nil -} - -// SetDataSchema implements EventContextWriter.SetDataSchema -func (ec *EventContextV03) SetDataSchema(u string) error { - u = strings.TrimSpace(u) - if u == "" { - ec.SchemaURL = nil - return nil - } - pu, err := url.Parse(u) - if err != nil { - return err - } - ec.SchemaURL = &types.URIRef{URL: *pu} - return nil -} - -// DeprecatedSetDataContentEncoding implements EventContextWriter.DeprecatedSetDataContentEncoding -func (ec *EventContextV03) DeprecatedSetDataContentEncoding(e string) error { - e = strings.ToLower(strings.TrimSpace(e)) - if e == "" { - ec.DataContentEncoding = nil - } else { - ec.DataContentEncoding = &e - } - return nil -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1.go b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1.go deleted file mode 100644 index 8f164502b..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1.go +++ /dev/null @@ -1,315 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package event - -import ( - "fmt" - "mime" - "sort" - "strings" - - "github.com/cloudevents/sdk-go/v2/types" -) - -// WIP: AS OF SEP 20, 2019 - -const ( - // CloudEventsVersionV1 represents the version 1.0 of the CloudEvents spec. - CloudEventsVersionV1 = "1.0" -) - -var specV1Attributes = map[string]struct{}{ - "id": {}, - "source": {}, - "type": {}, - "datacontenttype": {}, - "subject": {}, - "time": {}, - "specversion": {}, - "dataschema": {}, -} - -// EventContextV1 represents the non-data attributes of a CloudEvents v1.0 -// event. -type EventContextV1 struct { - // ID of the event; must be non-empty and unique within the scope of the producer. - // +required - ID string `json:"id"` - // Source - A URI describing the event producer. - // +required - Source types.URIRef `json:"source"` - // Type - The type of the occurrence which has happened. - // +required - Type string `json:"type"` - - // DataContentType - A MIME (RFC2046) string describing the media type of `data`. - // +optional - DataContentType *string `json:"datacontenttype,omitempty"` - // Subject - The subject of the event in the context of the event producer - // (identified by `source`). - // +optional - Subject *string `json:"subject,omitempty"` - // Time - A Timestamp when the event happened. - // +optional - Time *types.Timestamp `json:"time,omitempty"` - // DataSchema - A link to the schema that the `data` attribute adheres to. - // +optional - DataSchema *types.URI `json:"dataschema,omitempty"` - - // Extensions - Additional extension metadata beyond the base spec. - // +optional - Extensions map[string]interface{} `json:"-"` -} - -// Adhere to EventContext -var _ EventContext = (*EventContextV1)(nil) - -// ExtensionAs implements EventContext.ExtensionAs -func (ec EventContextV1) ExtensionAs(name string, obj interface{}) error { - name = strings.ToLower(name) - value, ok := ec.Extensions[name] - if !ok { - return fmt.Errorf("extension %q does not exist", name) - } - - // Only support *string for now. - if v, ok := obj.(*string); ok { - if *v, ok = value.(string); ok { - return nil - } - } - return fmt.Errorf("unknown extension type %T", obj) -} - -// SetExtension adds the extension 'name' with value 'value' to the CloudEvents -// context. This function fails if the name doesn't respect the regex -// ^[a-zA-Z0-9]+$ or if the name uses a reserved event context key. -func (ec *EventContextV1) SetExtension(name string, value interface{}) error { - if err := validateExtensionName(name); err != nil { - return err - } - - if _, ok := specV1Attributes[strings.ToLower(name)]; ok { - return fmt.Errorf("bad key %q: CloudEvents spec attribute MUST NOT be overwritten by extension", name) - } - - name = strings.ToLower(name) - if ec.Extensions == nil { - ec.Extensions = make(map[string]interface{}) - } - if value == nil { - delete(ec.Extensions, name) - if len(ec.Extensions) == 0 { - ec.Extensions = nil - } - return nil - } else { - v, err := types.Validate(value) // Ensure it's a legal CE attribute value - if err == nil { - ec.Extensions[name] = v - } - return err - } -} - -// Clone implements EventContextConverter.Clone -func (ec EventContextV1) Clone() EventContext { - ec1 := ec.AsV1() - ec1.Source = types.Clone(ec.Source).(types.URIRef) - if ec.Time != nil { - ec1.Time = types.Clone(ec.Time).(*types.Timestamp) - } - if ec.DataSchema != nil { - ec1.DataSchema = types.Clone(ec.DataSchema).(*types.URI) - } - ec1.Extensions = ec.cloneExtensions() - return ec1 -} - -func (ec *EventContextV1) cloneExtensions() map[string]interface{} { - old := ec.Extensions - if old == nil { - return nil - } - new := make(map[string]interface{}, len(ec.Extensions)) - for k, v := range old { - new[k] = types.Clone(v) - } - return new -} - -// AsV03 implements EventContextConverter.AsV03 -func (ec EventContextV1) AsV03() *EventContextV03 { - ret := EventContextV03{ - ID: ec.ID, - Time: ec.Time, - Type: ec.Type, - DataContentType: ec.DataContentType, - Source: types.URIRef{URL: ec.Source.URL}, - Subject: ec.Subject, - Extensions: make(map[string]interface{}), - } - - if ec.DataSchema != nil { - ret.SchemaURL = &types.URIRef{URL: ec.DataSchema.URL} - } - - if ec.Extensions != nil { - for k, v := range ec.Extensions { - k = strings.ToLower(k) - // DeprecatedDataContentEncoding was introduced in 0.3, removed in 1.0 - if strings.EqualFold(k, DataContentEncodingKey) { - etv, ok := v.(string) - if ok && etv != "" { - ret.DataContentEncoding = &etv - } - continue - } - ret.Extensions[k] = v - } - } - if len(ret.Extensions) == 0 { - ret.Extensions = nil - } - return &ret -} - -// AsV1 implements EventContextConverter.AsV1 -func (ec EventContextV1) AsV1() *EventContextV1 { - return &ec -} - -// Validate returns errors based on requirements from the CloudEvents spec. -// For more details, see https://github.com/cloudevents/spec/blob/v1.0/spec.md. -func (ec EventContextV1) Validate() ValidationError { - errors := map[string]error{} - - // id - // Type: String - // Constraints: - // REQUIRED - // MUST be a non-empty string - // MUST be unique within the scope of the producer - id := strings.TrimSpace(ec.ID) - if id == "" { - errors["id"] = fmt.Errorf("MUST be a non-empty string") - // no way to test "MUST be unique within the scope of the producer" - } - - // source - // Type: URI-reference - // Constraints: - // REQUIRED - // MUST be a non-empty URI-reference - // An absolute URI is RECOMMENDED - source := strings.TrimSpace(ec.Source.String()) - if source == "" { - errors["source"] = fmt.Errorf("REQUIRED") - } - - // type - // Type: String - // Constraints: - // REQUIRED - // MUST be a non-empty string - // SHOULD be prefixed with a reverse-DNS name. The prefixed domain dictates the organization which defines the semantics of this event type. - eventType := strings.TrimSpace(ec.Type) - if eventType == "" { - errors["type"] = fmt.Errorf("MUST be a non-empty string") - } - - // The following attributes are optional but still have validation. - - // datacontenttype - // Type: String per RFC 2046 - // Constraints: - // OPTIONAL - // If present, MUST adhere to the format specified in RFC 2046 - if ec.DataContentType != nil { - dataContentType := strings.TrimSpace(*ec.DataContentType) - if dataContentType == "" { - errors["datacontenttype"] = fmt.Errorf("if present, MUST adhere to the format specified in RFC 2046") - } else { - _, _, err := mime.ParseMediaType(dataContentType) - if err != nil { - errors["datacontenttype"] = fmt.Errorf("failed to parse RFC 2046 media type %w", err) - } - } - } - - // dataschema - // Type: URI - // Constraints: - // OPTIONAL - // If present, MUST adhere to the format specified in RFC 3986 - if ec.DataSchema != nil { - if !ec.DataSchema.Validate() { - errors["dataschema"] = fmt.Errorf("if present, MUST adhere to the format specified in RFC 3986, Section 4.3. Absolute URI") - } - } - - // subject - // Type: String - // Constraints: - // OPTIONAL - // MUST be a non-empty string - if ec.Subject != nil { - subject := strings.TrimSpace(*ec.Subject) - if subject == "" { - errors["subject"] = fmt.Errorf("if present, MUST be a non-empty string") - } - } - - // time - // Type: Timestamp - // Constraints: - // OPTIONAL - // If present, MUST adhere to the format specified in RFC 3339 - // --> no need to test this, no way to set the time without it being valid. - - if len(errors) > 0 { - return errors - } - return nil -} - -// String returns a pretty-printed representation of the EventContext. -func (ec EventContextV1) String() string { - b := strings.Builder{} - - b.WriteString("Context Attributes,\n") - - b.WriteString(" specversion: " + CloudEventsVersionV1 + "\n") - b.WriteString(" type: " + ec.Type + "\n") - b.WriteString(" source: " + ec.Source.String() + "\n") - if ec.Subject != nil { - b.WriteString(" subject: " + *ec.Subject + "\n") - } - b.WriteString(" id: " + ec.ID + "\n") - if ec.Time != nil { - b.WriteString(" time: " + ec.Time.String() + "\n") - } - if ec.DataSchema != nil { - b.WriteString(" dataschema: " + ec.DataSchema.String() + "\n") - } - if ec.DataContentType != nil { - b.WriteString(" datacontenttype: " + *ec.DataContentType + "\n") - } - - if ec.Extensions != nil && len(ec.Extensions) > 0 { - b.WriteString("Extensions,\n") - keys := make([]string, 0, len(ec.Extensions)) - for k := range ec.Extensions { - keys = append(keys, k) - } - sort.Strings(keys) - for _, key := range keys { - b.WriteString(fmt.Sprintf(" %s: %v\n", key, ec.Extensions[key])) - } - } - - return b.String() -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1_reader.go b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1_reader.go deleted file mode 100644 index 74f73b029..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1_reader.go +++ /dev/null @@ -1,104 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package event - -import ( - "fmt" - "strings" - "time" -) - -// GetSpecVersion implements EventContextReader.GetSpecVersion -func (ec EventContextV1) GetSpecVersion() string { - return CloudEventsVersionV1 -} - -// GetDataContentType implements EventContextReader.GetDataContentType -func (ec EventContextV1) GetDataContentType() string { - if ec.DataContentType != nil { - return *ec.DataContentType - } - return "" -} - -// GetDataMediaType implements EventContextReader.GetDataMediaType -func (ec EventContextV1) GetDataMediaType() (string, error) { - if ec.DataContentType != nil { - dct := *ec.DataContentType - i := strings.IndexRune(dct, ';') - if i == -1 { - return dct, nil - } - return strings.TrimSpace(dct[0:i]), nil - } - return "", nil -} - -// GetType implements EventContextReader.GetType -func (ec EventContextV1) GetType() string { - return ec.Type -} - -// GetSource implements EventContextReader.GetSource -func (ec EventContextV1) GetSource() string { - return ec.Source.String() -} - -// GetSubject implements EventContextReader.GetSubject -func (ec EventContextV1) GetSubject() string { - if ec.Subject != nil { - return *ec.Subject - } - return "" -} - -// GetTime implements EventContextReader.GetTime -func (ec EventContextV1) GetTime() time.Time { - if ec.Time != nil { - return ec.Time.Time - } - return time.Time{} -} - -// GetID implements EventContextReader.GetID -func (ec EventContextV1) GetID() string { - return ec.ID -} - -// GetDataSchema implements EventContextReader.GetDataSchema -func (ec EventContextV1) GetDataSchema() string { - if ec.DataSchema != nil { - return ec.DataSchema.String() - } - return "" -} - -// DeprecatedGetDataContentEncoding implements EventContextReader.DeprecatedGetDataContentEncoding -func (ec EventContextV1) DeprecatedGetDataContentEncoding() string { - return "" -} - -// GetExtensions implements EventContextReader.GetExtensions -func (ec EventContextV1) GetExtensions() map[string]interface{} { - if len(ec.Extensions) == 0 { - return nil - } - // For now, convert the extensions of v1.0 to the pre-v1.0 style. - ext := make(map[string]interface{}, len(ec.Extensions)) - for k, v := range ec.Extensions { - ext[k] = v - } - return ext -} - -// GetExtension implements EventContextReader.GetExtension -func (ec EventContextV1) GetExtension(key string) (interface{}, error) { - v, ok := caseInsensitiveSearch(key, ec.Extensions) - if !ok { - return "", fmt.Errorf("%q not found", key) - } - return v, nil -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1_writer.go b/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1_writer.go deleted file mode 100644 index 5f2aca763..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/eventcontext_v1_writer.go +++ /dev/null @@ -1,97 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package event - -import ( - "errors" - "net/url" - "strings" - "time" - - "github.com/cloudevents/sdk-go/v2/types" -) - -// Adhere to EventContextWriter -var _ EventContextWriter = (*EventContextV1)(nil) - -// SetDataContentType implements EventContextWriter.SetDataContentType -func (ec *EventContextV1) SetDataContentType(ct string) error { - ct = strings.TrimSpace(ct) - if ct == "" { - ec.DataContentType = nil - } else { - ec.DataContentType = &ct - } - return nil -} - -// SetType implements EventContextWriter.SetType -func (ec *EventContextV1) SetType(t string) error { - t = strings.TrimSpace(t) - ec.Type = t - return nil -} - -// SetSource implements EventContextWriter.SetSource -func (ec *EventContextV1) SetSource(u string) error { - pu, err := url.Parse(u) - if err != nil { - return err - } - ec.Source = types.URIRef{URL: *pu} - return nil -} - -// SetSubject implements EventContextWriter.SetSubject -func (ec *EventContextV1) SetSubject(s string) error { - s = strings.TrimSpace(s) - if s == "" { - ec.Subject = nil - } else { - ec.Subject = &s - } - return nil -} - -// SetID implements EventContextWriter.SetID -func (ec *EventContextV1) SetID(id string) error { - id = strings.TrimSpace(id) - if id == "" { - return errors.New("id is required to be a non-empty string") - } - ec.ID = id - return nil -} - -// SetTime implements EventContextWriter.SetTime -func (ec *EventContextV1) SetTime(t time.Time) error { - if t.IsZero() { - ec.Time = nil - } else { - ec.Time = &types.Timestamp{Time: t} - } - return nil -} - -// SetDataSchema implements EventContextWriter.SetDataSchema -func (ec *EventContextV1) SetDataSchema(u string) error { - u = strings.TrimSpace(u) - if u == "" { - ec.DataSchema = nil - return nil - } - pu, err := url.Parse(u) - if err != nil { - return err - } - ec.DataSchema = &types.URI{URL: *pu} - return nil -} - -// DeprecatedSetDataContentEncoding implements EventContextWriter.DeprecatedSetDataContentEncoding -func (ec *EventContextV1) DeprecatedSetDataContentEncoding(e string) error { - return errors.New("deprecated: SetDataContentEncoding is not supported in v1.0 of CloudEvents") -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/event/extensions.go b/vendor/github.com/cloudevents/sdk-go/v2/event/extensions.go deleted file mode 100644 index 72d0e757a..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/event/extensions.go +++ /dev/null @@ -1,57 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package event - -import ( - "errors" - "fmt" - "strings" -) - -const ( - // DataContentEncodingKey is the key to DeprecatedDataContentEncoding for versions that do not support data content encoding - // directly. - DataContentEncodingKey = "datacontentencoding" -) - -var ( - // This determines the behavior of validateExtensionName(). For MaxExtensionNameLength > 0, an error will be returned, - // if len(key) > MaxExtensionNameLength - MaxExtensionNameLength = 0 -) - -func caseInsensitiveSearch(key string, space map[string]interface{}) (interface{}, bool) { - lkey := strings.ToLower(key) - for k, v := range space { - if strings.EqualFold(lkey, strings.ToLower(k)) { - return v, true - } - } - return nil, false -} - -func IsExtensionNameValid(key string) bool { - if err := validateExtensionName(key); err != nil { - return false - } - return true -} - -func validateExtensionName(key string) error { - if len(key) < 1 { - return errors.New("bad key, CloudEvents attribute names MUST NOT be empty") - } - if MaxExtensionNameLength > 0 && len(key) > MaxExtensionNameLength { - return fmt.Errorf("bad key, CloudEvents attribute name '%s' is longer than %d characters", key, MaxExtensionNameLength) - } - - for _, c := range key { - if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) { - return errors.New("bad key, CloudEvents attribute names MUST consist of lower-case letters ('a' to 'z'), upper-case letters ('A' to 'Z') or digits ('0' to '9') from the ASCII character set") - } - } - return nil -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/doc.go deleted file mode 100644 index 3c771fc5c..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/doc.go +++ /dev/null @@ -1,25 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -/* -Package protocol defines interfaces to decouple the client package -from protocol implementations. - -Most event sender and receiver applications should not use this -package, they should use the client package. This package is for -infrastructure developers implementing new transports, or intermediary -components like importers, channels or brokers. - -Available protocols: - -* HTTP (using net/http) -* Kafka (using github.com/Shopify/sarama) -* AMQP (using pack.ag/amqp) -* Go Channels -* Nats -* Nats Streaming (stan) -* Google PubSub -*/ -package protocol diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/error.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/error.go deleted file mode 100644 index a3f335261..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/error.go +++ /dev/null @@ -1,42 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package protocol - -import "fmt" - -// ErrTransportMessageConversion is an error produced when the transport -// message can not be converted. -type ErrTransportMessageConversion struct { - fatal bool - handled bool - transport string - message string -} - -// NewErrTransportMessageConversion makes a new ErrTransportMessageConversion. -func NewErrTransportMessageConversion(transport, message string, handled, fatal bool) *ErrTransportMessageConversion { - return &ErrTransportMessageConversion{ - transport: transport, - message: message, - handled: handled, - fatal: fatal, - } -} - -// IsFatal reports if this error should be considered fatal. -func (e *ErrTransportMessageConversion) IsFatal() bool { - return e.fatal -} - -// Handled reports if this error should be considered accepted and no further action. -func (e *ErrTransportMessageConversion) Handled() bool { - return e.handled -} - -// Error implements error.Error -func (e *ErrTransportMessageConversion) Error() string { - return fmt.Sprintf("transport %s failed to convert message: %s", e.transport, e.message) -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/abuse_protection.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/abuse_protection.go deleted file mode 100644 index 48f03fb6c..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/abuse_protection.go +++ /dev/null @@ -1,128 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package http - -import ( - "context" - cecontext "github.com/cloudevents/sdk-go/v2/context" - "go.uber.org/zap" - "net/http" - "strconv" - "strings" - "time" -) - -type WebhookConfig struct { - AllowedMethods []string // defaults to POST - AllowedRate *int - AutoACKCallback bool - AllowedOrigins []string -} - -const ( - DefaultAllowedRate = 1000 - DefaultTimeout = time.Second * 600 -) - -// TODO: implement rate limiting. -// Throttling is indicated by requests being rejected using HTTP status code 429 Too Many Requests. -// TODO: use this if Webhook Request Origin has been turned on. -// Inbound requests should be rejected if Allowed Origins is required by SDK. - -func (p *Protocol) OptionsHandler(rw http.ResponseWriter, req *http.Request) { - if req.Method != http.MethodOptions || p.WebhookConfig == nil { - rw.WriteHeader(http.StatusMethodNotAllowed) - return - } - - headers := make(http.Header) - - // The spec does not say we need to validate the origin, just the request origin. - // After the handshake, we will validate the origin. - if origin, ok := p.ValidateRequestOrigin(req); !ok { - rw.WriteHeader(http.StatusBadRequest) - return - } else { - headers.Set("WebHook-Allowed-Origin", origin) - } - - allowedRateRequired := false - if _, ok := req.Header[http.CanonicalHeaderKey("WebHook-Request-Rate")]; ok { - // must send WebHook-Allowed-Rate - allowedRateRequired = true - } - - if p.WebhookConfig.AllowedRate != nil { - headers.Set("WebHook-Allowed-Rate", strconv.Itoa(*p.WebhookConfig.AllowedRate)) - } else if allowedRateRequired { - headers.Set("WebHook-Allowed-Rate", strconv.Itoa(DefaultAllowedRate)) - } - - if len(p.WebhookConfig.AllowedMethods) > 0 { - headers.Set("Allow", strings.Join(p.WebhookConfig.AllowedMethods, ", ")) - } else { - headers.Set("Allow", http.MethodPost) - } - - cb := req.Header.Get("WebHook-Request-Callback") - if cb != "" { - if p.WebhookConfig.AutoACKCallback { - go func() { - reqAck, err := http.NewRequest(http.MethodPost, cb, nil) - if err != nil { - cecontext.LoggerFrom(req.Context()).Errorw("OPTIONS handler failed to create http request attempting to ack callback.", zap.Error(err), zap.String("callback", cb)) - return - } - - // Write out the headers. - for k := range headers { - reqAck.Header.Set(k, headers.Get(k)) - } - - _, err = http.DefaultClient.Do(reqAck) - if err != nil { - cecontext.LoggerFrom(req.Context()).Errorw("OPTIONS handler failed to ack callback.", zap.Error(err), zap.String("callback", cb)) - return - } - }() - return - } else { - cecontext.LoggerFrom(req.Context()).Infof("ACTION REQUIRED: Please validate web hook request callback: %q", cb) - // TODO: what to do pending https://github.com/cloudevents/spec/issues/617 - return - } - } - - // Write out the headers. - for k := range headers { - rw.Header().Set(k, headers.Get(k)) - } -} - -func (p *Protocol) ValidateRequestOrigin(req *http.Request) (string, bool) { - return p.validateOrigin(req.Header.Get("WebHook-Request-Origin")) -} - -func (p *Protocol) ValidateOrigin(req *http.Request) (string, bool) { - return p.validateOrigin(req.Header.Get("Origin")) -} - -func (p *Protocol) validateOrigin(ro string) (string, bool) { - cecontext.LoggerFrom(context.TODO()).Infow("Validating origin.", zap.String("origin", ro)) - - for _, ao := range p.WebhookConfig.AllowedOrigins { - if ao == "*" { - return ao, true - } - // TODO: it is not clear what the rules for allowed hosts are. - // Need to find docs for this. For now, test for prefix. - if strings.HasPrefix(ro, ao) { - return ao, true - } - } - - return ro, false -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/context.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/context.go deleted file mode 100644 index e973738c6..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/context.go +++ /dev/null @@ -1,48 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package http - -import ( - "context" - - nethttp "net/http" - "net/url" -) - -type requestKey struct{} - -// RequestData holds the http.Request information subset that can be -// used to retrieve HTTP information for an incoming CloudEvent. -type RequestData struct { - URL *url.URL - Header nethttp.Header - RemoteAddr string - Host string -} - -// WithRequestDataAtContext uses the http.Request to add RequestData -// information to the Context. -func WithRequestDataAtContext(ctx context.Context, r *nethttp.Request) context.Context { - if r == nil { - return ctx - } - - return context.WithValue(ctx, requestKey{}, &RequestData{ - URL: r.URL, - Header: r.Header, - RemoteAddr: r.RemoteAddr, - Host: r.Host, - }) -} - -// RequestDataFromContext retrieves RequestData from the Context. -// If not set nil is returned. -func RequestDataFromContext(ctx context.Context) *RequestData { - if req := ctx.Value(requestKey{}); req != nil { - return req.(*RequestData) - } - return nil -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/doc.go deleted file mode 100644 index 3428ea387..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/doc.go +++ /dev/null @@ -1,9 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -/* -Package http implements an HTTP binding using net/http module -*/ -package http diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/headers.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/headers.go deleted file mode 100644 index 055a5c4dd..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/headers.go +++ /dev/null @@ -1,55 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package http - -import ( - "context" - "github.com/cloudevents/sdk-go/v2/binding" - "net/http" - "net/textproto" - "strings" - "unicode" - - "github.com/cloudevents/sdk-go/v2/binding/spec" -) - -var attributeHeadersMapping map[string]string - -type customHeaderKey int - -const ( - headerKey customHeaderKey = iota -) - -func init() { - attributeHeadersMapping = make(map[string]string) - for _, v := range specs.Versions() { - for _, a := range v.Attributes() { - if a.Kind() == spec.DataContentType { - attributeHeadersMapping[a.Name()] = ContentType - } else { - attributeHeadersMapping[a.Name()] = textproto.CanonicalMIMEHeaderKey(prefix + a.Name()) - } - } - } -} - -func extNameToHeaderName(name string) string { - var b strings.Builder - b.Grow(len(name) + len(prefix)) - b.WriteString(prefix) - b.WriteRune(unicode.ToUpper(rune(name[0]))) - b.WriteString(name[1:]) - return b.String() -} - -func HeaderFrom(ctx context.Context) http.Header { - return binding.GetOrDefaultFromCtx(ctx, headerKey, make(http.Header)).(http.Header) -} - -func WithCustomHeader(ctx context.Context, header http.Header) context.Context { - return context.WithValue(ctx, headerKey, header) -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/message.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/message.go deleted file mode 100644 index 7a7c36f9b..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/message.go +++ /dev/null @@ -1,175 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package http - -import ( - "context" - "io" - nethttp "net/http" - "net/textproto" - "strings" - "unicode" - - "github.com/cloudevents/sdk-go/v2/binding" - "github.com/cloudevents/sdk-go/v2/binding/format" - "github.com/cloudevents/sdk-go/v2/binding/spec" -) - -const prefix = "Ce-" - -var specs = spec.WithPrefixMatchExact( - func(s string) string { - if s == "datacontenttype" { - return "Content-Type" - } else { - return textproto.CanonicalMIMEHeaderKey("Ce-" + s) - } - }, - "Ce-", -) - -const ContentType = "Content-Type" -const ContentLength = "Content-Length" - -// Message holds the Header and Body of a HTTP Request or Response. -// The Message instance *must* be constructed from NewMessage function. -// This message *cannot* be read several times. In order to read it more times, buffer it using binding/buffering methods -type Message struct { - Header nethttp.Header - BodyReader io.ReadCloser - OnFinish func(error) error - - ctx context.Context - - format format.Format - version spec.Version -} - -// Check if http.Message implements binding.Message -var _ binding.Message = (*Message)(nil) -var _ binding.MessageContext = (*Message)(nil) -var _ binding.MessageMetadataReader = (*Message)(nil) - -// NewMessage returns a binding.Message with header and data. -// The returned binding.Message *cannot* be read several times. In order to read it more times, buffer it using binding/buffering methods -func NewMessage(header nethttp.Header, body io.ReadCloser) *Message { - m := Message{Header: header} - if body != nil { - m.BodyReader = body - } - if m.format = format.Lookup(header.Get(ContentType)); m.format == nil { - m.version = specs.Version(m.Header.Get(specs.PrefixedSpecVersionName())) - } - return &m -} - -// NewMessageFromHttpRequest returns a binding.Message with header and data. -// The returned binding.Message *cannot* be read several times. In order to read it more times, buffer it using binding/buffering methods -func NewMessageFromHttpRequest(req *nethttp.Request) *Message { - if req == nil { - return nil - } - message := NewMessage(req.Header, req.Body) - message.ctx = req.Context() - return message -} - -// NewMessageFromHttpResponse returns a binding.Message with header and data. -// The returned binding.Message *cannot* be read several times. In order to read it more times, buffer it using binding/buffering methods -func NewMessageFromHttpResponse(resp *nethttp.Response) *Message { - if resp == nil { - return nil - } - msg := NewMessage(resp.Header, resp.Body) - return msg -} - -func (m *Message) ReadEncoding() binding.Encoding { - if m.version != nil { - return binding.EncodingBinary - } - if m.format != nil { - if m.format == format.JSONBatch { - return binding.EncodingBatch - } - return binding.EncodingStructured - } - return binding.EncodingUnknown -} - -func (m *Message) ReadStructured(ctx context.Context, encoder binding.StructuredWriter) error { - if m.format == nil { - return binding.ErrNotStructured - } else { - return encoder.SetStructuredEvent(ctx, m.format, m.BodyReader) - } -} - -func (m *Message) ReadBinary(ctx context.Context, encoder binding.BinaryWriter) (err error) { - if m.version == nil { - return binding.ErrNotBinary - } - - for k, v := range m.Header { - attr := m.version.Attribute(k) - if attr != nil { - err = encoder.SetAttribute(attr, v[0]) - } else if strings.HasPrefix(k, prefix) { - // Trim Prefix + To lower - var b strings.Builder - b.Grow(len(k) - len(prefix)) - b.WriteRune(unicode.ToLower(rune(k[len(prefix)]))) - b.WriteString(k[len(prefix)+1:]) - err = encoder.SetExtension(b.String(), v[0]) - } - if err != nil { - return err - } - } - - if m.BodyReader != nil { - err = encoder.SetData(m.BodyReader) - if err != nil { - return err - } - } - - return -} - -func (m *Message) GetAttribute(k spec.Kind) (spec.Attribute, interface{}) { - attr := m.version.AttributeFromKind(k) - if attr != nil { - h := m.Header[attributeHeadersMapping[attr.Name()]] - if h != nil { - return attr, h[0] - } - return attr, nil - } - return nil, nil -} - -func (m *Message) GetExtension(name string) interface{} { - h := m.Header[extNameToHeaderName(name)] - if h != nil { - return h[0] - } - return nil -} - -func (m *Message) Context() context.Context { - return m.ctx -} - -func (m *Message) Finish(err error) error { - if m.BodyReader != nil { - _ = m.BodyReader.Close() - } - if m.OnFinish != nil { - return m.OnFinish(err) - } - return nil -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/options.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/options.go deleted file mode 100644 index 6582af3ea..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/options.go +++ /dev/null @@ -1,300 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package http - -import ( - "fmt" - "net" - nethttp "net/http" - "net/url" - "strings" - "time" -) - -// Option is the function signature required to be considered an http.Option. -type Option func(*Protocol) error - -// WithTarget sets the outbound recipient of cloudevents when using an HTTP -// request. -func WithTarget(targetUrl string) Option { - return func(p *Protocol) error { - if p == nil { - return fmt.Errorf("http target option can not set nil protocol") - } - targetUrl = strings.TrimSpace(targetUrl) - if targetUrl != "" { - var err error - var target *url.URL - target, err = url.Parse(targetUrl) - if err != nil { - return fmt.Errorf("http target option failed to parse target url: %s", err.Error()) - } - - p.Target = target - - if p.RequestTemplate == nil { - p.RequestTemplate = &nethttp.Request{ - Method: nethttp.MethodPost, - } - } - p.RequestTemplate.URL = target - - return nil - } - return fmt.Errorf("http target option was empty string") - } -} - -// WithHeader sets an additional default outbound header for all cloudevents -// when using an HTTP request. -func WithHeader(key, value string) Option { - return func(p *Protocol) error { - if p == nil { - return fmt.Errorf("http header option can not set nil protocol") - } - key = strings.TrimSpace(key) - if key != "" { - if p.RequestTemplate == nil { - p.RequestTemplate = &nethttp.Request{ - Method: nethttp.MethodPost, - } - } - if p.RequestTemplate.Header == nil { - p.RequestTemplate.Header = nethttp.Header{} - } - p.RequestTemplate.Header.Add(key, value) - return nil - } - return fmt.Errorf("http header option was empty string") - } -} - -// WithShutdownTimeout sets the shutdown timeout when the http server is being shutdown. -func WithShutdownTimeout(timeout time.Duration) Option { - return func(p *Protocol) error { - if p == nil { - return fmt.Errorf("http shutdown timeout option can not set nil protocol") - } - p.ShutdownTimeout = timeout - return nil - } -} - -func checkListen(p *Protocol, prefix string) error { - switch { - case p.listener.Load() != nil: - return fmt.Errorf("error setting %v: listener already set", prefix) - } - return nil -} - -// WithPort sets the listening port for StartReceiver. -// Only one of WithListener or WithPort is allowed. -func WithPort(port int) Option { - return func(p *Protocol) error { - if p == nil { - return fmt.Errorf("http port option can not set nil protocol") - } - if port < 0 || port > 65535 { - return fmt.Errorf("http port option was given an invalid port: %d", port) - } - if err := checkListen(p, "http port option"); err != nil { - return err - } - p.Port = port - return nil - } -} - -// WithListener sets the listener for StartReceiver. -// Only one of WithListener or WithPort is allowed. -func WithListener(l net.Listener) Option { - return func(p *Protocol) error { - if p == nil { - return fmt.Errorf("http listener option can not set nil protocol") - } - if err := checkListen(p, "http listener"); err != nil { - return err - } - p.listener.Store(l) - return nil - } -} - -// WithPath sets the path to receive cloudevents on for HTTP transports. -func WithPath(path string) Option { - return func(p *Protocol) error { - if p == nil { - return fmt.Errorf("http path option can not set nil protocol") - } - path = strings.TrimSpace(path) - if len(path) == 0 { - return fmt.Errorf("http path option was given an invalid path: %q", path) - } - p.Path = path - return nil - } -} - -// WithMethod sets the HTTP verb (GET, POST, PUT, etc.) to use -// when using an HTTP request. -func WithMethod(method string) Option { - return func(p *Protocol) error { - if p == nil { - return fmt.Errorf("http method option can not set nil protocol") - } - method = strings.TrimSpace(method) - if method != "" { - if p.RequestTemplate == nil { - p.RequestTemplate = &nethttp.Request{} - } - p.RequestTemplate.Method = method - return nil - } - return fmt.Errorf("http method option was empty string") - } -} - -// Middleware is a function that takes an existing http.Handler and wraps it in middleware, -// returning the wrapped http.Handler. -type Middleware func(next nethttp.Handler) nethttp.Handler - -// WithMiddleware adds an HTTP middleware to the transport. It may be specified multiple times. -// Middleware is applied to everything before it. For example -// `NewClient(WithMiddleware(foo), WithMiddleware(bar))` would result in `bar(foo(original))`. -func WithMiddleware(middleware Middleware) Option { - return func(p *Protocol) error { - if p == nil { - return fmt.Errorf("http middleware option can not set nil protocol") - } - p.middleware = append(p.middleware, middleware) - return nil - } -} - -// WithRoundTripper sets the HTTP RoundTripper. -func WithRoundTripper(roundTripper nethttp.RoundTripper) Option { - return func(p *Protocol) error { - if p == nil { - return fmt.Errorf("http round tripper option can not set nil protocol") - } - p.roundTripper = roundTripper - return nil - } -} - -// WithRoundTripperDecorator decorates the default HTTP RoundTripper chosen. -func WithRoundTripperDecorator(decorator func(roundTripper nethttp.RoundTripper) nethttp.RoundTripper) Option { - return func(p *Protocol) error { - if p == nil { - return fmt.Errorf("http round tripper option can not set nil protocol") - } - if p.roundTripper == nil { - if p.Client == nil { - p.roundTripper = nethttp.DefaultTransport - } else { - p.roundTripper = p.Client.Transport - } - } - p.roundTripper = decorator(p.roundTripper) - return nil - } -} - -// WithClient sets the protocol client -func WithClient(client nethttp.Client) Option { - return func(p *Protocol) error { - if p == nil { - return fmt.Errorf("client option can not set nil protocol") - } - p.Client = &client - return nil - } -} - -// WithGetHandlerFunc sets the http GET handler func -func WithGetHandlerFunc(fn nethttp.HandlerFunc) Option { - return func(p *Protocol) error { - if p == nil { - return fmt.Errorf("http GET handler func can not set nil protocol") - } - p.GetHandlerFn = fn - return nil - } -} - -// WithOptionsHandlerFunc sets the http OPTIONS handler func -func WithOptionsHandlerFunc(fn nethttp.HandlerFunc) Option { - return func(p *Protocol) error { - if p == nil { - return fmt.Errorf("http OPTIONS handler func can not set nil protocol") - } - p.OptionsHandlerFn = fn - return nil - } -} - -// WithDefaultOptionsHandlerFunc sets the options handler to be the built in handler and configures the options. -// methods: the supported methods reported to OPTIONS caller. -// rate: the rate limit reported to OPTIONS caller. -// origins: the prefix of the accepted origins, or "*". -// callback: preform the callback to ACK the OPTIONS request. -func WithDefaultOptionsHandlerFunc(methods []string, rate int, origins []string, callback bool) Option { - return func(p *Protocol) error { - if p == nil { - return fmt.Errorf("http OPTIONS handler func can not set nil protocol") - } - p.OptionsHandlerFn = p.OptionsHandler - p.WebhookConfig = &WebhookConfig{ - AllowedMethods: methods, - AllowedRate: &rate, - AllowedOrigins: origins, - AutoACKCallback: callback, - } - return nil - } -} - -// IsRetriable is a custom function that can be used to override the -// default retriable status codes. -type IsRetriable func(statusCode int) bool - -// WithIsRetriableFunc sets the function that gets called to determine if an -// error should be retried. If not set, the defaultIsRetriableFunc is used. -func WithIsRetriableFunc(isRetriable IsRetriable) Option { - return func(p *Protocol) error { - if p == nil { - return fmt.Errorf("isRetriable handler func can not set nil protocol") - } - if isRetriable == nil { - return fmt.Errorf("isRetriable handler can not be nil") - } - p.isRetriableFunc = isRetriable - return nil - } -} - -func WithRateLimiter(rl RateLimiter) Option { - return func(p *Protocol) error { - if p == nil { - return fmt.Errorf("http OPTIONS handler func can not set nil protocol") - } - p.limiter = rl - return nil - } -} - -// WithRequestDataAtContextMiddleware adds to the Context RequestData. -// This enables a user's dispatch handler to inspect HTTP request information by -// retrieving it from the Context. -func WithRequestDataAtContextMiddleware() Option { - return WithMiddleware(func(next nethttp.Handler) nethttp.Handler { - return nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) { - ctx := WithRequestDataAtContext(r.Context(), r) - next.ServeHTTP(w, r.WithContext(ctx)) - }) - }) -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol.go deleted file mode 100644 index 7ee3b8fe1..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol.go +++ /dev/null @@ -1,411 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package http - -import ( - "bytes" - "context" - "errors" - "fmt" - "io" - "net/http" - "net/url" - "strconv" - "sync" - "sync/atomic" - "time" - - "github.com/cloudevents/sdk-go/v2/binding" - cecontext "github.com/cloudevents/sdk-go/v2/context" - "github.com/cloudevents/sdk-go/v2/event" - "github.com/cloudevents/sdk-go/v2/protocol" -) - -const ( - // DefaultShutdownTimeout defines the default timeout given to the http.Server when calling Shutdown. - DefaultShutdownTimeout = time.Minute * 1 -) - -type msgErr struct { - msg *Message - respFn protocol.ResponseFn - err error -} - -// Default error codes that we retry on - string isn't used, it's just there so -// people know what each error code's title is. -// To modify this use Option -var defaultRetriableErrors = map[int]string{ - 404: "Not Found", - 413: "Payload Too Large", - 425: "Too Early", - 429: "Too Many Requests", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Gateway Timeout", -} - -// Protocol acts as both a http client and a http handler. -type Protocol struct { - Target *url.URL - RequestTemplate *http.Request - Client *http.Client - incoming chan msgErr - - // OptionsHandlerFn handles the OPTIONS method requests and is intended to - // implement the abuse protection spec: - // https://github.com/cloudevents/spec/blob/v1.0/http-webhook.md#4-abuse-protection - OptionsHandlerFn http.HandlerFunc - WebhookConfig *WebhookConfig - - GetHandlerFn http.HandlerFunc - DeleteHandlerFn http.HandlerFunc - - // To support Opener: - - // ShutdownTimeout defines the timeout given to the http.Server when calling Shutdown. - // If 0, DefaultShutdownTimeout is used. - ShutdownTimeout time.Duration - - // Port is the port configured to bind the receiver to. Defaults to 8080. - // If you want to know the effective port you're listening to, use GetListeningPort() - Port int - // Path is the path to bind the receiver to. Defaults to "/". - Path string - - // Receive Mutex - reMu sync.Mutex - // Handler is the handler the http Server will use. Use this to reuse the - // http server. If nil, the Protocol will create a one. - Handler *http.ServeMux - - listener atomic.Value - roundTripper http.RoundTripper - server *http.Server - handlerRegistered bool - middleware []Middleware - limiter RateLimiter - - isRetriableFunc IsRetriable -} - -func New(opts ...Option) (*Protocol, error) { - p := &Protocol{ - incoming: make(chan msgErr), - Port: -1, - } - if err := p.applyOptions(opts...); err != nil { - return nil, err - } - - if p.Client == nil { - // This is how http.DefaultClient is initialized. We do not just use - // that because when WithRoundTripper is used, it will change the client's - // transport, which would cause that transport to be used process-wide. - p.Client = &http.Client{} - } - - if p.roundTripper != nil { - p.Client.Transport = p.roundTripper - } - - if p.ShutdownTimeout == 0 { - p.ShutdownTimeout = DefaultShutdownTimeout - } - - if p.isRetriableFunc == nil { - p.isRetriableFunc = defaultIsRetriableFunc - } - - if p.limiter == nil { - p.limiter = noOpLimiter{} - } - - return p, nil -} - -// NewObserved creates an HTTP protocol with trace propagating middleware. -// Deprecated: now this behaves like New and it will be removed in future releases, -// setup the http observed protocol using the opencensus separate module NewObservedHttp -var NewObserved = New - -func (p *Protocol) applyOptions(opts ...Option) error { - for _, fn := range opts { - if err := fn(p); err != nil { - return err - } - } - return nil -} - -// Send implements binding.Sender -func (p *Protocol) Send(ctx context.Context, m binding.Message, transformers ...binding.Transformer) error { - if ctx == nil { - return fmt.Errorf("nil Context") - } else if m == nil { - return fmt.Errorf("nil Message") - } - - msg, err := p.Request(ctx, m, transformers...) - if msg != nil { - defer func() { _ = msg.Finish(err) }() - } - if err != nil && !protocol.IsACK(err) { - var res *Result - if protocol.ResultAs(err, &res) { - if message, ok := msg.(*Message); ok { - buf := new(bytes.Buffer) - buf.ReadFrom(message.BodyReader) - errorStr := buf.String() - // If the error is not wrapped, then append the original error string. - if og, ok := err.(*Result); ok { - og.Format = og.Format + "%s" - og.Args = append(og.Args, errorStr) - err = og - } else { - err = NewResult(res.StatusCode, "%w: %s", err, errorStr) - } - } - } - } - return err -} - -// Request implements binding.Requester -func (p *Protocol) Request(ctx context.Context, m binding.Message, transformers ...binding.Transformer) (binding.Message, error) { - if ctx == nil { - return nil, fmt.Errorf("nil Context") - } else if m == nil { - return nil, fmt.Errorf("nil Message") - } - - var err error - defer func() { _ = m.Finish(err) }() - - req := p.makeRequest(ctx) - - if p.Client == nil || req == nil || req.URL == nil { - return nil, fmt.Errorf("not initialized: %#v", p) - } - - if err = WriteRequest(ctx, m, req, transformers...); err != nil { - return nil, err - } - - return p.do(ctx, req) -} - -func (p *Protocol) makeRequest(ctx context.Context) *http.Request { - req := &http.Request{ - Method: http.MethodPost, - Header: HeaderFrom(ctx), - } - - if p.RequestTemplate != nil { - req.Method = p.RequestTemplate.Method - req.URL = p.RequestTemplate.URL - req.Close = p.RequestTemplate.Close - req.Host = p.RequestTemplate.Host - copyHeadersEnsure(p.RequestTemplate.Header, &req.Header) - } - - if p.Target != nil { - req.URL = p.Target - } - - // Override the default request with target from context. - if target := cecontext.TargetFrom(ctx); target != nil { - req.URL = target - } - return req.WithContext(ctx) -} - -// Ensure to is a non-nil map before copying -func copyHeadersEnsure(from http.Header, to *http.Header) { - if len(from) > 0 { - if *to == nil { - *to = http.Header{} - } - copyHeaders(from, *to) - } -} - -func copyHeaders(from, to http.Header) { - if from == nil || to == nil { - return - } - for header, values := range from { - for _, value := range values { - to.Add(header, value) - } - } -} - -// Receive the next incoming HTTP request as a CloudEvent. -// Returns non-nil error if the incoming HTTP request fails to parse as a CloudEvent -// Returns io.EOF if the receiver is closed. -func (p *Protocol) Receive(ctx context.Context) (binding.Message, error) { - if ctx == nil { - return nil, fmt.Errorf("nil Context") - } - - msg, fn, err := p.Respond(ctx) - // No-op the response when finish is invoked. - if msg != nil { - return binding.WithFinish(msg, func(err error) { - if fn != nil { - _ = fn(ctx, nil, nil) - } - }), err - } else { - return nil, err - } -} - -// Respond receives the next incoming HTTP request as a CloudEvent and waits -// for the response callback to invoked before continuing. -// Returns non-nil error if the incoming HTTP request fails to parse as a CloudEvent -// Returns io.EOF if the receiver is closed. -func (p *Protocol) Respond(ctx context.Context) (binding.Message, protocol.ResponseFn, error) { - if ctx == nil { - return nil, nil, fmt.Errorf("nil Context") - } - - select { - case in, ok := <-p.incoming: - if !ok { - return nil, nil, io.EOF - } - - if in.msg == nil { - return nil, in.respFn, in.err - } - return in.msg, in.respFn, in.err - - case <-ctx.Done(): - return nil, nil, io.EOF - } -} - -// ServeHTTP implements http.Handler. -// Blocks until ResponseFn is invoked. -func (p *Protocol) ServeHTTP(rw http.ResponseWriter, req *http.Request) { - // always apply limiter first using req context - ok, reset, err := p.limiter.Allow(req.Context(), req) - if err != nil { - p.incoming <- msgErr{msg: nil, err: fmt.Errorf("unable to acquire rate limit token: %w", err)} - rw.WriteHeader(http.StatusInternalServerError) - return - } - - if !ok { - rw.Header().Add("Retry-After", strconv.Itoa(int(reset))) - http.Error(rw, "limit exceeded", 429) - return - } - - // Filter the GET style methods: - switch req.Method { - case http.MethodOptions: - if p.OptionsHandlerFn == nil { - rw.WriteHeader(http.StatusMethodNotAllowed) - return - } - p.OptionsHandlerFn(rw, req) - return - - case http.MethodGet: - if p.GetHandlerFn == nil { - rw.WriteHeader(http.StatusMethodNotAllowed) - return - } - p.GetHandlerFn(rw, req) - return - - case http.MethodDelete: - if p.DeleteHandlerFn == nil { - rw.WriteHeader(http.StatusMethodNotAllowed) - return - } - p.DeleteHandlerFn(rw, req) - return - } - - m := NewMessageFromHttpRequest(req) - if m == nil { - // Should never get here unless ServeHTTP is called directly. - p.incoming <- msgErr{msg: nil, err: binding.ErrUnknownEncoding} - rw.WriteHeader(http.StatusBadRequest) - return // if there was no message, return. - } - - var finishErr error - m.OnFinish = func(err error) error { - finishErr = err - return nil - } - - wg := sync.WaitGroup{} - wg.Add(1) - var fn protocol.ResponseFn = func(ctx context.Context, respMsg binding.Message, res protocol.Result, transformers ...binding.Transformer) error { - // Unblock the ServeHTTP after the reply is written - defer func() { - wg.Done() - }() - - if finishErr != nil { - http.Error(rw, fmt.Sprintf("Cannot forward CloudEvent: %s", finishErr), http.StatusInternalServerError) - return finishErr - } - - status := http.StatusOK - var errMsg string - if res != nil { - var result *Result - switch { - case protocol.ResultAs(res, &result): - if result.StatusCode > 100 && result.StatusCode < 600 { - status = result.StatusCode - } - errMsg = fmt.Errorf(result.Format, result.Args...).Error() - case !protocol.IsACK(res): - // Map client errors to http status code - validationError := event.ValidationError{} - if errors.As(res, &validationError) { - status = http.StatusBadRequest - rw.Header().Set("content-type", "text/plain") - rw.WriteHeader(status) - _, _ = rw.Write([]byte(validationError.Error())) - return validationError - } else if errors.Is(res, binding.ErrUnknownEncoding) { - status = http.StatusUnsupportedMediaType - } else { - status = http.StatusInternalServerError - } - } - } - - if respMsg != nil { - err := WriteResponseWriter(ctx, respMsg, status, rw, transformers...) - return respMsg.Finish(err) - } - - rw.WriteHeader(status) - if _, err := rw.Write([]byte(errMsg)); err != nil { - return err - } - return nil - } - - p.incoming <- msgErr{msg: m, respFn: fn} // Send to Request - // Block until ResponseFn is invoked - wg.Wait() -} - -func defaultIsRetriableFunc(sc int) bool { - _, ok := defaultRetriableErrors[sc] - return ok -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_lifecycle.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_lifecycle.go deleted file mode 100644 index 04ef96915..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_lifecycle.go +++ /dev/null @@ -1,143 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package http - -import ( - "context" - "fmt" - "net" - "net/http" - "strings" - - "github.com/cloudevents/sdk-go/v2/protocol" -) - -var _ protocol.Opener = (*Protocol)(nil) - -func (p *Protocol) OpenInbound(ctx context.Context) error { - p.reMu.Lock() - defer p.reMu.Unlock() - - if p.Handler == nil { - p.Handler = http.NewServeMux() - } - - if !p.handlerRegistered { - // handler.Handle might panic if the user tries to use the same path as the sdk. - p.Handler.Handle(p.GetPath(), p) - p.handlerRegistered = true - } - - // After listener is invok - listener, err := p.listen() - if err != nil { - return err - } - - p.server = &http.Server{ - Addr: listener.Addr().String(), - Handler: attachMiddleware(p.Handler, p.middleware), - ReadTimeout: DefaultTimeout, - WriteTimeout: DefaultTimeout, - } - - // Shutdown - defer func() { - _ = p.server.Close() - p.server = nil - }() - - errChan := make(chan error) - go func() { - errChan <- p.server.Serve(listener) - }() - - // wait for the server to return or ctx.Done(). - select { - case <-ctx.Done(): - // Try a graceful shutdown. - ctx, cancel := context.WithTimeout(context.Background(), p.ShutdownTimeout) - defer cancel() - - shdwnErr := p.server.Shutdown(ctx) - if shdwnErr != nil { - shdwnErr = fmt.Errorf("shutting down HTTP server: %w", shdwnErr) - } - - // Wait for server goroutine to exit - rntmErr := <-errChan - if rntmErr != nil && rntmErr != http.ErrServerClosed { - rntmErr = fmt.Errorf("server failed during shutdown: %w", rntmErr) - - if shdwnErr != nil { - return fmt.Errorf("combined error during shutdown of HTTP server: %w, %v", - shdwnErr, rntmErr) - } - - return rntmErr - } - - return shdwnErr - - case err := <-errChan: - if err != nil { - return fmt.Errorf("during runtime of HTTP server: %w", err) - } - return nil - } -} - -// GetListeningPort returns the listening port. -// Returns -1 if it's not listening. -func (p *Protocol) GetListeningPort() int { - if listener := p.listener.Load(); listener != nil { - if tcpAddr, ok := listener.(net.Listener).Addr().(*net.TCPAddr); ok { - return tcpAddr.Port - } - } - return -1 -} - -// listen if not already listening, update t.Port -func (p *Protocol) listen() (net.Listener, error) { - if p.listener.Load() == nil { - port := 8080 - if p.Port != -1 { - port = p.Port - if port < 0 || port > 65535 { - return nil, fmt.Errorf("invalid port %d", port) - } - } - var err error - var listener net.Listener - if listener, err = net.Listen("tcp", fmt.Sprintf(":%d", port)); err != nil { - return nil, err - } - p.listener.Store(listener) - return listener, nil - } - return p.listener.Load().(net.Listener), nil -} - -// GetPath returns the path the transport is hosted on. If the path is '/', -// the transport will handle requests on any URI. To discover the true path -// a request was received on, inspect the context from Receive(cxt, ...) with -// TransportContextFrom(ctx). -func (p *Protocol) GetPath() string { - path := strings.TrimSpace(p.Path) - if len(path) > 0 { - return path - } - return "/" // default -} - -// attachMiddleware attaches the HTTP middleware to the specified handler. -func attachMiddleware(h http.Handler, middleware []Middleware) http.Handler { - for _, m := range middleware { - h = m(h) - } - return h -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_rate.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_rate.go deleted file mode 100644 index 9c4c10a29..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_rate.go +++ /dev/null @@ -1,34 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package http - -import ( - "context" - "net/http" -) - -type RateLimiter interface { - // Allow attempts to take one token from the rate limiter for the specified - // request. It returns ok when this operation was successful. In case ok is - // false, reset will indicate the time in seconds when it is safe to perform - // another attempt. An error is returned when this operation failed, e.g. due to - // a backend error. - Allow(ctx context.Context, r *http.Request) (ok bool, reset uint64, err error) - // Close terminates rate limiter and cleans up any data structures or - // connections that may remain open. After a store is stopped, Take() should - // always return zero values. - Close(ctx context.Context) error -} - -type noOpLimiter struct{} - -func (n noOpLimiter) Allow(ctx context.Context, r *http.Request) (bool, uint64, error) { - return true, 0, nil -} - -func (n noOpLimiter) Close(ctx context.Context) error { - return nil -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_retry.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_retry.go deleted file mode 100644 index 21fc7e9b3..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/protocol_retry.go +++ /dev/null @@ -1,126 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package http - -import ( - "bytes" - "context" - "errors" - "io" - "net/http" - "time" - - "go.uber.org/zap" - - "github.com/cloudevents/sdk-go/v2/binding" - cecontext "github.com/cloudevents/sdk-go/v2/context" - "github.com/cloudevents/sdk-go/v2/protocol" -) - -func (p *Protocol) do(ctx context.Context, req *http.Request) (binding.Message, error) { - params := cecontext.RetriesFrom(ctx) - - switch params.Strategy { - case cecontext.BackoffStrategyConstant, cecontext.BackoffStrategyLinear, cecontext.BackoffStrategyExponential: - return p.doWithRetry(ctx, params, req) - case cecontext.BackoffStrategyNone: - fallthrough - default: - return p.doOnce(req) - } -} - -func (p *Protocol) doOnce(req *http.Request) (binding.Message, protocol.Result) { - resp, err := p.Client.Do(req) - if err != nil { - return nil, protocol.NewReceipt(false, "%w", err) - } - - var result protocol.Result - if resp.StatusCode/100 == 2 { - result = protocol.ResultACK - } else { - result = protocol.ResultNACK - } - - return NewMessage(resp.Header, resp.Body), NewResult(resp.StatusCode, "%w", result) -} - -func (p *Protocol) doWithRetry(ctx context.Context, params *cecontext.RetryParams, req *http.Request) (binding.Message, error) { - start := time.Now() - retry := 0 - results := make([]protocol.Result, 0) - - var ( - body []byte - err error - ) - - if req != nil && req.Body != nil { - defer func() { - if err = req.Body.Close(); err != nil { - cecontext.LoggerFrom(ctx).Warnw("could not close request body", zap.Error(err)) - } - }() - body, err = io.ReadAll(req.Body) - if err != nil { - panic(err) - } - resetBody(req, body) - } - - for { - msg, result := p.doOnce(req) - - // Fast track common case. - if protocol.IsACK(result) { - return msg, NewRetriesResult(result, retry, start, results) - } - - var httpResult *Result - if errors.As(result, &httpResult) { - sc := httpResult.StatusCode - if !p.isRetriableFunc(sc) { - cecontext.LoggerFrom(ctx).Debugw("status code not retryable, will not try again", - zap.Error(httpResult), - zap.Int("statusCode", sc)) - return msg, NewRetriesResult(result, retry, start, results) - } - } - - // total tries = retry + 1 - if err = params.Backoff(ctx, retry+1); err != nil { - // do not try again. - cecontext.LoggerFrom(ctx).Debugw("backoff error, will not try again", zap.Error(err)) - return msg, NewRetriesResult(result, retry, start, results) - } - - retry++ - resetBody(req, body) - results = append(results, result) - if msg != nil { - // avoid leak, forget message, ignore error - _ = msg.Finish(nil) - } - } -} - -// reset body to allow it to be read multiple times, e.g. when retrying http -// requests -func resetBody(req *http.Request, body []byte) { - if req == nil || req.Body == nil { - return - } - - req.Body = io.NopCloser(bytes.NewReader(body)) - - // do not modify existing GetBody function - if req.GetBody == nil { - req.GetBody = func() (io.ReadCloser, error) { - return io.NopCloser(bytes.NewReader(body)), nil - } - } -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/result.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/result.go deleted file mode 100644 index 7a0b2626c..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/result.go +++ /dev/null @@ -1,60 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package http - -import ( - "errors" - "fmt" - - "github.com/cloudevents/sdk-go/v2/protocol" -) - -// NewResult returns a fully populated http Result that should be used as -// a transport.Result. -func NewResult(statusCode int, messageFmt string, args ...interface{}) protocol.Result { - return &Result{ - StatusCode: statusCode, - Format: messageFmt, - Args: args, - } -} - -// Result wraps the fields required to make adjustments for http Responses. -type Result struct { - StatusCode int - Format string - Args []interface{} -} - -// make sure Result implements error. -var _ error = (*Result)(nil) - -// Is returns if the target error is a Result type checking target. -func (e *Result) Is(target error) bool { - if o, ok := target.(*Result); ok { - return e.StatusCode == o.StatusCode - } - - // Special case for nil == ACK - if o, ok := target.(*protocol.Receipt); ok { - if e == nil && o.ACK { - return true - } - } - - // Allow for wrapped errors. - if e != nil { - err := fmt.Errorf(e.Format, e.Args...) - return errors.Is(err, target) - } - return false -} - -// Error returns the string that is formed by using the format string with the -// provided args. -func (e *Result) Error() string { - return fmt.Sprintf("%d: %v", e.StatusCode, fmt.Errorf(e.Format, e.Args...)) -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/retries_result.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/retries_result.go deleted file mode 100644 index f4046d522..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/retries_result.go +++ /dev/null @@ -1,59 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package http - -import ( - "fmt" - "time" - - "github.com/cloudevents/sdk-go/v2/protocol" -) - -// NewRetriesResult returns a http RetriesResult that should be used as -// a transport.Result without retries -func NewRetriesResult(result protocol.Result, retries int, startTime time.Time, attempts []protocol.Result) protocol.Result { - rr := &RetriesResult{ - Result: result, - Retries: retries, - Duration: time.Since(startTime), - } - if len(attempts) > 0 { - rr.Attempts = attempts - } - return rr -} - -// RetriesResult wraps the fields required to make adjustments for http Responses. -type RetriesResult struct { - // The last result - protocol.Result - - // Retries is the number of times the request was tried - Retries int - - // Duration records the time spent retrying. Exclude the successful request (if any) - Duration time.Duration - - // Attempts of all failed requests. Exclude last result. - Attempts []protocol.Result -} - -// make sure RetriesResult implements error. -var _ error = (*RetriesResult)(nil) - -// Is returns if the target error is a RetriesResult type checking target. -func (e *RetriesResult) Is(target error) bool { - return protocol.ResultIs(e.Result, target) -} - -// Error returns the string that is formed by using the format string with the -// provided args. -func (e *RetriesResult) Error() string { - if e.Retries == 0 { - return e.Result.Error() - } - return fmt.Sprintf("%s (%dx)", e.Result.Error(), e.Retries) -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/utility.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/utility.go deleted file mode 100644 index 350fc1cf6..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/utility.go +++ /dev/null @@ -1,89 +0,0 @@ -/* - Copyright 2022 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package http - -import ( - "bytes" - "context" - "encoding/json" - nethttp "net/http" - - "github.com/cloudevents/sdk-go/v2/binding" - "github.com/cloudevents/sdk-go/v2/event" -) - -// NewEventFromHTTPRequest returns an Event. -func NewEventFromHTTPRequest(req *nethttp.Request) (*event.Event, error) { - msg := NewMessageFromHttpRequest(req) - return binding.ToEvent(context.Background(), msg) -} - -// NewEventFromHTTPResponse returns an Event. -func NewEventFromHTTPResponse(resp *nethttp.Response) (*event.Event, error) { - msg := NewMessageFromHttpResponse(resp) - return binding.ToEvent(context.Background(), msg) -} - -// NewEventsFromHTTPRequest returns a batched set of Events from a HTTP Request -func NewEventsFromHTTPRequest(req *nethttp.Request) ([]event.Event, error) { - msg := NewMessageFromHttpRequest(req) - return binding.ToEvents(context.Background(), msg, msg.BodyReader) -} - -// NewEventsFromHTTPResponse returns a batched set of Events from a HTTP Response -func NewEventsFromHTTPResponse(resp *nethttp.Response) ([]event.Event, error) { - msg := NewMessageFromHttpResponse(resp) - return binding.ToEvents(context.Background(), msg, msg.BodyReader) -} - -// NewHTTPRequestFromEvent creates a http.Request object that can be used with any http.Client for a singular event. -// This is an HTTP POST action to the provided url. -func NewHTTPRequestFromEvent(ctx context.Context, url string, event event.Event) (*nethttp.Request, error) { - if err := event.Validate(); err != nil { - return nil, err - } - - req, err := nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, url, nil) - if err != nil { - return nil, err - } - if err := WriteRequest(ctx, (*binding.EventMessage)(&event), req); err != nil { - return nil, err - } - - return req, nil -} - -// NewHTTPRequestFromEvents creates a http.Request object that can be used with any http.Client for sending -// a batched set of events. This is an HTTP POST action to the provided url. -func NewHTTPRequestFromEvents(ctx context.Context, url string, events []event.Event) (*nethttp.Request, error) { - // Sending batch events is quite straightforward, as there is only JSON format, so a simple implementation. - for _, e := range events { - if err := e.Validate(); err != nil { - return nil, err - } - } - var buffer bytes.Buffer - err := json.NewEncoder(&buffer).Encode(events) - if err != nil { - return nil, err - } - - request, err := nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, url, &buffer) - if err != nil { - return nil, err - } - - request.Header.Set(ContentType, event.ApplicationCloudEventsBatchJSON) - - return request, nil -} - -// IsHTTPBatch returns if the current http.Request or http.Response is a batch event operation, by checking the -// header `Content-Type` value. -func IsHTTPBatch(header nethttp.Header) bool { - return header.Get(ContentType) == event.ApplicationCloudEventsBatchJSON -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/write_request.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/write_request.go deleted file mode 100644 index f22259a3a..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/write_request.go +++ /dev/null @@ -1,142 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package http - -import ( - "bytes" - "context" - "io" - "net/http" - "strings" - - "github.com/cloudevents/sdk-go/v2/binding" - "github.com/cloudevents/sdk-go/v2/binding/format" - "github.com/cloudevents/sdk-go/v2/binding/spec" - "github.com/cloudevents/sdk-go/v2/types" -) - -// WriteRequest fills the provided httpRequest with the message m. -// Using context you can tweak the encoding processing (more details on binding.Write documentation). -func WriteRequest(ctx context.Context, m binding.Message, httpRequest *http.Request, transformers ...binding.Transformer) error { - structuredWriter := (*httpRequestWriter)(httpRequest) - binaryWriter := (*httpRequestWriter)(httpRequest) - - _, err := binding.Write( - ctx, - m, - structuredWriter, - binaryWriter, - transformers..., - ) - return err -} - -type httpRequestWriter http.Request - -func (b *httpRequestWriter) SetStructuredEvent(ctx context.Context, format format.Format, event io.Reader) error { - b.Header.Set(ContentType, format.MediaType()) - return b.setBody(event) -} - -func (b *httpRequestWriter) Start(ctx context.Context) error { - return nil -} - -func (b *httpRequestWriter) End(ctx context.Context) error { - return nil -} - -func (b *httpRequestWriter) SetData(data io.Reader) error { - return b.setBody(data) -} - -// setBody is a cherry-pick of the implementation in http.NewRequestWithContext -func (b *httpRequestWriter) setBody(body io.Reader) error { - rc, ok := body.(io.ReadCloser) - if !ok && body != nil { - rc = io.NopCloser(body) - } - b.Body = rc - if body != nil { - switch v := body.(type) { - case *bytes.Buffer: - b.ContentLength = int64(v.Len()) - buf := v.Bytes() - b.GetBody = func() (io.ReadCloser, error) { - r := bytes.NewReader(buf) - return io.NopCloser(r), nil - } - case *bytes.Reader: - b.ContentLength = int64(v.Len()) - snapshot := *v - b.GetBody = func() (io.ReadCloser, error) { - r := snapshot - return io.NopCloser(&r), nil - } - case *strings.Reader: - b.ContentLength = int64(v.Len()) - snapshot := *v - b.GetBody = func() (io.ReadCloser, error) { - r := snapshot - return io.NopCloser(&r), nil - } - default: - // This is where we'd set it to -1 (at least - // if body != NoBody) to mean unknown, but - // that broke people during the Go 1.8 testing - // period. People depend on it being 0 I - // guess. Maybe retry later. See Issue 18117. - } - // For client requests, Request.ContentLength of 0 - // means either actually 0, or unknown. The only way - // to explicitly say that the ContentLength is zero is - // to set the Body to nil. But turns out too much code - // depends on NewRequest returning a non-nil Body, - // so we use a well-known ReadCloser variable instead - // and have the http package also treat that sentinel - // variable to mean explicitly zero. - if b.GetBody != nil && b.ContentLength == 0 { - b.Body = http.NoBody - b.GetBody = func() (io.ReadCloser, error) { return http.NoBody, nil } - } - } - return nil -} - -func (b *httpRequestWriter) SetAttribute(attribute spec.Attribute, value interface{}) error { - mapping := attributeHeadersMapping[attribute.Name()] - if value == nil { - delete(b.Header, mapping) - return nil - } - - // Http headers, everything is a string! - s, err := types.Format(value) - if err != nil { - return err - } - b.Header[mapping] = append(b.Header[mapping], s) - return nil -} - -func (b *httpRequestWriter) SetExtension(name string, value interface{}) error { - if value == nil { - delete(b.Header, extNameToHeaderName(name)) - return nil - } - // Http headers, everything is a string! - s, err := types.Format(value) - if err != nil { - return err - } - b.Header[extNameToHeaderName(name)] = []string{s} - return nil -} - -var ( - _ binding.StructuredWriter = (*httpRequestWriter)(nil) // Test it conforms to the interface - _ binding.BinaryWriter = (*httpRequestWriter)(nil) // Test it conforms to the interface -) diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/write_responsewriter.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/write_responsewriter.go deleted file mode 100644 index 41385dab1..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/http/write_responsewriter.go +++ /dev/null @@ -1,126 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package http - -import ( - "bytes" - "context" - "io" - "net/http" - "strconv" - "strings" - - "github.com/cloudevents/sdk-go/v2/binding" - "github.com/cloudevents/sdk-go/v2/binding/format" - "github.com/cloudevents/sdk-go/v2/binding/spec" - "github.com/cloudevents/sdk-go/v2/types" -) - -// WriteResponseWriter writes out to the the provided httpResponseWriter with the message m. -// Using context you can tweak the encoding processing (more details on binding.Write documentation). -func WriteResponseWriter(ctx context.Context, m binding.Message, status int, rw http.ResponseWriter, transformers ...binding.Transformer) error { - if status < 200 || status >= 600 { - status = http.StatusOK - } - writer := &httpResponseWriter{rw: rw, status: status} - - _, err := binding.Write( - ctx, - m, - writer, - writer, - transformers..., - ) - return err -} - -type httpResponseWriter struct { - rw http.ResponseWriter - status int - body io.Reader -} - -func (b *httpResponseWriter) SetStructuredEvent(ctx context.Context, format format.Format, event io.Reader) error { - b.rw.Header().Set(ContentType, format.MediaType()) - b.body = event - return b.finalizeWriter() -} - -func (b *httpResponseWriter) Start(ctx context.Context) error { - return nil -} - -func (b *httpResponseWriter) SetAttribute(attribute spec.Attribute, value interface{}) error { - mapping := attributeHeadersMapping[attribute.Name()] - if value == nil { - delete(b.rw.Header(), mapping) - } - - // Http headers, everything is a string! - s, err := types.Format(value) - if err != nil { - return err - } - b.rw.Header()[mapping] = append(b.rw.Header()[mapping], s) - return nil -} - -func (b *httpResponseWriter) SetExtension(name string, value interface{}) error { - if value == nil { - delete(b.rw.Header(), extNameToHeaderName(name)) - } - // Http headers, everything is a string! - s, err := types.Format(value) - if err != nil { - return err - } - b.rw.Header()[extNameToHeaderName(name)] = []string{s} - return nil -} - -func (b *httpResponseWriter) SetData(reader io.Reader) error { - b.body = reader - return nil -} - -func (b *httpResponseWriter) finalizeWriter() error { - if b.body != nil { - // Try to figure it out if we have a content-length - contentLength := -1 - switch v := b.body.(type) { - case *bytes.Buffer: - contentLength = v.Len() - case *bytes.Reader: - contentLength = v.Len() - case *strings.Reader: - contentLength = v.Len() - } - - if contentLength != -1 { - b.rw.Header().Add("Content-length", strconv.Itoa(contentLength)) - } - - // Finalize the headers. - b.rw.WriteHeader(b.status) - - // Write body. - _, err := io.Copy(b.rw, b.body) - if err != nil { - return err - } - } else { - // Finalize the headers. - b.rw.WriteHeader(b.status) - } - return nil -} - -func (b *httpResponseWriter) End(ctx context.Context) error { - return b.finalizeWriter() -} - -var _ binding.StructuredWriter = (*httpResponseWriter)(nil) // Test it conforms to the interface -var _ binding.BinaryWriter = (*httpResponseWriter)(nil) // Test it conforms to the interface diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/inbound.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/inbound.go deleted file mode 100644 index e7a74294d..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/inbound.go +++ /dev/null @@ -1,54 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package protocol - -import ( - "context" - - "github.com/cloudevents/sdk-go/v2/binding" -) - -// Receiver receives messages. -type Receiver interface { - // Receive blocks till a message is received or ctx expires. - // Receive can be invoked safely from different goroutines. - // - // A non-nil error means the receiver is closed. - // io.EOF means it closed cleanly, any other value indicates an error. - // The caller is responsible for `Finish()` the returned message - Receive(ctx context.Context) (binding.Message, error) -} - -// ReceiveCloser is a Receiver that can be closed. -type ReceiveCloser interface { - Receiver - Closer -} - -// ResponseFn is the function callback provided from Responder.Respond to allow -// for a receiver to "reply" to a message it receives. -// transformers are applied when the message is written on the wire. -type ResponseFn func(ctx context.Context, m binding.Message, r Result, transformers ...binding.Transformer) error - -// Responder receives messages and is given a callback to respond. -type Responder interface { - // Respond blocks till a message is received or ctx expires. - // Respond can be invoked safely from different goroutines. - // - // A non-nil error means the receiver is closed. - // io.EOF means it closed cleanly, any other value indicates an error. - // The caller is responsible for `Finish()` the returned message, - // while the protocol implementation is responsible for `Finish()` the response message. - // The caller MUST invoke ResponseFn, in order to avoid leaks. - // The correct flow for the caller is to finish the received message and then invoke the ResponseFn - Respond(ctx context.Context) (binding.Message, ResponseFn, error) -} - -// ResponderCloser is a Responder that can be closed. -type ResponderCloser interface { - Responder - Closer -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/lifecycle.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/lifecycle.go deleted file mode 100644 index 4a058c962..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/lifecycle.go +++ /dev/null @@ -1,23 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package protocol - -import ( - "context" -) - -// Opener is the common interface for things that need to be opened. -type Opener interface { - // OpenInbound is a blocking call and ctx is used to stop the Inbound message Receiver/Responder. - // Closing the context won't close the Receiver/Responder, aka it won't invoke Close(ctx). - OpenInbound(ctx context.Context) error -} - -// Closer is the common interface for things that can be closed. -// After invoking Close(ctx), you cannot reuse the object you closed. -type Closer interface { - Close(ctx context.Context) error -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/outbound.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/outbound.go deleted file mode 100644 index e44fa432a..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/outbound.go +++ /dev/null @@ -1,49 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package protocol - -import ( - "context" - - "github.com/cloudevents/sdk-go/v2/binding" -) - -// Sender sends messages. -type Sender interface { - // Send a message. - // - // Send returns when the "outbound" message has been sent. The Sender may - // still be expecting acknowledgment or holding other state for the message. - // - // m.Finish() is called when sending is finished (both succeeded or failed): - // expected acknowledgments (or errors) have been received, the Sender is - // no longer holding any state for the message. - // m.Finish() may be called during or after Send(). - // - // transformers are applied when the message is written on the wire. - Send(ctx context.Context, m binding.Message, transformers ...binding.Transformer) error -} - -// SendCloser is a Sender that can be closed. -type SendCloser interface { - Sender - Closer -} - -// Requester sends a message and receives a response -// -// Optional interface that may be implemented by protocols that support -// request/response correlation. -type Requester interface { - // Request sends m like Sender.Send() but also arranges to receive a response. - Request(ctx context.Context, m binding.Message, transformers ...binding.Transformer) (binding.Message, error) -} - -// RequesterCloser is a Requester that can be closed. -type RequesterCloser interface { - Requester - Closer -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/protocol/result.go b/vendor/github.com/cloudevents/sdk-go/v2/protocol/result.go deleted file mode 100644 index eae64e018..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/protocol/result.go +++ /dev/null @@ -1,127 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package protocol - -import ( - "errors" - "fmt" -) - -// Result leverages go's error wrapping. -type Result error - -// ResultIs reports whether any error in err's chain matches target. -// -// The chain consists of err itself followed by the sequence of errors obtained by -// repeatedly calling Unwrap. -// -// An error is considered to match a target if it is equal to that target or if -// it implements a method Is(error) bool such that Is(target) returns true. -// (text from errors/wrap.go) -var ResultIs = errors.Is - -// ResultAs finds the first error in err's chain that matches target, and if so, sets -// target to that error value and returns true. -// -// The chain consists of err itself followed by the sequence of errors obtained by -// repeatedly calling Unwrap. -// -// An error matches target if the error's concrete value is assignable to the value -// pointed to by target, or if the error has a method As(interface{}) bool such that -// As(target) returns true. In the latter case, the As method is responsible for -// setting target. -// -// As will panic if target is not a non-nil pointer to either a type that implements -// error, or to any interface type. As returns false if err is nil. -// (text from errors/wrap.go) -var ResultAs = errors.As - -func NewResult(messageFmt string, args ...interface{}) Result { - return fmt.Errorf(messageFmt, args...) -} - -// IsACK true means the recipient acknowledged the event. -func IsACK(target Result) bool { - // special case, nil target also means ACK. - if target == nil { - return true - } - - return ResultIs(target, ResultACK) -} - -// IsNACK true means the recipient did not acknowledge the event. -func IsNACK(target Result) bool { - return ResultIs(target, ResultNACK) -} - -// IsUndelivered true means the target result is not an ACK/NACK, but some other -// error unrelated to delivery not from the intended recipient. Likely target -// is an error that represents some part of the protocol is misconfigured or -// the event that was attempting to be sent was invalid. -func IsUndelivered(target Result) bool { - if target == nil { - // Short-circuit nil result is ACK. - return false - } - return !ResultIs(target, ResultACK) && !ResultIs(target, ResultNACK) -} - -var ( - ResultACK = NewReceipt(true, "") - ResultNACK = NewReceipt(false, "") -) - -// NewReceipt returns a fully populated protocol Receipt that should be used as -// a transport.Result. This type holds the base ACK/NACK results. -func NewReceipt(ack bool, messageFmt string, args ...interface{}) Result { - return &Receipt{ - Err: fmt.Errorf(messageFmt, args...), - ACK: ack, - } -} - -// Receipt wraps the fields required to understand if a protocol event is acknowledged. -type Receipt struct { - Err error - ACK bool -} - -// make sure Result implements error. -var _ error = (*Receipt)(nil) - -// Is returns if the target error is a Result type checking target. -func (e *Receipt) Is(target error) bool { - if o, ok := target.(*Receipt); ok { - if e == nil { - // Special case nil e as ACK. - return o.ACK - } - return e.ACK == o.ACK - } - // Allow for wrapped errors. - if e != nil { - return errors.Is(e.Err, target) - } - return false -} - -// Error returns the string that is formed by using the format string with the -// provided args. -func (e *Receipt) Error() string { - if e != nil { - return e.Err.Error() - } - return "" -} - -// Unwrap returns the wrapped error if exist or nil -func (e *Receipt) Unwrap() error { - if e != nil { - return errors.Unwrap(e.Err) - } - return nil -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/staticcheck.conf b/vendor/github.com/cloudevents/sdk-go/v2/staticcheck.conf deleted file mode 100644 index d6f269556..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/staticcheck.conf +++ /dev/null @@ -1,3 +0,0 @@ -checks = [ - "all", "-ST1003", -] \ No newline at end of file diff --git a/vendor/github.com/cloudevents/sdk-go/v2/types/allocate.go b/vendor/github.com/cloudevents/sdk-go/v2/types/allocate.go deleted file mode 100644 index 814626874..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/types/allocate.go +++ /dev/null @@ -1,41 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package types - -import "reflect" - -// Allocate allocates a new instance of type t and returns: -// asPtr is of type t if t is a pointer type and of type &t otherwise -// asValue is a Value of type t pointing to the same data as asPtr -func Allocate(obj interface{}) (asPtr interface{}, asValue reflect.Value) { - if obj == nil { - return nil, reflect.Value{} - } - - switch t := reflect.TypeOf(obj); t.Kind() { - case reflect.Ptr: - reflectPtr := reflect.New(t.Elem()) - asPtr = reflectPtr.Interface() - asValue = reflectPtr - case reflect.Map: - reflectPtr := reflect.MakeMap(t) - asPtr = reflectPtr.Interface() - asValue = reflectPtr - case reflect.String: - reflectPtr := reflect.New(t) - asPtr = "" - asValue = reflectPtr.Elem() - case reflect.Slice: - reflectPtr := reflect.MakeSlice(t, 0, 0) - asPtr = reflectPtr.Interface() - asValue = reflectPtr - default: - reflectPtr := reflect.New(t) - asPtr = reflectPtr.Interface() - asValue = reflectPtr.Elem() - } - return -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/types/doc.go b/vendor/github.com/cloudevents/sdk-go/v2/types/doc.go deleted file mode 100644 index 3a0a595a1..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/types/doc.go +++ /dev/null @@ -1,45 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -/* -Package types implements the CloudEvents type system. - -CloudEvents defines a set of abstract types for event context attributes. Each -type has a corresponding native Go type and a canonical string encoding. The -native Go types used to represent the CloudEvents types are: -bool, int32, string, []byte, *url.URL, time.Time - - +----------------+----------------+-----------------------------------+ - |CloudEvents Type|Native Type |Convertible From | - +================+================+===================================+ - |Bool |bool |bool | - +----------------+----------------+-----------------------------------+ - |Integer |int32 |Any numeric type with value in | - | | |range of int32 | - +----------------+----------------+-----------------------------------+ - |String |string |string | - +----------------+----------------+-----------------------------------+ - |Binary |[]byte |[]byte | - +----------------+----------------+-----------------------------------+ - |URI-Reference |*url.URL |url.URL, types.URIRef, types.URI | - +----------------+----------------+-----------------------------------+ - |URI |*url.URL |url.URL, types.URIRef, types.URI | - | | |Must be an absolute URI. | - +----------------+----------------+-----------------------------------+ - |Timestamp |time.Time |time.Time, types.Timestamp | - +----------------+----------------+-----------------------------------+ - -Extension attributes may be stored as a native type or a canonical string. The -To functions will convert to the desired from any convertible type -or from the canonical string form. - -The Parse and Format functions convert native types to/from -canonical strings. - -Note are no Parse or Format functions for URL or string. For URL use the -standard url.Parse() and url.URL.String(). The canonical string format of a -string is the string itself. -*/ -package types diff --git a/vendor/github.com/cloudevents/sdk-go/v2/types/timestamp.go b/vendor/github.com/cloudevents/sdk-go/v2/types/timestamp.go deleted file mode 100644 index ff049727d..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/types/timestamp.go +++ /dev/null @@ -1,75 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package types - -import ( - "encoding/json" - "encoding/xml" - "fmt" - "time" -) - -// Timestamp wraps time.Time to normalize the time layout to RFC3339. It is -// intended to enforce compliance with the CloudEvents spec for their -// definition of Timestamp. Custom marshal methods are implemented to ensure -// the outbound Timestamp is a string in the RFC3339 layout. -type Timestamp struct { - time.Time -} - -// ParseTimestamp attempts to parse the given time assuming RFC3339 layout -func ParseTimestamp(s string) (*Timestamp, error) { - if s == "" { - return nil, nil - } - tt, err := ParseTime(s) - return &Timestamp{Time: tt}, err -} - -// MarshalJSON implements a custom json marshal method used when this type is -// marshaled using json.Marshal. -func (t *Timestamp) MarshalJSON() ([]byte, error) { - if t == nil || t.IsZero() { - return []byte(`""`), nil - } - return []byte(fmt.Sprintf("%q", t)), nil -} - -// UnmarshalJSON implements the json unmarshal method used when this type is -// unmarshaled using json.Unmarshal. -func (t *Timestamp) UnmarshalJSON(b []byte) error { - var timestamp string - if err := json.Unmarshal(b, ×tamp); err != nil { - return err - } - var err error - t.Time, err = ParseTime(timestamp) - return err -} - -// MarshalXML implements a custom xml marshal method used when this type is -// marshaled using xml.Marshal. -func (t *Timestamp) MarshalXML(e *xml.Encoder, start xml.StartElement) error { - if t == nil || t.IsZero() { - return e.EncodeElement(nil, start) - } - return e.EncodeElement(t.String(), start) -} - -// UnmarshalXML implements the xml unmarshal method used when this type is -// unmarshaled using xml.Unmarshal. -func (t *Timestamp) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { - var timestamp string - if err := d.DecodeElement(×tamp, &start); err != nil { - return err - } - var err error - t.Time, err = ParseTime(timestamp) - return err -} - -// String outputs the time using RFC3339 format. -func (t Timestamp) String() string { return FormatTime(t.Time) } diff --git a/vendor/github.com/cloudevents/sdk-go/v2/types/uri.go b/vendor/github.com/cloudevents/sdk-go/v2/types/uri.go deleted file mode 100644 index bed608094..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/types/uri.go +++ /dev/null @@ -1,86 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package types - -import ( - "encoding/json" - "encoding/xml" - "fmt" - "net/url" -) - -// URI is a wrapper to url.URL. It is intended to enforce compliance with -// the CloudEvents spec for their definition of URI. Custom -// marshal methods are implemented to ensure the outbound URI object -// is a flat string. -type URI struct { - url.URL -} - -// ParseURI attempts to parse the given string as a URI. -func ParseURI(u string) *URI { - if u == "" { - return nil - } - pu, err := url.Parse(u) - if err != nil { - return nil - } - return &URI{URL: *pu} -} - -// MarshalJSON implements a custom json marshal method used when this type is -// marshaled using json.Marshal. -func (u URI) MarshalJSON() ([]byte, error) { - b := fmt.Sprintf("%q", u.String()) - return []byte(b), nil -} - -// UnmarshalJSON implements the json unmarshal method used when this type is -// unmarshaled using json.Unmarshal. -func (u *URI) UnmarshalJSON(b []byte) error { - var ref string - if err := json.Unmarshal(b, &ref); err != nil { - return err - } - r := ParseURI(ref) - if r != nil { - *u = *r - } - return nil -} - -// MarshalXML implements a custom xml marshal method used when this type is -// marshaled using xml.Marshal. -func (u URI) MarshalXML(e *xml.Encoder, start xml.StartElement) error { - return e.EncodeElement(u.String(), start) -} - -// UnmarshalXML implements the xml unmarshal method used when this type is -// unmarshaled using xml.Unmarshal. -func (u *URI) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { - var ref string - if err := d.DecodeElement(&ref, &start); err != nil { - return err - } - r := ParseURI(ref) - if r != nil { - *u = *r - } - return nil -} - -func (u URI) Validate() bool { - return u.IsAbs() -} - -// String returns the full string representation of the URI-Reference. -func (u *URI) String() string { - if u == nil { - return "" - } - return u.URL.String() -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/types/uriref.go b/vendor/github.com/cloudevents/sdk-go/v2/types/uriref.go deleted file mode 100644 index 22fa12314..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/types/uriref.go +++ /dev/null @@ -1,82 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package types - -import ( - "encoding/json" - "encoding/xml" - "fmt" - "net/url" -) - -// URIRef is a wrapper to url.URL. It is intended to enforce compliance with -// the CloudEvents spec for their definition of URI-Reference. Custom -// marshal methods are implemented to ensure the outbound URIRef object is -// is a flat string. -type URIRef struct { - url.URL -} - -// ParseURIRef attempts to parse the given string as a URI-Reference. -func ParseURIRef(u string) *URIRef { - if u == "" { - return nil - } - pu, err := url.Parse(u) - if err != nil { - return nil - } - return &URIRef{URL: *pu} -} - -// MarshalJSON implements a custom json marshal method used when this type is -// marshaled using json.Marshal. -func (u URIRef) MarshalJSON() ([]byte, error) { - b := fmt.Sprintf("%q", u.String()) - return []byte(b), nil -} - -// UnmarshalJSON implements the json unmarshal method used when this type is -// unmarshaled using json.Unmarshal. -func (u *URIRef) UnmarshalJSON(b []byte) error { - var ref string - if err := json.Unmarshal(b, &ref); err != nil { - return err - } - r := ParseURIRef(ref) - if r != nil { - *u = *r - } - return nil -} - -// MarshalXML implements a custom xml marshal method used when this type is -// marshaled using xml.Marshal. -func (u URIRef) MarshalXML(e *xml.Encoder, start xml.StartElement) error { - return e.EncodeElement(u.String(), start) -} - -// UnmarshalXML implements the xml unmarshal method used when this type is -// unmarshaled using xml.Unmarshal. -func (u *URIRef) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { - var ref string - if err := d.DecodeElement(&ref, &start); err != nil { - return err - } - r := ParseURIRef(ref) - if r != nil { - *u = *r - } - return nil -} - -// String returns the full string representation of the URI-Reference. -func (u *URIRef) String() string { - if u == nil { - return "" - } - return u.URL.String() -} diff --git a/vendor/github.com/cloudevents/sdk-go/v2/types/value.go b/vendor/github.com/cloudevents/sdk-go/v2/types/value.go deleted file mode 100644 index 14004d3e1..000000000 --- a/vendor/github.com/cloudevents/sdk-go/v2/types/value.go +++ /dev/null @@ -1,337 +0,0 @@ -/* - Copyright 2021 The CloudEvents Authors - SPDX-License-Identifier: Apache-2.0 -*/ - -package types - -import ( - "encoding/base64" - "fmt" - "math" - "net/url" - "reflect" - "strconv" - "time" -) - -// FormatBool returns canonical string format: "true" or "false" -func FormatBool(v bool) string { return strconv.FormatBool(v) } - -// FormatInteger returns canonical string format: decimal notation. -func FormatInteger(v int32) string { return strconv.Itoa(int(v)) } - -// FormatBinary returns canonical string format: standard base64 encoding -func FormatBinary(v []byte) string { return base64.StdEncoding.EncodeToString(v) } - -// FormatTime returns canonical string format: RFC3339 with nanoseconds -func FormatTime(v time.Time) string { return v.UTC().Format(time.RFC3339Nano) } - -// ParseBool parse canonical string format: "true" or "false" -func ParseBool(v string) (bool, error) { return strconv.ParseBool(v) } - -// ParseInteger parse canonical string format: decimal notation. -func ParseInteger(v string) (int32, error) { - // Accept floating-point but truncate to int32 as per CE spec. - f, err := strconv.ParseFloat(v, 64) - if err != nil { - return 0, err - } - if f > math.MaxInt32 || f < math.MinInt32 { - return 0, rangeErr(v) - } - return int32(f), nil -} - -// ParseBinary parse canonical string format: standard base64 encoding -func ParseBinary(v string) ([]byte, error) { return base64.StdEncoding.DecodeString(v) } - -// ParseTime parse canonical string format: RFC3339 with nanoseconds -func ParseTime(v string) (time.Time, error) { - t, err := time.Parse(time.RFC3339Nano, v) - if err != nil { - err := convertErr(time.Time{}, v) - err.extra = ": not in RFC3339 format" - return time.Time{}, err - } - return t, nil -} - -// Format returns the canonical string format of v, where v can be -// any type that is convertible to a CloudEvents type. -func Format(v interface{}) (string, error) { - v, err := Validate(v) - if err != nil { - return "", err - } - switch v := v.(type) { - case bool: - return FormatBool(v), nil - case int32: - return FormatInteger(v), nil - case string: - return v, nil - case []byte: - return FormatBinary(v), nil - case URI: - return v.String(), nil - case URIRef: - // url.URL is often passed by pointer so allow both - return v.String(), nil - case Timestamp: - return FormatTime(v.Time), nil - default: - return "", fmt.Errorf("%T is not a CloudEvents type", v) - } -} - -// Validate v is a valid CloudEvents attribute value, convert it to one of: -// bool, int32, string, []byte, types.URI, types.URIRef, types.Timestamp -func Validate(v interface{}) (interface{}, error) { - switch v := v.(type) { - case bool, int32, string, []byte: - return v, nil // Already a CloudEvents type, no validation needed. - - case uint, uintptr, uint8, uint16, uint32, uint64: - u := reflect.ValueOf(v).Uint() - if u > math.MaxInt32 { - return nil, rangeErr(v) - } - return int32(u), nil - case int, int8, int16, int64: - i := reflect.ValueOf(v).Int() - if i > math.MaxInt32 || i < math.MinInt32 { - return nil, rangeErr(v) - } - return int32(i), nil - case float32, float64: - f := reflect.ValueOf(v).Float() - if f > math.MaxInt32 || f < math.MinInt32 { - return nil, rangeErr(v) - } - return int32(f), nil - - case *url.URL: - if v == nil { - break - } - return URI{URL: *v}, nil - case url.URL: - return URI{URL: v}, nil - case *URIRef: - if v != nil { - return *v, nil - } - return nil, nil - case URIRef: - return v, nil - case *URI: - if v != nil { - return *v, nil - } - return nil, nil - case URI: - return v, nil - case time.Time: - return Timestamp{Time: v}, nil - case *time.Time: - if v == nil { - break - } - return Timestamp{Time: *v}, nil - case Timestamp: - return v, nil - } - rx := reflect.ValueOf(v) - if rx.Kind() == reflect.Ptr && !rx.IsNil() { - // Allow pointers-to convertible types - return Validate(rx.Elem().Interface()) - } - return nil, fmt.Errorf("invalid CloudEvents value: %#v", v) -} - -// Clone v clones a CloudEvents attribute value, which is one of the valid types: -// -// bool, int32, string, []byte, types.URI, types.URIRef, types.Timestamp -// -// Returns the same type -// Panics if the type is not valid -func Clone(v interface{}) interface{} { - if v == nil { - return nil - } - switch v := v.(type) { - case bool, int32, string, nil: - return v // Already a CloudEvents type, no validation needed. - case []byte: - clone := make([]byte, len(v)) - copy(clone, v) - return v - case url.URL: - return URI{v} - case *url.URL: - return &URI{*v} - case URIRef: - return v - case *URIRef: - return &URIRef{v.URL} - case URI: - return v - case *URI: - return &URI{v.URL} - case time.Time: - return Timestamp{v} - case *time.Time: - return &Timestamp{*v} - case Timestamp: - return v - case *Timestamp: - return &Timestamp{v.Time} - } - panic(fmt.Errorf("invalid CloudEvents value: %#v", v)) -} - -// ToBool accepts a bool value or canonical "true"/"false" string. -func ToBool(v interface{}) (bool, error) { - v, err := Validate(v) - if err != nil { - return false, err - } - switch v := v.(type) { - case bool: - return v, nil - case string: - return ParseBool(v) - default: - return false, convertErr(true, v) - } -} - -// ToInteger accepts any numeric value in int32 range, or canonical string. -func ToInteger(v interface{}) (int32, error) { - v, err := Validate(v) - if err != nil { - return 0, err - } - switch v := v.(type) { - case int32: - return v, nil - case string: - return ParseInteger(v) - default: - return 0, convertErr(int32(0), v) - } -} - -// ToString returns a string value unaltered. -// -// This function does not perform canonical string encoding, use one of the -// Format functions for that. -func ToString(v interface{}) (string, error) { - v, err := Validate(v) - if err != nil { - return "", err - } - switch v := v.(type) { - case string: - return v, nil - default: - return "", convertErr("", v) - } -} - -// ToBinary returns a []byte value, decoding from base64 string if necessary. -func ToBinary(v interface{}) ([]byte, error) { - v, err := Validate(v) - if err != nil { - return nil, err - } - switch v := v.(type) { - case []byte: - return v, nil - case string: - return base64.StdEncoding.DecodeString(v) - default: - return nil, convertErr([]byte(nil), v) - } -} - -// ToURL returns a *url.URL value, parsing from string if necessary. -func ToURL(v interface{}) (*url.URL, error) { - v, err := Validate(v) - if err != nil { - return nil, err - } - switch v := v.(type) { - case *URI: - return &v.URL, nil - case URI: - return &v.URL, nil - case *URIRef: - return &v.URL, nil - case URIRef: - return &v.URL, nil - case string: - u, err := url.Parse(v) - if err != nil { - return nil, err - } - return u, nil - default: - return nil, convertErr((*url.URL)(nil), v) - } -} - -// ToTime returns a time.Time value, parsing from RFC3339 string if necessary. -func ToTime(v interface{}) (time.Time, error) { - v, err := Validate(v) - if err != nil { - return time.Time{}, err - } - switch v := v.(type) { - case Timestamp: - return v.Time, nil - case string: - ts, err := time.Parse(time.RFC3339Nano, v) - if err != nil { - return time.Time{}, err - } - return ts, nil - default: - return time.Time{}, convertErr(time.Time{}, v) - } -} - -func IsZero(v interface{}) bool { - // Fast path - if v == nil { - return true - } - if s, ok := v.(string); ok && s == "" { - return true - } - return reflect.ValueOf(v).IsZero() -} - -type ConvertErr struct { - // Value being converted - Value interface{} - // Type of attempted conversion - Type reflect.Type - - extra string -} - -func (e *ConvertErr) Error() string { - return fmt.Sprintf("cannot convert %#v to %s%s", e.Value, e.Type, e.extra) -} - -func convertErr(target, v interface{}) *ConvertErr { - return &ConvertErr{Value: v, Type: reflect.TypeOf(target)} -} - -func rangeErr(v interface{}) error { - e := convertErr(int32(0), v) - e.extra = ": out of range" - return e -} diff --git a/vendor/github.com/containerd/stargz-snapshotter/estargz/LICENSE b/vendor/github.com/containerd/stargz-snapshotter/estargz/LICENSE deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/containerd/stargz-snapshotter/estargz/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - 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 "[]" - 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 - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/containerd/stargz-snapshotter/estargz/build.go b/vendor/github.com/containerd/stargz-snapshotter/estargz/build.go deleted file mode 100644 index b071cea51..000000000 --- a/vendor/github.com/containerd/stargz-snapshotter/estargz/build.go +++ /dev/null @@ -1,690 +0,0 @@ -/* - Copyright The containerd 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. -*/ - -/* - Copyright 2019 The Go Authors. All rights reserved. - Use of this source code is governed by a BSD-style - license that can be found in the LICENSE file. -*/ - -package estargz - -import ( - "archive/tar" - "bytes" - "compress/gzip" - "context" - "errors" - "fmt" - "io" - "os" - "path" - "runtime" - "strings" - "sync" - - "github.com/containerd/stargz-snapshotter/estargz/errorutil" - "github.com/klauspost/compress/zstd" - digest "github.com/opencontainers/go-digest" - "golang.org/x/sync/errgroup" -) - -type options struct { - chunkSize int - compressionLevel int - prioritizedFiles []string - missedPrioritizedFiles *[]string - compression Compression - ctx context.Context - minChunkSize int -} - -type Option func(o *options) error - -// WithChunkSize option specifies the chunk size of eStargz blob to build. -func WithChunkSize(chunkSize int) Option { - return func(o *options) error { - o.chunkSize = chunkSize - return nil - } -} - -// WithCompressionLevel option specifies the gzip compression level. -// The default is gzip.BestCompression. -// This option will be ignored if WithCompression option is used. -// See also: https://godoc.org/compress/gzip#pkg-constants -func WithCompressionLevel(level int) Option { - return func(o *options) error { - o.compressionLevel = level - return nil - } -} - -// WithPrioritizedFiles option specifies the list of prioritized files. -// These files must be complete paths that are absolute or relative to "/" -// For example, all of "foo/bar", "/foo/bar", "./foo/bar" and "../foo/bar" -// are treated as "/foo/bar". -func WithPrioritizedFiles(files []string) Option { - return func(o *options) error { - o.prioritizedFiles = files - return nil - } -} - -// WithAllowPrioritizeNotFound makes Build continue the execution even if some -// of prioritized files specified by WithPrioritizedFiles option aren't found -// in the input tar. Instead, this records all missed file names to the passed -// slice. -func WithAllowPrioritizeNotFound(missedFiles *[]string) Option { - return func(o *options) error { - if missedFiles == nil { - return fmt.Errorf("WithAllowPrioritizeNotFound: slice must be passed") - } - o.missedPrioritizedFiles = missedFiles - return nil - } -} - -// WithCompression specifies compression algorithm to be used. -// Default is gzip. -func WithCompression(compression Compression) Option { - return func(o *options) error { - o.compression = compression - return nil - } -} - -// WithContext specifies a context that can be used for clean canceleration. -func WithContext(ctx context.Context) Option { - return func(o *options) error { - o.ctx = ctx - return nil - } -} - -// WithMinChunkSize option specifies the minimal number of bytes of data -// must be written in one gzip stream. -// By increasing this number, one gzip stream can contain multiple files -// and it hopefully leads to smaller result blob. -// NOTE: This adds a TOC property that old reader doesn't understand. -func WithMinChunkSize(minChunkSize int) Option { - return func(o *options) error { - o.minChunkSize = minChunkSize - return nil - } -} - -// Blob is an eStargz blob. -type Blob struct { - io.ReadCloser - diffID digest.Digester - tocDigest digest.Digest -} - -// DiffID returns the digest of uncompressed blob. -// It is only valid to call DiffID after Close. -func (b *Blob) DiffID() digest.Digest { - return b.diffID.Digest() -} - -// TOCDigest returns the digest of uncompressed TOC JSON. -func (b *Blob) TOCDigest() digest.Digest { - return b.tocDigest -} - -// Build builds an eStargz blob which is an extended version of stargz, from a blob (gzip, zstd -// or plain tar) passed through the argument. If there are some prioritized files are listed in -// the option, these files are grouped as "prioritized" and can be used for runtime optimization -// (e.g. prefetch). This function builds a blob in parallel, with dividing that blob into several -// (at least the number of runtime.GOMAXPROCS(0)) sub-blobs. -func Build(tarBlob *io.SectionReader, opt ...Option) (_ *Blob, rErr error) { - var opts options - opts.compressionLevel = gzip.BestCompression // BestCompression by default - for _, o := range opt { - if err := o(&opts); err != nil { - return nil, err - } - } - if opts.compression == nil { - opts.compression = newGzipCompressionWithLevel(opts.compressionLevel) - } - layerFiles := newTempFiles() - ctx := opts.ctx - if ctx == nil { - ctx = context.Background() - } - done := make(chan struct{}) - defer close(done) - go func() { - select { - case <-done: - // nop - case <-ctx.Done(): - layerFiles.CleanupAll() - } - }() - defer func() { - if rErr != nil { - if err := layerFiles.CleanupAll(); err != nil { - rErr = fmt.Errorf("failed to cleanup tmp files: %v: %w", err, rErr) - } - } - if cErr := ctx.Err(); cErr != nil { - rErr = fmt.Errorf("error from context %q: %w", cErr, rErr) - } - }() - tarBlob, err := decompressBlob(tarBlob, layerFiles) - if err != nil { - return nil, err - } - entries, err := sortEntries(tarBlob, opts.prioritizedFiles, opts.missedPrioritizedFiles) - if err != nil { - return nil, err - } - var tarParts [][]*entry - if opts.minChunkSize > 0 { - // Each entry needs to know the size of the current gzip stream so they - // cannot be processed in parallel. - tarParts = [][]*entry{entries} - } else { - tarParts = divideEntries(entries, runtime.GOMAXPROCS(0)) - } - writers := make([]*Writer, len(tarParts)) - payloads := make([]*os.File, len(tarParts)) - var mu sync.Mutex - var eg errgroup.Group - for i, parts := range tarParts { - i, parts := i, parts - // builds verifiable stargz sub-blobs - eg.Go(func() error { - esgzFile, err := layerFiles.TempFile("", "esgzdata") - if err != nil { - return err - } - sw := NewWriterWithCompressor(esgzFile, opts.compression) - sw.ChunkSize = opts.chunkSize - sw.MinChunkSize = opts.minChunkSize - if sw.needsOpenGzEntries == nil { - sw.needsOpenGzEntries = make(map[string]struct{}) - } - for _, f := range []string{PrefetchLandmark, NoPrefetchLandmark} { - sw.needsOpenGzEntries[f] = struct{}{} - } - if err := sw.AppendTar(readerFromEntries(parts...)); err != nil { - return err - } - mu.Lock() - writers[i] = sw - payloads[i] = esgzFile - mu.Unlock() - return nil - }) - } - if err := eg.Wait(); err != nil { - rErr = err - return nil, err - } - tocAndFooter, tocDgst, err := closeWithCombine(writers...) - if err != nil { - rErr = err - return nil, err - } - var rs []io.Reader - for _, p := range payloads { - fs, err := fileSectionReader(p) - if err != nil { - return nil, err - } - rs = append(rs, fs) - } - diffID := digest.Canonical.Digester() - pr, pw := io.Pipe() - go func() { - r, err := opts.compression.Reader(io.TeeReader(io.MultiReader(append(rs, tocAndFooter)...), pw)) - if err != nil { - pw.CloseWithError(err) - return - } - defer r.Close() - if _, err := io.Copy(diffID.Hash(), r); err != nil { - pw.CloseWithError(err) - return - } - pw.Close() - }() - return &Blob{ - ReadCloser: readCloser{ - Reader: pr, - closeFunc: layerFiles.CleanupAll, - }, - tocDigest: tocDgst, - diffID: diffID, - }, nil -} - -// closeWithCombine takes unclosed Writers and close them. This also returns the -// toc that combined all Writers into. -// Writers doesn't write TOC and footer to the underlying writers so they can be -// combined into a single eStargz and tocAndFooter returned by this function can -// be appended at the tail of that combined blob. -func closeWithCombine(ws ...*Writer) (tocAndFooterR io.Reader, tocDgst digest.Digest, err error) { - if len(ws) == 0 { - return nil, "", fmt.Errorf("at least one writer must be passed") - } - for _, w := range ws { - if w.closed { - return nil, "", fmt.Errorf("writer must be unclosed") - } - defer func(w *Writer) { w.closed = true }(w) - if err := w.closeGz(); err != nil { - return nil, "", err - } - if err := w.bw.Flush(); err != nil { - return nil, "", err - } - } - var ( - mtoc = new(JTOC) - currentOffset int64 - ) - mtoc.Version = ws[0].toc.Version - for _, w := range ws { - for _, e := range w.toc.Entries { - // Recalculate Offset of non-empty files/chunks - if (e.Type == "reg" && e.Size > 0) || e.Type == "chunk" { - e.Offset += currentOffset - } - mtoc.Entries = append(mtoc.Entries, e) - } - if w.toc.Version > mtoc.Version { - mtoc.Version = w.toc.Version - } - currentOffset += w.cw.n - } - - return tocAndFooter(ws[0].compressor, mtoc, currentOffset) -} - -func tocAndFooter(compressor Compressor, toc *JTOC, offset int64) (io.Reader, digest.Digest, error) { - buf := new(bytes.Buffer) - tocDigest, err := compressor.WriteTOCAndFooter(buf, offset, toc, nil) - if err != nil { - return nil, "", err - } - return buf, tocDigest, nil -} - -// divideEntries divides passed entries to the parts at least the number specified by the -// argument. -func divideEntries(entries []*entry, minPartsNum int) (set [][]*entry) { - var estimatedSize int64 - for _, e := range entries { - estimatedSize += e.header.Size - } - unitSize := estimatedSize / int64(minPartsNum) - var ( - nextEnd = unitSize - offset int64 - ) - set = append(set, []*entry{}) - for _, e := range entries { - set[len(set)-1] = append(set[len(set)-1], e) - offset += e.header.Size - if offset > nextEnd { - set = append(set, []*entry{}) - nextEnd += unitSize - } - } - return -} - -var errNotFound = errors.New("not found") - -// sortEntries reads the specified tar blob and returns a list of tar entries. -// If some of prioritized files are specified, the list starts from these -// files with keeping the order specified by the argument. -func sortEntries(in io.ReaderAt, prioritized []string, missedPrioritized *[]string) ([]*entry, error) { - - // Import tar file. - intar, err := importTar(in) - if err != nil { - return nil, fmt.Errorf("failed to sort: %w", err) - } - - // Sort the tar file respecting to the prioritized files list. - sorted := &tarFile{} - for _, l := range prioritized { - if err := moveRec(l, intar, sorted); err != nil { - if errors.Is(err, errNotFound) && missedPrioritized != nil { - *missedPrioritized = append(*missedPrioritized, l) - continue // allow not found - } - return nil, fmt.Errorf("failed to sort tar entries: %w", err) - } - } - if len(prioritized) == 0 { - sorted.add(&entry{ - header: &tar.Header{ - Name: NoPrefetchLandmark, - Typeflag: tar.TypeReg, - Size: int64(len([]byte{landmarkContents})), - }, - payload: bytes.NewReader([]byte{landmarkContents}), - }) - } else { - sorted.add(&entry{ - header: &tar.Header{ - Name: PrefetchLandmark, - Typeflag: tar.TypeReg, - Size: int64(len([]byte{landmarkContents})), - }, - payload: bytes.NewReader([]byte{landmarkContents}), - }) - } - - // Dump all entry and concatinate them. - return append(sorted.dump(), intar.dump()...), nil -} - -// readerFromEntries returns a reader of tar archive that contains entries passed -// through the arguments. -func readerFromEntries(entries ...*entry) io.Reader { - pr, pw := io.Pipe() - go func() { - tw := tar.NewWriter(pw) - defer tw.Close() - for _, entry := range entries { - if err := tw.WriteHeader(entry.header); err != nil { - pw.CloseWithError(fmt.Errorf("Failed to write tar header: %v", err)) - return - } - if _, err := io.Copy(tw, entry.payload); err != nil { - pw.CloseWithError(fmt.Errorf("Failed to write tar payload: %v", err)) - return - } - } - pw.Close() - }() - return pr -} - -func importTar(in io.ReaderAt) (*tarFile, error) { - tf := &tarFile{} - pw, err := newCountReadSeeker(in) - if err != nil { - return nil, fmt.Errorf("failed to make position watcher: %w", err) - } - tr := tar.NewReader(pw) - - // Walk through all nodes. - for { - // Fetch and parse next header. - h, err := tr.Next() - if err != nil { - if err == io.EOF { - break - } else { - return nil, fmt.Errorf("failed to parse tar file, %w", err) - } - } - switch cleanEntryName(h.Name) { - case PrefetchLandmark, NoPrefetchLandmark: - // Ignore existing landmark - continue - } - - // Add entry. If it already exists, replace it. - if _, ok := tf.get(h.Name); ok { - tf.remove(h.Name) - } - tf.add(&entry{ - header: h, - payload: io.NewSectionReader(in, pw.currentPos(), h.Size), - }) - } - - return tf, nil -} - -func moveRec(name string, in *tarFile, out *tarFile) error { - name = cleanEntryName(name) - if name == "" { // root directory. stop recursion. - if e, ok := in.get(name); ok { - // entry of the root directory exists. we should move it as well. - // this case will occur if tar entries are prefixed with "./", "/", etc. - out.add(e) - in.remove(name) - } - return nil - } - - _, okIn := in.get(name) - _, okOut := out.get(name) - if !okIn && !okOut { - return fmt.Errorf("file: %q: %w", name, errNotFound) - } - - parent, _ := path.Split(strings.TrimSuffix(name, "/")) - if err := moveRec(parent, in, out); err != nil { - return err - } - if e, ok := in.get(name); ok && e.header.Typeflag == tar.TypeLink { - if err := moveRec(e.header.Linkname, in, out); err != nil { - return err - } - } - if e, ok := in.get(name); ok { - out.add(e) - in.remove(name) - } - return nil -} - -type entry struct { - header *tar.Header - payload io.ReadSeeker -} - -type tarFile struct { - index map[string]*entry - stream []*entry -} - -func (f *tarFile) add(e *entry) { - if f.index == nil { - f.index = make(map[string]*entry) - } - f.index[cleanEntryName(e.header.Name)] = e - f.stream = append(f.stream, e) -} - -func (f *tarFile) remove(name string) { - name = cleanEntryName(name) - if f.index != nil { - delete(f.index, name) - } - var filtered []*entry - for _, e := range f.stream { - if cleanEntryName(e.header.Name) == name { - continue - } - filtered = append(filtered, e) - } - f.stream = filtered -} - -func (f *tarFile) get(name string) (e *entry, ok bool) { - if f.index == nil { - return nil, false - } - e, ok = f.index[cleanEntryName(name)] - return -} - -func (f *tarFile) dump() []*entry { - return f.stream -} - -type readCloser struct { - io.Reader - closeFunc func() error -} - -func (rc readCloser) Close() error { - return rc.closeFunc() -} - -func fileSectionReader(file *os.File) (*io.SectionReader, error) { - info, err := file.Stat() - if err != nil { - return nil, err - } - return io.NewSectionReader(file, 0, info.Size()), nil -} - -func newTempFiles() *tempFiles { - return &tempFiles{} -} - -type tempFiles struct { - files []*os.File - filesMu sync.Mutex - cleanupOnce sync.Once -} - -func (tf *tempFiles) TempFile(dir, pattern string) (*os.File, error) { - f, err := os.CreateTemp(dir, pattern) - if err != nil { - return nil, err - } - tf.filesMu.Lock() - tf.files = append(tf.files, f) - tf.filesMu.Unlock() - return f, nil -} - -func (tf *tempFiles) CleanupAll() (err error) { - tf.cleanupOnce.Do(func() { - err = tf.cleanupAll() - }) - return -} - -func (tf *tempFiles) cleanupAll() error { - tf.filesMu.Lock() - defer tf.filesMu.Unlock() - var allErr []error - for _, f := range tf.files { - if err := f.Close(); err != nil { - allErr = append(allErr, err) - } - if err := os.Remove(f.Name()); err != nil { - allErr = append(allErr, err) - } - } - tf.files = nil - return errorutil.Aggregate(allErr) -} - -func newCountReadSeeker(r io.ReaderAt) (*countReadSeeker, error) { - pos := int64(0) - return &countReadSeeker{r: r, cPos: &pos}, nil -} - -type countReadSeeker struct { - r io.ReaderAt - cPos *int64 - - mu sync.Mutex -} - -func (cr *countReadSeeker) Read(p []byte) (int, error) { - cr.mu.Lock() - defer cr.mu.Unlock() - - n, err := cr.r.ReadAt(p, *cr.cPos) - if err == nil { - *cr.cPos += int64(n) - } - return n, err -} - -func (cr *countReadSeeker) Seek(offset int64, whence int) (int64, error) { - cr.mu.Lock() - defer cr.mu.Unlock() - - switch whence { - default: - return 0, fmt.Errorf("Unknown whence: %v", whence) - case io.SeekStart: - case io.SeekCurrent: - offset += *cr.cPos - case io.SeekEnd: - return 0, fmt.Errorf("Unsupported whence: %v", whence) - } - - if offset < 0 { - return 0, fmt.Errorf("invalid offset") - } - *cr.cPos = offset - return offset, nil -} - -func (cr *countReadSeeker) currentPos() int64 { - cr.mu.Lock() - defer cr.mu.Unlock() - - return *cr.cPos -} - -func decompressBlob(org *io.SectionReader, tmp *tempFiles) (*io.SectionReader, error) { - if org.Size() < 4 { - return org, nil - } - src := make([]byte, 4) - if _, err := org.Read(src); err != nil && err != io.EOF { - return nil, err - } - var dR io.Reader - if bytes.Equal([]byte{0x1F, 0x8B, 0x08}, src[:3]) { - // gzip - dgR, err := gzip.NewReader(io.NewSectionReader(org, 0, org.Size())) - if err != nil { - return nil, err - } - defer dgR.Close() - dR = io.Reader(dgR) - } else if bytes.Equal([]byte{0x28, 0xb5, 0x2f, 0xfd}, src[:4]) { - // zstd - dzR, err := zstd.NewReader(io.NewSectionReader(org, 0, org.Size())) - if err != nil { - return nil, err - } - defer dzR.Close() - dR = io.Reader(dzR) - } else { - // uncompressed - return io.NewSectionReader(org, 0, org.Size()), nil - } - b, err := tmp.TempFile("", "uncompresseddata") - if err != nil { - return nil, err - } - if _, err := io.Copy(b, dR); err != nil { - return nil, err - } - return fileSectionReader(b) -} diff --git a/vendor/github.com/containerd/stargz-snapshotter/estargz/errorutil/errors.go b/vendor/github.com/containerd/stargz-snapshotter/estargz/errorutil/errors.go deleted file mode 100644 index 6de78b02d..000000000 --- a/vendor/github.com/containerd/stargz-snapshotter/estargz/errorutil/errors.go +++ /dev/null @@ -1,40 +0,0 @@ -/* - Copyright The containerd 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 errorutil - -import ( - "errors" - "fmt" - "strings" -) - -// Aggregate combines a list of errors into a single new error. -func Aggregate(errs []error) error { - switch len(errs) { - case 0: - return nil - case 1: - return errs[0] - default: - points := make([]string, len(errs)+1) - points[0] = fmt.Sprintf("%d error(s) occurred:", len(errs)) - for i, err := range errs { - points[i+1] = fmt.Sprintf("* %s", err) - } - return errors.New(strings.Join(points, "\n\t")) - } -} diff --git a/vendor/github.com/containerd/stargz-snapshotter/estargz/estargz.go b/vendor/github.com/containerd/stargz-snapshotter/estargz/estargz.go deleted file mode 100644 index f4d554655..000000000 --- a/vendor/github.com/containerd/stargz-snapshotter/estargz/estargz.go +++ /dev/null @@ -1,1223 +0,0 @@ -/* - Copyright The containerd 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. -*/ - -/* - Copyright 2019 The Go Authors. All rights reserved. - Use of this source code is governed by a BSD-style - license that can be found in the LICENSE file. -*/ - -package estargz - -import ( - "bufio" - "bytes" - "compress/gzip" - "crypto/sha256" - "errors" - "fmt" - "hash" - "io" - "os" - "path" - "sort" - "strings" - "sync" - "time" - - "github.com/containerd/stargz-snapshotter/estargz/errorutil" - digest "github.com/opencontainers/go-digest" - "github.com/vbatts/tar-split/archive/tar" -) - -// A Reader permits random access reads from a stargz file. -type Reader struct { - sr *io.SectionReader - toc *JTOC - tocDigest digest.Digest - - // m stores all non-chunk entries, keyed by name. - m map[string]*TOCEntry - - // chunks stores all TOCEntry values for regular files that - // are split up. For a file with a single chunk, it's only - // stored in m. - chunks map[string][]*TOCEntry - - decompressor Decompressor -} - -type openOpts struct { - tocOffset int64 - decompressors []Decompressor - telemetry *Telemetry -} - -// OpenOption is an option used during opening the layer -type OpenOption func(o *openOpts) error - -// WithTOCOffset option specifies the offset of TOC -func WithTOCOffset(tocOffset int64) OpenOption { - return func(o *openOpts) error { - o.tocOffset = tocOffset - return nil - } -} - -// WithDecompressors option specifies decompressors to use. -// Default is gzip-based decompressor. -func WithDecompressors(decompressors ...Decompressor) OpenOption { - return func(o *openOpts) error { - o.decompressors = decompressors - return nil - } -} - -// WithTelemetry option specifies the telemetry hooks -func WithTelemetry(telemetry *Telemetry) OpenOption { - return func(o *openOpts) error { - o.telemetry = telemetry - return nil - } -} - -// MeasureLatencyHook is a func which takes start time and records the diff -type MeasureLatencyHook func(time.Time) - -// Telemetry is a struct which defines telemetry hooks. By implementing these hooks you should be able to record -// the latency metrics of the respective steps of estargz open operation. To be used with estargz.OpenWithTelemetry(...) -type Telemetry struct { - GetFooterLatency MeasureLatencyHook // measure time to get stargz footer (in milliseconds) - GetTocLatency MeasureLatencyHook // measure time to GET TOC JSON (in milliseconds) - DeserializeTocLatency MeasureLatencyHook // measure time to deserialize TOC JSON (in milliseconds) -} - -// Open opens a stargz file for reading. -// The behavior is configurable using options. -// -// Note that each entry name is normalized as the path that is relative to root. -func Open(sr *io.SectionReader, opt ...OpenOption) (*Reader, error) { - var opts openOpts - for _, o := range opt { - if err := o(&opts); err != nil { - return nil, err - } - } - - gzipCompressors := []Decompressor{new(GzipDecompressor), new(LegacyGzipDecompressor)} - decompressors := append(gzipCompressors, opts.decompressors...) - - // Determine the size to fetch. Try to fetch as many bytes as possible. - fetchSize := maxFooterSize(sr.Size(), decompressors...) - if maybeTocOffset := opts.tocOffset; maybeTocOffset > fetchSize { - if maybeTocOffset > sr.Size() { - return nil, fmt.Errorf("blob size %d is smaller than the toc offset", sr.Size()) - } - fetchSize = sr.Size() - maybeTocOffset - } - - start := time.Now() // before getting layer footer - footer := make([]byte, fetchSize) - if _, err := sr.ReadAt(footer, sr.Size()-fetchSize); err != nil { - return nil, fmt.Errorf("error reading footer: %v", err) - } - if opts.telemetry != nil && opts.telemetry.GetFooterLatency != nil { - opts.telemetry.GetFooterLatency(start) - } - - var allErr []error - var found bool - var r *Reader - for _, d := range decompressors { - fSize := d.FooterSize() - fOffset := positive(int64(len(footer)) - fSize) - maybeTocBytes := footer[:fOffset] - _, tocOffset, tocSize, err := d.ParseFooter(footer[fOffset:]) - if err != nil { - allErr = append(allErr, err) - continue - } - if tocOffset >= 0 && tocSize <= 0 { - tocSize = sr.Size() - tocOffset - fSize - } - if tocOffset >= 0 && tocSize < int64(len(maybeTocBytes)) { - maybeTocBytes = maybeTocBytes[:tocSize] - } - r, err = parseTOC(d, sr, tocOffset, tocSize, maybeTocBytes, opts) - if err == nil { - found = true - break - } - allErr = append(allErr, err) - } - if !found { - return nil, errorutil.Aggregate(allErr) - } - if err := r.initFields(); err != nil { - return nil, fmt.Errorf("failed to initialize fields of entries: %v", err) - } - return r, nil -} - -// OpenFooter extracts and parses footer from the given blob. -// only supports gzip-based eStargz. -func OpenFooter(sr *io.SectionReader) (tocOffset int64, footerSize int64, rErr error) { - if sr.Size() < FooterSize && sr.Size() < legacyFooterSize { - return 0, 0, fmt.Errorf("blob size %d is smaller than the footer size", sr.Size()) - } - var footer [FooterSize]byte - if _, err := sr.ReadAt(footer[:], sr.Size()-FooterSize); err != nil { - return 0, 0, fmt.Errorf("error reading footer: %v", err) - } - var allErr []error - for _, d := range []Decompressor{new(GzipDecompressor), new(LegacyGzipDecompressor)} { - fSize := d.FooterSize() - fOffset := positive(int64(len(footer)) - fSize) - _, tocOffset, _, err := d.ParseFooter(footer[fOffset:]) - if err == nil { - return tocOffset, fSize, err - } - allErr = append(allErr, err) - } - return 0, 0, errorutil.Aggregate(allErr) -} - -// initFields populates the Reader from r.toc after decoding it from -// JSON. -// -// Unexported fields are populated and TOCEntry fields that were -// implicit in the JSON are populated. -func (r *Reader) initFields() error { - r.m = make(map[string]*TOCEntry, len(r.toc.Entries)) - r.chunks = make(map[string][]*TOCEntry) - var lastPath string - uname := map[int]string{} - gname := map[int]string{} - var lastRegEnt *TOCEntry - var chunkTopIndex int - for i, ent := range r.toc.Entries { - ent.Name = cleanEntryName(ent.Name) - switch ent.Type { - case "reg", "chunk": - if ent.Offset != r.toc.Entries[chunkTopIndex].Offset { - chunkTopIndex = i - } - ent.chunkTopIndex = chunkTopIndex - } - if ent.Type == "reg" { - lastRegEnt = ent - } - if ent.Type == "chunk" { - ent.Name = lastPath - r.chunks[ent.Name] = append(r.chunks[ent.Name], ent) - if ent.ChunkSize == 0 && lastRegEnt != nil { - ent.ChunkSize = lastRegEnt.Size - ent.ChunkOffset - } - } else { - lastPath = ent.Name - - if ent.Uname != "" { - uname[ent.UID] = ent.Uname - } else { - ent.Uname = uname[ent.UID] - } - if ent.Gname != "" { - gname[ent.GID] = ent.Gname - } else { - ent.Gname = uname[ent.GID] - } - - ent.modTime, _ = time.Parse(time.RFC3339, ent.ModTime3339) - - if ent.Type == "dir" { - ent.NumLink++ // Parent dir links to this directory - } - r.m[ent.Name] = ent - } - if ent.Type == "reg" && ent.ChunkSize > 0 && ent.ChunkSize < ent.Size { - r.chunks[ent.Name] = make([]*TOCEntry, 0, ent.Size/ent.ChunkSize+1) - r.chunks[ent.Name] = append(r.chunks[ent.Name], ent) - } - if ent.ChunkSize == 0 && ent.Size != 0 { - ent.ChunkSize = ent.Size - } - } - - // Populate children, add implicit directories: - for _, ent := range r.toc.Entries { - if ent.Type == "chunk" { - continue - } - // add "foo/": - // add "foo" child to "" (creating "" if necessary) - // - // add "foo/bar/": - // add "bar" child to "foo" (creating "foo" if necessary) - // - // add "foo/bar.txt": - // add "bar.txt" child to "foo" (creating "foo" if necessary) - // - // add "a/b/c/d/e/f.txt": - // create "a/b/c/d/e" node - // add "f.txt" child to "e" - - name := ent.Name - pdirName := parentDir(name) - if name == pdirName { - // This entry and its parent are the same. - // Ignore this for avoiding infinite loop of the reference. - // The example case where this can occur is when tar contains the root - // directory itself (e.g. "./", "/"). - continue - } - pdir := r.getOrCreateDir(pdirName) - ent.NumLink++ // at least one name(ent.Name) references this entry. - if ent.Type == "hardlink" { - org, err := r.getSource(ent) - if err != nil { - return err - } - org.NumLink++ // original entry is referenced by this ent.Name. - ent = org - } - pdir.addChild(path.Base(name), ent) - } - - lastOffset := r.sr.Size() - for i := len(r.toc.Entries) - 1; i >= 0; i-- { - e := r.toc.Entries[i] - if e.isDataType() { - e.nextOffset = lastOffset - } - if e.Offset != 0 && e.InnerOffset == 0 { - lastOffset = e.Offset - } - } - - return nil -} - -func (r *Reader) getSource(ent *TOCEntry) (_ *TOCEntry, err error) { - if ent.Type == "hardlink" { - org, ok := r.m[cleanEntryName(ent.LinkName)] - if !ok { - return nil, fmt.Errorf("%q is a hardlink but the linkname %q isn't found", ent.Name, ent.LinkName) - } - ent, err = r.getSource(org) - if err != nil { - return nil, err - } - } - return ent, nil -} - -func parentDir(p string) string { - dir, _ := path.Split(p) - return strings.TrimSuffix(dir, "/") -} - -func (r *Reader) getOrCreateDir(d string) *TOCEntry { - e, ok := r.m[d] - if !ok { - e = &TOCEntry{ - Name: d, - Type: "dir", - Mode: 0755, - NumLink: 2, // The directory itself(.) and the parent link to this directory. - } - r.m[d] = e - if d != "" { - pdir := r.getOrCreateDir(parentDir(d)) - pdir.addChild(path.Base(d), e) - } - } - return e -} - -func (r *Reader) TOCDigest() digest.Digest { - return r.tocDigest -} - -// VerifyTOC checks that the TOC JSON in the passed blob matches the -// passed digests and that the TOC JSON contains digests for all chunks -// contained in the blob. If the verification succceeds, this function -// returns TOCEntryVerifier which holds all chunk digests in the stargz blob. -func (r *Reader) VerifyTOC(tocDigest digest.Digest) (TOCEntryVerifier, error) { - // Verify the digest of TOC JSON - if r.tocDigest != tocDigest { - return nil, fmt.Errorf("invalid TOC JSON %q; want %q", r.tocDigest, tocDigest) - } - return r.Verifiers() -} - -// Verifiers returns TOCEntryVerifier of this chunk. Use VerifyTOC instead in most cases -// because this doesn't verify TOC. -func (r *Reader) Verifiers() (TOCEntryVerifier, error) { - chunkDigestMap := make(map[int64]digest.Digest) // map from chunk offset to the chunk digest - regDigestMap := make(map[int64]digest.Digest) // map from chunk offset to the reg file digest - var chunkDigestMapIncomplete bool - var regDigestMapIncomplete bool - var containsChunk bool - for _, e := range r.toc.Entries { - if e.Type != "reg" && e.Type != "chunk" { - continue - } - - // offset must be unique in stargz blob - _, dOK := chunkDigestMap[e.Offset] - _, rOK := regDigestMap[e.Offset] - if dOK || rOK { - return nil, fmt.Errorf("offset %d found twice", e.Offset) - } - - if e.Type == "reg" { - if e.Size == 0 { - continue // ignores empty file - } - - // record the digest of regular file payload - if e.Digest != "" { - d, err := digest.Parse(e.Digest) - if err != nil { - return nil, fmt.Errorf("failed to parse regular file digest %q: %w", e.Digest, err) - } - regDigestMap[e.Offset] = d - } else { - regDigestMapIncomplete = true - } - } else { - containsChunk = true // this layer contains "chunk" entries. - } - - // "reg" also can contain ChunkDigest (e.g. when "reg" is the first entry of - // chunked file) - if e.ChunkDigest != "" { - d, err := digest.Parse(e.ChunkDigest) - if err != nil { - return nil, fmt.Errorf("failed to parse chunk digest %q: %w", e.ChunkDigest, err) - } - chunkDigestMap[e.Offset] = d - } else { - chunkDigestMapIncomplete = true - } - } - - if chunkDigestMapIncomplete { - // Though some chunk digests are not found, if this layer doesn't contain - // "chunk"s and all digest of "reg" files are recorded, we can use them instead. - if !containsChunk && !regDigestMapIncomplete { - return &verifier{digestMap: regDigestMap}, nil - } - return nil, fmt.Errorf("some ChunkDigest not found in TOC JSON") - } - - return &verifier{digestMap: chunkDigestMap}, nil -} - -// verifier is an implementation of TOCEntryVerifier which holds verifiers keyed by -// offset of the chunk. -type verifier struct { - digestMap map[int64]digest.Digest - digestMapMu sync.Mutex -} - -// Verifier returns a content verifier specified by TOCEntry. -func (v *verifier) Verifier(ce *TOCEntry) (digest.Verifier, error) { - v.digestMapMu.Lock() - defer v.digestMapMu.Unlock() - d, ok := v.digestMap[ce.Offset] - if !ok { - return nil, fmt.Errorf("verifier for offset=%d,size=%d hasn't been registered", - ce.Offset, ce.ChunkSize) - } - return d.Verifier(), nil -} - -// ChunkEntryForOffset returns the TOCEntry containing the byte of the -// named file at the given offset within the file. -// Name must be absolute path or one that is relative to root. -func (r *Reader) ChunkEntryForOffset(name string, offset int64) (e *TOCEntry, ok bool) { - name = cleanEntryName(name) - e, ok = r.Lookup(name) - if !ok || !e.isDataType() { - return nil, false - } - ents := r.chunks[name] - if len(ents) < 2 { - if offset >= e.ChunkSize { - return nil, false - } - return e, true - } - i := sort.Search(len(ents), func(i int) bool { - e := ents[i] - return e.ChunkOffset >= offset || (offset > e.ChunkOffset && offset < e.ChunkOffset+e.ChunkSize) - }) - if i == len(ents) { - return nil, false - } - return ents[i], true -} - -// Lookup returns the Table of Contents entry for the given path. -// -// To get the root directory, use the empty string. -// Path must be absolute path or one that is relative to root. -func (r *Reader) Lookup(path string) (e *TOCEntry, ok bool) { - path = cleanEntryName(path) - if r == nil { - return - } - e, ok = r.m[path] - if ok && e.Type == "hardlink" { - var err error - e, err = r.getSource(e) - if err != nil { - return nil, false - } - } - return -} - -// OpenFile returns the reader of the specified file payload. -// -// Name must be absolute path or one that is relative to root. -func (r *Reader) OpenFile(name string) (*io.SectionReader, error) { - fr, err := r.newFileReader(name) - if err != nil { - return nil, err - } - return io.NewSectionReader(fr, 0, fr.size), nil -} - -func (r *Reader) newFileReader(name string) (*fileReader, error) { - name = cleanEntryName(name) - ent, ok := r.Lookup(name) - if !ok { - // TODO: come up with some error plan. This is lazy: - return nil, &os.PathError{ - Path: name, - Op: "OpenFile", - Err: os.ErrNotExist, - } - } - if ent.Type != "reg" { - return nil, &os.PathError{ - Path: name, - Op: "OpenFile", - Err: errors.New("not a regular file"), - } - } - return &fileReader{ - r: r, - size: ent.Size, - ents: r.getChunks(ent), - }, nil -} - -func (r *Reader) OpenFileWithPreReader(name string, preRead func(*TOCEntry, io.Reader) error) (*io.SectionReader, error) { - fr, err := r.newFileReader(name) - if err != nil { - return nil, err - } - fr.preRead = preRead - return io.NewSectionReader(fr, 0, fr.size), nil -} - -func (r *Reader) getChunks(ent *TOCEntry) []*TOCEntry { - if ents, ok := r.chunks[ent.Name]; ok { - return ents - } - return []*TOCEntry{ent} -} - -type fileReader struct { - r *Reader - size int64 - ents []*TOCEntry // 1 or more reg/chunk entries - preRead func(*TOCEntry, io.Reader) error -} - -func (fr *fileReader) ReadAt(p []byte, off int64) (n int, err error) { - if off >= fr.size { - return 0, io.EOF - } - if off < 0 { - return 0, errors.New("invalid offset") - } - var i int - if len(fr.ents) > 1 { - i = sort.Search(len(fr.ents), func(i int) bool { - return fr.ents[i].ChunkOffset >= off - }) - if i == len(fr.ents) { - i = len(fr.ents) - 1 - } - } - ent := fr.ents[i] - if ent.ChunkOffset > off { - if i == 0 { - return 0, errors.New("internal error; first chunk offset is non-zero") - } - ent = fr.ents[i-1] - } - - // If ent is a chunk of a large file, adjust the ReadAt - // offset by the chunk's offset. - off -= ent.ChunkOffset - - finalEnt := fr.ents[len(fr.ents)-1] - compressedOff := ent.Offset - // compressedBytesRemain is the number of compressed bytes in this - // file remaining, over 1+ chunks. - compressedBytesRemain := finalEnt.NextOffset() - compressedOff - - sr := io.NewSectionReader(fr.r.sr, compressedOff, compressedBytesRemain) - - const maxRead = 2 << 20 - var bufSize = maxRead - if compressedBytesRemain < maxRead { - bufSize = int(compressedBytesRemain) - } - - br := bufio.NewReaderSize(sr, bufSize) - if _, err := br.Peek(bufSize); err != nil { - return 0, fmt.Errorf("fileReader.ReadAt.peek: %v", err) - } - - dr, err := fr.r.decompressor.Reader(br) - if err != nil { - return 0, fmt.Errorf("fileReader.ReadAt.decompressor.Reader: %v", err) - } - defer dr.Close() - - if fr.preRead == nil { - if n, err := io.CopyN(io.Discard, dr, ent.InnerOffset+off); n != ent.InnerOffset+off || err != nil { - return 0, fmt.Errorf("discard of %d bytes != %v, %v", ent.InnerOffset+off, n, err) - } - return io.ReadFull(dr, p) - } - - var retN int - var retErr error - var found bool - var nr int64 - for _, e := range fr.r.toc.Entries[ent.chunkTopIndex:] { - if !e.isDataType() { - continue - } - if e.Offset != fr.r.toc.Entries[ent.chunkTopIndex].Offset { - break - } - if in, err := io.CopyN(io.Discard, dr, e.InnerOffset-nr); err != nil || in != e.InnerOffset-nr { - return 0, fmt.Errorf("discard of remaining %d bytes != %v, %v", e.InnerOffset-nr, in, err) - } - nr = e.InnerOffset - if e == ent { - found = true - if n, err := io.CopyN(io.Discard, dr, off); n != off || err != nil { - return 0, fmt.Errorf("discard of offset %d bytes != %v, %v", off, n, err) - } - retN, retErr = io.ReadFull(dr, p) - nr += off + int64(retN) - continue - } - cr := &countReader{r: io.LimitReader(dr, e.ChunkSize)} - if err := fr.preRead(e, cr); err != nil { - return 0, fmt.Errorf("failed to pre read: %w", err) - } - nr += cr.n - } - if !found { - return 0, fmt.Errorf("fileReader.ReadAt: target entry not found") - } - return retN, retErr -} - -// A Writer writes stargz files. -// -// Use NewWriter to create a new Writer. -type Writer struct { - bw *bufio.Writer - cw *countWriter - toc *JTOC - diffHash hash.Hash // SHA-256 of uncompressed tar - - closed bool - gz io.WriteCloser - lastUsername map[int]string - lastGroupname map[int]string - compressor Compressor - - uncompressedCounter *countWriteFlusher - - // ChunkSize optionally controls the maximum number of bytes - // of data of a regular file that can be written in one gzip - // stream before a new gzip stream is started. - // Zero means to use a default, currently 4 MiB. - ChunkSize int - - // MinChunkSize optionally controls the minimum number of bytes - // of data must be written in one gzip stream before a new gzip - // NOTE: This adds a TOC property that stargz snapshotter < v0.13.0 doesn't understand. - MinChunkSize int - - needsOpenGzEntries map[string]struct{} -} - -// currentCompressionWriter writes to the current w.gz field, which can -// change throughout writing a tar entry. -// -// Additionally, it updates w's SHA-256 of the uncompressed bytes -// of the tar file. -type currentCompressionWriter struct{ w *Writer } - -func (ccw currentCompressionWriter) Write(p []byte) (int, error) { - ccw.w.diffHash.Write(p) - if ccw.w.gz == nil { - if err := ccw.w.condOpenGz(); err != nil { - return 0, err - } - } - return ccw.w.gz.Write(p) -} - -func (w *Writer) chunkSize() int { - if w.ChunkSize <= 0 { - return 4 << 20 - } - return w.ChunkSize -} - -// Unpack decompresses the given estargz blob and returns a ReadCloser of the tar blob. -// TOC JSON and footer are removed. -func Unpack(sr *io.SectionReader, c Decompressor) (io.ReadCloser, error) { - footerSize := c.FooterSize() - if sr.Size() < footerSize { - return nil, fmt.Errorf("blob is too small; %d < %d", sr.Size(), footerSize) - } - footerOffset := sr.Size() - footerSize - footer := make([]byte, footerSize) - if _, err := sr.ReadAt(footer, footerOffset); err != nil { - return nil, err - } - blobPayloadSize, _, _, err := c.ParseFooter(footer) - if err != nil { - return nil, fmt.Errorf("failed to parse footer: %w", err) - } - if blobPayloadSize < 0 { - blobPayloadSize = sr.Size() - } - return c.Reader(io.LimitReader(sr, blobPayloadSize)) -} - -// NewWriter returns a new stargz writer (gzip-based) writing to w. -// -// The writer must be closed to write its trailing table of contents. -func NewWriter(w io.Writer) *Writer { - return NewWriterLevel(w, gzip.BestCompression) -} - -// NewWriterLevel returns a new stargz writer (gzip-based) writing to w. -// The compression level is configurable. -// -// The writer must be closed to write its trailing table of contents. -func NewWriterLevel(w io.Writer, compressionLevel int) *Writer { - return NewWriterWithCompressor(w, NewGzipCompressorWithLevel(compressionLevel)) -} - -// NewWriterWithCompressor returns a new stargz writer writing to w. -// The compression method is configurable. -// -// The writer must be closed to write its trailing table of contents. -func NewWriterWithCompressor(w io.Writer, c Compressor) *Writer { - bw := bufio.NewWriter(w) - cw := &countWriter{w: bw} - return &Writer{ - bw: bw, - cw: cw, - toc: &JTOC{Version: 1}, - diffHash: sha256.New(), - compressor: c, - uncompressedCounter: &countWriteFlusher{}, - } -} - -// Close writes the stargz's table of contents and flushes all the -// buffers, returning any error. -func (w *Writer) Close() (digest.Digest, error) { - if w.closed { - return "", nil - } - defer func() { w.closed = true }() - - if err := w.closeGz(); err != nil { - return "", err - } - - // Write the TOC index and footer. - tocDigest, err := w.compressor.WriteTOCAndFooter(w.cw, w.cw.n, w.toc, w.diffHash) - if err != nil { - return "", err - } - if err := w.bw.Flush(); err != nil { - return "", err - } - - return tocDigest, nil -} - -func (w *Writer) closeGz() error { - if w.closed { - return errors.New("write on closed Writer") - } - if w.gz != nil { - if err := w.gz.Close(); err != nil { - return err - } - w.gz = nil - } - return nil -} - -func (w *Writer) flushGz() error { - if w.closed { - return errors.New("flush on closed Writer") - } - if w.gz != nil { - if f, ok := w.gz.(interface { - Flush() error - }); ok { - return f.Flush() - } - } - return nil -} - -// nameIfChanged returns name, unless it was the already the value of (*mp)[id], -// in which case it returns the empty string. -func (w *Writer) nameIfChanged(mp *map[int]string, id int, name string) string { - if name == "" { - return "" - } - if *mp == nil { - *mp = make(map[int]string) - } - if (*mp)[id] == name { - return "" - } - (*mp)[id] = name - return name -} - -func (w *Writer) condOpenGz() (err error) { - if w.gz == nil { - w.gz, err = w.compressor.Writer(w.cw) - if w.gz != nil { - w.gz = w.uncompressedCounter.register(w.gz) - } - } - return -} - -// AppendTar reads the tar or tar.gz file from r and appends -// each of its contents to w. -// -// The input r can optionally be gzip compressed but the output will -// always be compressed by the specified compressor. -func (w *Writer) AppendTar(r io.Reader) error { - return w.appendTar(r, false) -} - -// AppendTarLossLess reads the tar or tar.gz file from r and appends -// each of its contents to w. -// -// The input r can optionally be gzip compressed but the output will -// always be compressed by the specified compressor. -// -// The difference of this func with AppendTar is that this writes -// the input tar stream into w without any modification (e.g. to header bytes). -// -// Note that if the input tar stream already contains TOC JSON, this returns -// error because w cannot overwrite the TOC JSON to the one generated by w without -// lossy modification. To avoid this error, if the input stream is known to be stargz/estargz, -// you shoud decompress it and remove TOC JSON in advance. -func (w *Writer) AppendTarLossLess(r io.Reader) error { - return w.appendTar(r, true) -} - -func (w *Writer) appendTar(r io.Reader, lossless bool) error { - var src io.Reader - br := bufio.NewReader(r) - if isGzip(br) { - zr, _ := gzip.NewReader(br) - src = zr - } else { - src = io.Reader(br) - } - dst := currentCompressionWriter{w} - var tw *tar.Writer - if !lossless { - tw = tar.NewWriter(dst) // use tar writer only when this isn't lossless mode. - } - tr := tar.NewReader(src) - if lossless { - tr.RawAccounting = true - } - prevOffset := w.cw.n - var prevOffsetUncompressed int64 - for { - h, err := tr.Next() - if err == io.EOF { - if lossless { - if remain := tr.RawBytes(); len(remain) > 0 { - // Collect the remaining null bytes. - // https://github.com/vbatts/tar-split/blob/80a436fd6164c557b131f7c59ed69bd81af69761/concept/main.go#L49-L53 - if _, err := dst.Write(remain); err != nil { - return err - } - } - } - break - } - if err != nil { - return fmt.Errorf("error reading from source tar: tar.Reader.Next: %v", err) - } - if cleanEntryName(h.Name) == TOCTarName { - // It is possible for a layer to be "stargzified" twice during the - // distribution lifecycle. So we reserve "TOCTarName" here to avoid - // duplicated entries in the resulting layer. - if lossless { - // We cannot handle this in lossless way. - return fmt.Errorf("existing TOC JSON is not allowed; decompress layer before append") - } - continue - } - - xattrs := make(map[string][]byte) - const xattrPAXRecordsPrefix = "SCHILY.xattr." - if h.PAXRecords != nil { - for k, v := range h.PAXRecords { - if strings.HasPrefix(k, xattrPAXRecordsPrefix) { - xattrs[k[len(xattrPAXRecordsPrefix):]] = []byte(v) - } - } - } - ent := &TOCEntry{ - Name: h.Name, - Mode: h.Mode, - UID: h.Uid, - GID: h.Gid, - Uname: w.nameIfChanged(&w.lastUsername, h.Uid, h.Uname), - Gname: w.nameIfChanged(&w.lastGroupname, h.Gid, h.Gname), - ModTime3339: formatModtime(h.ModTime), - Xattrs: xattrs, - } - if err := w.condOpenGz(); err != nil { - return err - } - if tw != nil { - if err := tw.WriteHeader(h); err != nil { - return err - } - } else { - if _, err := dst.Write(tr.RawBytes()); err != nil { - return err - } - } - switch h.Typeflag { - case tar.TypeLink: - ent.Type = "hardlink" - ent.LinkName = h.Linkname - case tar.TypeSymlink: - ent.Type = "symlink" - ent.LinkName = h.Linkname - case tar.TypeDir: - ent.Type = "dir" - case tar.TypeReg: - ent.Type = "reg" - ent.Size = h.Size - case tar.TypeChar: - ent.Type = "char" - ent.DevMajor = int(h.Devmajor) - ent.DevMinor = int(h.Devminor) - case tar.TypeBlock: - ent.Type = "block" - ent.DevMajor = int(h.Devmajor) - ent.DevMinor = int(h.Devminor) - case tar.TypeFifo: - ent.Type = "fifo" - default: - return fmt.Errorf("unsupported input tar entry %q", h.Typeflag) - } - - // We need to keep a reference to the TOC entry for regular files, so that we - // can fill the digest later. - var regFileEntry *TOCEntry - var payloadDigest digest.Digester - if h.Typeflag == tar.TypeReg { - regFileEntry = ent - payloadDigest = digest.Canonical.Digester() - } - - if h.Typeflag == tar.TypeReg && ent.Size > 0 { - var written int64 - totalSize := ent.Size // save it before we destroy ent - tee := io.TeeReader(tr, payloadDigest.Hash()) - for written < totalSize { - chunkSize := int64(w.chunkSize()) - remain := totalSize - written - if remain < chunkSize { - chunkSize = remain - } else { - ent.ChunkSize = chunkSize - } - - // We flush the underlying compression writer here to correctly calculate "w.cw.n". - if err := w.flushGz(); err != nil { - return err - } - if w.needsOpenGz(ent) || w.cw.n-prevOffset >= int64(w.MinChunkSize) { - if err := w.closeGz(); err != nil { - return err - } - ent.Offset = w.cw.n - prevOffset = ent.Offset - prevOffsetUncompressed = w.uncompressedCounter.n - } else { - ent.Offset = prevOffset - ent.InnerOffset = w.uncompressedCounter.n - prevOffsetUncompressed - } - - ent.ChunkOffset = written - chunkDigest := digest.Canonical.Digester() - - if err := w.condOpenGz(); err != nil { - return err - } - - teeChunk := io.TeeReader(tee, chunkDigest.Hash()) - var out io.Writer - if tw != nil { - out = tw - } else { - out = dst - } - if _, err := io.CopyN(out, teeChunk, chunkSize); err != nil { - return fmt.Errorf("error copying %q: %v", h.Name, err) - } - ent.ChunkDigest = chunkDigest.Digest().String() - w.toc.Entries = append(w.toc.Entries, ent) - written += chunkSize - ent = &TOCEntry{ - Name: h.Name, - Type: "chunk", - } - } - } else { - w.toc.Entries = append(w.toc.Entries, ent) - } - if payloadDigest != nil { - regFileEntry.Digest = payloadDigest.Digest().String() - } - if tw != nil { - if err := tw.Flush(); err != nil { - return err - } - } - } - remainDest := io.Discard - if lossless { - remainDest = dst // Preserve the remaining bytes in lossless mode - } - _, err := io.Copy(remainDest, src) - return err -} - -func (w *Writer) needsOpenGz(ent *TOCEntry) bool { - if ent.Type != "reg" { - return false - } - if w.needsOpenGzEntries == nil { - return false - } - _, ok := w.needsOpenGzEntries[ent.Name] - return ok -} - -// DiffID returns the SHA-256 of the uncompressed tar bytes. -// It is only valid to call DiffID after Close. -func (w *Writer) DiffID() string { - return fmt.Sprintf("sha256:%x", w.diffHash.Sum(nil)) -} - -func maxFooterSize(blobSize int64, decompressors ...Decompressor) (res int64) { - for _, d := range decompressors { - if s := d.FooterSize(); res < s && s <= blobSize { - res = s - } - } - return -} - -func parseTOC(d Decompressor, sr *io.SectionReader, tocOff, tocSize int64, tocBytes []byte, opts openOpts) (*Reader, error) { - if tocOff < 0 { - // This means that TOC isn't contained in the blob. - // We pass nil reader to ParseTOC and expect that ParseTOC acquire TOC from - // the external location. - start := time.Now() - toc, tocDgst, err := d.ParseTOC(nil) - if err != nil { - return nil, err - } - if opts.telemetry != nil && opts.telemetry.GetTocLatency != nil { - opts.telemetry.GetTocLatency(start) - } - if opts.telemetry != nil && opts.telemetry.DeserializeTocLatency != nil { - opts.telemetry.DeserializeTocLatency(start) - } - return &Reader{ - sr: sr, - toc: toc, - tocDigest: tocDgst, - decompressor: d, - }, nil - } - if len(tocBytes) > 0 { - start := time.Now() - toc, tocDgst, err := d.ParseTOC(bytes.NewReader(tocBytes)) - if err == nil { - if opts.telemetry != nil && opts.telemetry.DeserializeTocLatency != nil { - opts.telemetry.DeserializeTocLatency(start) - } - return &Reader{ - sr: sr, - toc: toc, - tocDigest: tocDgst, - decompressor: d, - }, nil - } - } - - start := time.Now() - tocBytes = make([]byte, tocSize) - if _, err := sr.ReadAt(tocBytes, tocOff); err != nil { - return nil, fmt.Errorf("error reading %d byte TOC targz: %v", len(tocBytes), err) - } - if opts.telemetry != nil && opts.telemetry.GetTocLatency != nil { - opts.telemetry.GetTocLatency(start) - } - start = time.Now() - toc, tocDgst, err := d.ParseTOC(bytes.NewReader(tocBytes)) - if err != nil { - return nil, err - } - if opts.telemetry != nil && opts.telemetry.DeserializeTocLatency != nil { - opts.telemetry.DeserializeTocLatency(start) - } - return &Reader{ - sr: sr, - toc: toc, - tocDigest: tocDgst, - decompressor: d, - }, nil -} - -func formatModtime(t time.Time) string { - if t.IsZero() || t.Unix() == 0 { - return "" - } - return t.UTC().Round(time.Second).Format(time.RFC3339) -} - -func cleanEntryName(name string) string { - // Use path.Clean to consistently deal with path separators across platforms. - return strings.TrimPrefix(path.Clean("/"+name), "/") -} - -// countWriter counts how many bytes have been written to its wrapped -// io.Writer. -type countWriter struct { - w io.Writer - n int64 -} - -func (cw *countWriter) Write(p []byte) (n int, err error) { - n, err = cw.w.Write(p) - cw.n += int64(n) - return -} - -type countWriteFlusher struct { - io.WriteCloser - n int64 -} - -func (wc *countWriteFlusher) register(w io.WriteCloser) io.WriteCloser { - wc.WriteCloser = w - return wc -} - -func (wc *countWriteFlusher) Write(p []byte) (n int, err error) { - n, err = wc.WriteCloser.Write(p) - wc.n += int64(n) - return -} - -func (wc *countWriteFlusher) Flush() error { - if f, ok := wc.WriteCloser.(interface { - Flush() error - }); ok { - return f.Flush() - } - return nil -} - -func (wc *countWriteFlusher) Close() error { - err := wc.WriteCloser.Close() - wc.WriteCloser = nil - return err -} - -// isGzip reports whether br is positioned right before an upcoming gzip stream. -// It does not consume any bytes from br. -func isGzip(br *bufio.Reader) bool { - const ( - gzipID1 = 0x1f - gzipID2 = 0x8b - gzipDeflate = 8 - ) - peek, _ := br.Peek(3) - return len(peek) >= 3 && peek[0] == gzipID1 && peek[1] == gzipID2 && peek[2] == gzipDeflate -} - -func positive(n int64) int64 { - if n < 0 { - return 0 - } - return n -} - -type countReader struct { - r io.Reader - n int64 -} - -func (cr *countReader) Read(p []byte) (n int, err error) { - n, err = cr.r.Read(p) - cr.n += int64(n) - return -} diff --git a/vendor/github.com/containerd/stargz-snapshotter/estargz/gzip.go b/vendor/github.com/containerd/stargz-snapshotter/estargz/gzip.go deleted file mode 100644 index f24afe32f..000000000 --- a/vendor/github.com/containerd/stargz-snapshotter/estargz/gzip.go +++ /dev/null @@ -1,237 +0,0 @@ -/* - Copyright The containerd 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. -*/ - -/* - Copyright 2019 The Go Authors. All rights reserved. - Use of this source code is governed by a BSD-style - license that can be found in the LICENSE file. -*/ - -package estargz - -import ( - "archive/tar" - "bytes" - "compress/gzip" - "encoding/binary" - "encoding/json" - "fmt" - "hash" - "io" - "strconv" - - digest "github.com/opencontainers/go-digest" -) - -type gzipCompression struct { - *GzipCompressor - *GzipDecompressor -} - -func newGzipCompressionWithLevel(level int) Compression { - return &gzipCompression{ - &GzipCompressor{level}, - &GzipDecompressor{}, - } -} - -func NewGzipCompressor() *GzipCompressor { - return &GzipCompressor{gzip.BestCompression} -} - -func NewGzipCompressorWithLevel(level int) *GzipCompressor { - return &GzipCompressor{level} -} - -type GzipCompressor struct { - compressionLevel int -} - -func (gc *GzipCompressor) Writer(w io.Writer) (WriteFlushCloser, error) { - return gzip.NewWriterLevel(w, gc.compressionLevel) -} - -func (gc *GzipCompressor) WriteTOCAndFooter(w io.Writer, off int64, toc *JTOC, diffHash hash.Hash) (digest.Digest, error) { - tocJSON, err := json.MarshalIndent(toc, "", "\t") - if err != nil { - return "", err - } - gz, _ := gzip.NewWriterLevel(w, gc.compressionLevel) - gw := io.Writer(gz) - if diffHash != nil { - gw = io.MultiWriter(gz, diffHash) - } - tw := tar.NewWriter(gw) - if err := tw.WriteHeader(&tar.Header{ - Typeflag: tar.TypeReg, - Name: TOCTarName, - Size: int64(len(tocJSON)), - }); err != nil { - return "", err - } - if _, err := tw.Write(tocJSON); err != nil { - return "", err - } - - if err := tw.Close(); err != nil { - return "", err - } - if err := gz.Close(); err != nil { - return "", err - } - if _, err := w.Write(gzipFooterBytes(off)); err != nil { - return "", err - } - return digest.FromBytes(tocJSON), nil -} - -// gzipFooterBytes returns the 51 bytes footer. -func gzipFooterBytes(tocOff int64) []byte { - buf := bytes.NewBuffer(make([]byte, 0, FooterSize)) - gz, _ := gzip.NewWriterLevel(buf, gzip.NoCompression) // MUST be NoCompression to keep 51 bytes - - // Extra header indicating the offset of TOCJSON - // https://tools.ietf.org/html/rfc1952#section-2.3.1.1 - header := make([]byte, 4) - header[0], header[1] = 'S', 'G' - subfield := fmt.Sprintf("%016xSTARGZ", tocOff) - binary.LittleEndian.PutUint16(header[2:4], uint16(len(subfield))) // little-endian per RFC1952 - gz.Header.Extra = append(header, []byte(subfield)...) - gz.Close() - if buf.Len() != FooterSize { - panic(fmt.Sprintf("footer buffer = %d, not %d", buf.Len(), FooterSize)) - } - return buf.Bytes() -} - -type GzipDecompressor struct{} - -func (gz *GzipDecompressor) Reader(r io.Reader) (io.ReadCloser, error) { - return gzip.NewReader(r) -} - -func (gz *GzipDecompressor) ParseTOC(r io.Reader) (toc *JTOC, tocDgst digest.Digest, err error) { - return parseTOCEStargz(r) -} - -func (gz *GzipDecompressor) ParseFooter(p []byte) (blobPayloadSize, tocOffset, tocSize int64, err error) { - if len(p) != FooterSize { - return 0, 0, 0, fmt.Errorf("invalid length %d cannot be parsed", len(p)) - } - zr, err := gzip.NewReader(bytes.NewReader(p)) - if err != nil { - return 0, 0, 0, err - } - defer zr.Close() - extra := zr.Header.Extra - si1, si2, subfieldlen, subfield := extra[0], extra[1], extra[2:4], extra[4:] - if si1 != 'S' || si2 != 'G' { - return 0, 0, 0, fmt.Errorf("invalid subfield IDs: %q, %q; want E, S", si1, si2) - } - if slen := binary.LittleEndian.Uint16(subfieldlen); slen != uint16(16+len("STARGZ")) { - return 0, 0, 0, fmt.Errorf("invalid length of subfield %d; want %d", slen, 16+len("STARGZ")) - } - if string(subfield[16:]) != "STARGZ" { - return 0, 0, 0, fmt.Errorf("STARGZ magic string must be included in the footer subfield") - } - tocOffset, err = strconv.ParseInt(string(subfield[:16]), 16, 64) - if err != nil { - return 0, 0, 0, fmt.Errorf("legacy: failed to parse toc offset: %w", err) - } - return tocOffset, tocOffset, 0, nil -} - -func (gz *GzipDecompressor) FooterSize() int64 { - return FooterSize -} - -func (gz *GzipDecompressor) DecompressTOC(r io.Reader) (tocJSON io.ReadCloser, err error) { - return decompressTOCEStargz(r) -} - -type LegacyGzipDecompressor struct{} - -func (gz *LegacyGzipDecompressor) Reader(r io.Reader) (io.ReadCloser, error) { - return gzip.NewReader(r) -} - -func (gz *LegacyGzipDecompressor) ParseTOC(r io.Reader) (toc *JTOC, tocDgst digest.Digest, err error) { - return parseTOCEStargz(r) -} - -func (gz *LegacyGzipDecompressor) ParseFooter(p []byte) (blobPayloadSize, tocOffset, tocSize int64, err error) { - if len(p) != legacyFooterSize { - return 0, 0, 0, fmt.Errorf("legacy: invalid length %d cannot be parsed", len(p)) - } - zr, err := gzip.NewReader(bytes.NewReader(p)) - if err != nil { - return 0, 0, 0, fmt.Errorf("legacy: failed to get footer gzip reader: %w", err) - } - defer zr.Close() - extra := zr.Header.Extra - if len(extra) != 16+len("STARGZ") { - return 0, 0, 0, fmt.Errorf("legacy: invalid stargz's extra field size") - } - if string(extra[16:]) != "STARGZ" { - return 0, 0, 0, fmt.Errorf("legacy: magic string STARGZ not found") - } - tocOffset, err = strconv.ParseInt(string(extra[:16]), 16, 64) - if err != nil { - return 0, 0, 0, fmt.Errorf("legacy: failed to parse toc offset: %w", err) - } - return tocOffset, tocOffset, 0, nil -} - -func (gz *LegacyGzipDecompressor) FooterSize() int64 { - return legacyFooterSize -} - -func (gz *LegacyGzipDecompressor) DecompressTOC(r io.Reader) (tocJSON io.ReadCloser, err error) { - return decompressTOCEStargz(r) -} - -func parseTOCEStargz(r io.Reader) (toc *JTOC, tocDgst digest.Digest, err error) { - tr, err := decompressTOCEStargz(r) - if err != nil { - return nil, "", err - } - dgstr := digest.Canonical.Digester() - toc = new(JTOC) - if err := json.NewDecoder(io.TeeReader(tr, dgstr.Hash())).Decode(&toc); err != nil { - return nil, "", fmt.Errorf("error decoding TOC JSON: %v", err) - } - if err := tr.Close(); err != nil { - return nil, "", err - } - return toc, dgstr.Digest(), nil -} - -func decompressTOCEStargz(r io.Reader) (tocJSON io.ReadCloser, err error) { - zr, err := gzip.NewReader(r) - if err != nil { - return nil, fmt.Errorf("malformed TOC gzip header: %v", err) - } - zr.Multistream(false) - tr := tar.NewReader(zr) - h, err := tr.Next() - if err != nil { - return nil, fmt.Errorf("failed to find tar header in TOC gzip stream: %v", err) - } - if h.Name != TOCTarName { - return nil, fmt.Errorf("TOC tar entry had name %q; expected %q", h.Name, TOCTarName) - } - return readCloser{tr, zr.Close}, nil -} diff --git a/vendor/github.com/containerd/stargz-snapshotter/estargz/testutil.go b/vendor/github.com/containerd/stargz-snapshotter/estargz/testutil.go deleted file mode 100644 index 0ca6fd75f..000000000 --- a/vendor/github.com/containerd/stargz-snapshotter/estargz/testutil.go +++ /dev/null @@ -1,2366 +0,0 @@ -/* - Copyright The containerd 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. -*/ - -/* - Copyright 2019 The Go Authors. All rights reserved. - Use of this source code is governed by a BSD-style - license that can be found in the LICENSE file. -*/ - -package estargz - -import ( - "archive/tar" - "bytes" - "compress/gzip" - "crypto/sha256" - "encoding/json" - "errors" - "fmt" - "io" - "math/rand" - "os" - "path/filepath" - "reflect" - "sort" - "strings" - "testing" - "time" - - "github.com/containerd/stargz-snapshotter/estargz/errorutil" - "github.com/klauspost/compress/zstd" - digest "github.com/opencontainers/go-digest" -) - -func init() { - rand.Seed(time.Now().UnixNano()) -} - -// TestingController is Compression with some helper methods necessary for testing. -type TestingController interface { - Compression - TestStreams(t *testing.T, b []byte, streams []int64) - DiffIDOf(*testing.T, []byte) string - String() string -} - -// CompressionTestSuite tests this pkg with controllers can build valid eStargz blobs and parse them. -func CompressionTestSuite(t *testing.T, controllers ...TestingControllerFactory) { - t.Run("testBuild", func(t *testing.T) { t.Parallel(); testBuild(t, controllers...) }) - t.Run("testDigestAndVerify", func(t *testing.T) { t.Parallel(); testDigestAndVerify(t, controllers...) }) - t.Run("testWriteAndOpen", func(t *testing.T) { t.Parallel(); testWriteAndOpen(t, controllers...) }) -} - -type TestingControllerFactory func() TestingController - -const ( - uncompressedType int = iota - gzipType - zstdType -) - -var srcCompressions = []int{ - uncompressedType, - gzipType, - zstdType, -} - -var allowedPrefix = [4]string{"", "./", "/", "../"} - -// testBuild tests the resulting stargz blob built by this pkg has the same -// contents as the normal stargz blob. -func testBuild(t *testing.T, controllers ...TestingControllerFactory) { - tests := []struct { - name string - chunkSize int - minChunkSize []int - in []tarEntry - }{ - { - name: "regfiles and directories", - chunkSize: 4, - in: tarOf( - file("foo", "test1"), - dir("foo2/"), - file("foo2/bar", "test2", xAttr(map[string]string{"test": "sample"})), - ), - }, - { - name: "empty files", - chunkSize: 4, - in: tarOf( - file("foo", "tttttt"), - file("foo_empty", ""), - file("foo2", "tttttt"), - file("foo_empty2", ""), - file("foo3", "tttttt"), - file("foo_empty3", ""), - file("foo4", "tttttt"), - file("foo_empty4", ""), - file("foo5", "tttttt"), - file("foo_empty5", ""), - file("foo6", "tttttt"), - ), - }, - { - name: "various files", - chunkSize: 4, - minChunkSize: []int{0, 64000}, - in: tarOf( - file("baz.txt", "bazbazbazbazbazbazbaz"), - file("foo1.txt", "a"), - file("bar/foo2.txt", "b"), - file("foo3.txt", "c"), - symlink("barlink", "test/bar.txt"), - dir("test/"), - dir("dev/"), - blockdev("dev/testblock", 3, 4), - fifo("dev/testfifo"), - chardev("dev/testchar1", 5, 6), - file("test/bar.txt", "testbartestbar", xAttr(map[string]string{"test2": "sample2"})), - dir("test2/"), - link("test2/bazlink", "baz.txt"), - chardev("dev/testchar2", 1, 2), - ), - }, - { - name: "no contents", - chunkSize: 4, - in: tarOf( - file("baz.txt", ""), - symlink("barlink", "test/bar.txt"), - dir("test/"), - dir("dev/"), - blockdev("dev/testblock", 3, 4), - fifo("dev/testfifo"), - chardev("dev/testchar1", 5, 6), - file("test/bar.txt", "", xAttr(map[string]string{"test2": "sample2"})), - dir("test2/"), - link("test2/bazlink", "baz.txt"), - chardev("dev/testchar2", 1, 2), - ), - }, - } - for _, tt := range tests { - if len(tt.minChunkSize) == 0 { - tt.minChunkSize = []int{0} - } - for _, srcCompression := range srcCompressions { - srcCompression := srcCompression - for _, newCL := range controllers { - newCL := newCL - for _, srcTarFormat := range []tar.Format{tar.FormatUSTAR, tar.FormatPAX, tar.FormatGNU} { - srcTarFormat := srcTarFormat - for _, prefix := range allowedPrefix { - prefix := prefix - for _, minChunkSize := range tt.minChunkSize { - minChunkSize := minChunkSize - t.Run(tt.name+"-"+fmt.Sprintf("compression=%v,prefix=%q,src=%d,format=%s,minChunkSize=%d", newCL(), prefix, srcCompression, srcTarFormat, minChunkSize), func(t *testing.T) { - tarBlob := buildTar(t, tt.in, prefix, srcTarFormat) - // Test divideEntries() - entries, err := sortEntries(tarBlob, nil, nil) // identical order - if err != nil { - t.Fatalf("failed to parse tar: %v", err) - } - var merged []*entry - for _, part := range divideEntries(entries, 4) { - merged = append(merged, part...) - } - if !reflect.DeepEqual(entries, merged) { - for _, e := range entries { - t.Logf("Original: %v", e.header) - } - for _, e := range merged { - t.Logf("Merged: %v", e.header) - } - t.Errorf("divided entries couldn't be merged") - return - } - - // Prepare sample data - cl1 := newCL() - wantBuf := new(bytes.Buffer) - sw := NewWriterWithCompressor(wantBuf, cl1) - sw.MinChunkSize = minChunkSize - sw.ChunkSize = tt.chunkSize - if err := sw.AppendTar(tarBlob); err != nil { - t.Fatalf("failed to append tar to want stargz: %v", err) - } - if _, err := sw.Close(); err != nil { - t.Fatalf("failed to prepare want stargz: %v", err) - } - wantData := wantBuf.Bytes() - want, err := Open(io.NewSectionReader( - bytes.NewReader(wantData), 0, int64(len(wantData))), - WithDecompressors(cl1), - ) - if err != nil { - t.Fatalf("failed to parse the want stargz: %v", err) - } - - // Prepare testing data - var opts []Option - if minChunkSize > 0 { - opts = append(opts, WithMinChunkSize(minChunkSize)) - } - cl2 := newCL() - rc, err := Build(compressBlob(t, tarBlob, srcCompression), - append(opts, WithChunkSize(tt.chunkSize), WithCompression(cl2))...) - if err != nil { - t.Fatalf("failed to build stargz: %v", err) - } - defer rc.Close() - gotBuf := new(bytes.Buffer) - if _, err := io.Copy(gotBuf, rc); err != nil { - t.Fatalf("failed to copy built stargz blob: %v", err) - } - gotData := gotBuf.Bytes() - got, err := Open(io.NewSectionReader( - bytes.NewReader(gotBuf.Bytes()), 0, int64(len(gotData))), - WithDecompressors(cl2), - ) - if err != nil { - t.Fatalf("failed to parse the got stargz: %v", err) - } - - // Check DiffID is properly calculated - rc.Close() - diffID := rc.DiffID() - wantDiffID := cl2.DiffIDOf(t, gotData) - if diffID.String() != wantDiffID { - t.Errorf("DiffID = %q; want %q", diffID, wantDiffID) - } - - // Compare as stargz - if !isSameVersion(t, cl1, wantData, cl2, gotData) { - t.Errorf("built stargz hasn't same json") - return - } - if !isSameEntries(t, want, got) { - t.Errorf("built stargz isn't same as the original") - return - } - - // Compare as tar.gz - if !isSameTarGz(t, cl1, wantData, cl2, gotData) { - t.Errorf("built stargz isn't same tar.gz") - return - } - }) - } - } - } - } - } - } -} - -func isSameTarGz(t *testing.T, cla TestingController, a []byte, clb TestingController, b []byte) bool { - aGz, err := cla.Reader(bytes.NewReader(a)) - if err != nil { - t.Fatalf("failed to read A") - } - defer aGz.Close() - bGz, err := clb.Reader(bytes.NewReader(b)) - if err != nil { - t.Fatalf("failed to read B") - } - defer bGz.Close() - - // Same as tar's Next() method but ignores landmarks and TOCJSON file - next := func(r *tar.Reader) (h *tar.Header, err error) { - for { - if h, err = r.Next(); err != nil { - return - } - if h.Name != PrefetchLandmark && - h.Name != NoPrefetchLandmark && - h.Name != TOCTarName { - return - } - } - } - - aTar := tar.NewReader(aGz) - bTar := tar.NewReader(bGz) - for { - // Fetch and parse next header. - aH, aErr := next(aTar) - bH, bErr := next(bTar) - if aErr != nil || bErr != nil { - if aErr == io.EOF && bErr == io.EOF { - break - } - t.Fatalf("Failed to parse tar file: A: %v, B: %v", aErr, bErr) - } - if !reflect.DeepEqual(aH, bH) { - t.Logf("different header (A = %v; B = %v)", aH, bH) - return false - - } - aFile, err := io.ReadAll(aTar) - if err != nil { - t.Fatal("failed to read tar payload of A") - } - bFile, err := io.ReadAll(bTar) - if err != nil { - t.Fatal("failed to read tar payload of B") - } - if !bytes.Equal(aFile, bFile) { - t.Logf("different tar payload (A = %q; B = %q)", string(a), string(b)) - return false - } - } - - return true -} - -func isSameVersion(t *testing.T, cla TestingController, a []byte, clb TestingController, b []byte) bool { - aJTOC, _, err := parseStargz(io.NewSectionReader(bytes.NewReader(a), 0, int64(len(a))), cla) - if err != nil { - t.Fatalf("failed to parse A: %v", err) - } - bJTOC, _, err := parseStargz(io.NewSectionReader(bytes.NewReader(b), 0, int64(len(b))), clb) - if err != nil { - t.Fatalf("failed to parse B: %v", err) - } - t.Logf("A: TOCJSON: %v", dumpTOCJSON(t, aJTOC)) - t.Logf("B: TOCJSON: %v", dumpTOCJSON(t, bJTOC)) - return aJTOC.Version == bJTOC.Version -} - -func isSameEntries(t *testing.T, a, b *Reader) bool { - aroot, ok := a.Lookup("") - if !ok { - t.Fatalf("failed to get root of A") - } - broot, ok := b.Lookup("") - if !ok { - t.Fatalf("failed to get root of B") - } - aEntry := stargzEntry{aroot, a} - bEntry := stargzEntry{broot, b} - return contains(t, aEntry, bEntry) && contains(t, bEntry, aEntry) -} - -func compressBlob(t *testing.T, src *io.SectionReader, srcCompression int) *io.SectionReader { - buf := new(bytes.Buffer) - var w io.WriteCloser - var err error - if srcCompression == gzipType { - w = gzip.NewWriter(buf) - } else if srcCompression == zstdType { - w, err = zstd.NewWriter(buf) - if err != nil { - t.Fatalf("failed to init zstd writer: %v", err) - } - } else { - return src - } - src.Seek(0, io.SeekStart) - if _, err := io.Copy(w, src); err != nil { - t.Fatalf("failed to compress source") - } - if err := w.Close(); err != nil { - t.Fatalf("failed to finalize compress source") - } - data := buf.Bytes() - return io.NewSectionReader(bytes.NewReader(data), 0, int64(len(data))) - -} - -type stargzEntry struct { - e *TOCEntry - r *Reader -} - -// contains checks if all child entries in "b" are also contained in "a". -// This function also checks if the files/chunks contain the same contents among "a" and "b". -func contains(t *testing.T, a, b stargzEntry) bool { - ae, ar := a.e, a.r - be, br := b.e, b.r - t.Logf("Comparing: %q vs %q", ae.Name, be.Name) - if !equalEntry(ae, be) { - t.Logf("%q != %q: entry: a: %v, b: %v", ae.Name, be.Name, ae, be) - return false - } - if ae.Type == "dir" { - t.Logf("Directory: %q vs %q: %v vs %v", ae.Name, be.Name, - allChildrenName(ae), allChildrenName(be)) - iscontain := true - ae.ForeachChild(func(aBaseName string, aChild *TOCEntry) bool { - // Walk through all files on this stargz file. - - if aChild.Name == PrefetchLandmark || - aChild.Name == NoPrefetchLandmark { - return true // Ignore landmarks - } - - // Ignore a TOCEntry of "./" (formated as "" by stargz lib) on root directory - // because this points to the root directory itself. - if aChild.Name == "" && ae.Name == "" { - return true - } - - bChild, ok := be.LookupChild(aBaseName) - if !ok { - t.Logf("%q (base: %q): not found in b: %v", - ae.Name, aBaseName, allChildrenName(be)) - iscontain = false - return false - } - - childcontain := contains(t, stargzEntry{aChild, a.r}, stargzEntry{bChild, b.r}) - if !childcontain { - t.Logf("%q != %q: non-equal dir", ae.Name, be.Name) - iscontain = false - return false - } - return true - }) - return iscontain - } else if ae.Type == "reg" { - af, err := ar.OpenFile(ae.Name) - if err != nil { - t.Fatalf("failed to open file %q on A: %v", ae.Name, err) - } - bf, err := br.OpenFile(be.Name) - if err != nil { - t.Fatalf("failed to open file %q on B: %v", be.Name, err) - } - - var nr int64 - for nr < ae.Size { - abytes, anext, aok := readOffset(t, af, nr, a) - bbytes, bnext, bok := readOffset(t, bf, nr, b) - if !aok && !bok { - break - } else if !(aok && bok) || anext != bnext { - t.Logf("%q != %q (offset=%d): chunk existence a=%v vs b=%v, anext=%v vs bnext=%v", - ae.Name, be.Name, nr, aok, bok, anext, bnext) - return false - } - nr = anext - if !bytes.Equal(abytes, bbytes) { - t.Logf("%q != %q: different contents %v vs %v", - ae.Name, be.Name, string(abytes), string(bbytes)) - return false - } - } - return true - } - - return true -} - -func allChildrenName(e *TOCEntry) (children []string) { - e.ForeachChild(func(baseName string, _ *TOCEntry) bool { - children = append(children, baseName) - return true - }) - return -} - -func equalEntry(a, b *TOCEntry) bool { - // Here, we selectively compare fileds that we are interested in. - return a.Name == b.Name && - a.Type == b.Type && - a.Size == b.Size && - a.ModTime3339 == b.ModTime3339 && - a.Stat().ModTime().Equal(b.Stat().ModTime()) && // modTime time.Time - a.LinkName == b.LinkName && - a.Mode == b.Mode && - a.UID == b.UID && - a.GID == b.GID && - a.Uname == b.Uname && - a.Gname == b.Gname && - (a.Offset >= 0) == (b.Offset >= 0) && - (a.NextOffset() > 0) == (b.NextOffset() > 0) && - a.DevMajor == b.DevMajor && - a.DevMinor == b.DevMinor && - a.NumLink == b.NumLink && - reflect.DeepEqual(a.Xattrs, b.Xattrs) && - // chunk-related infomations aren't compared in this function. - // ChunkOffset int64 `json:"chunkOffset,omitempty"` - // ChunkSize int64 `json:"chunkSize,omitempty"` - // children map[string]*TOCEntry - a.Digest == b.Digest -} - -func readOffset(t *testing.T, r *io.SectionReader, offset int64, e stargzEntry) ([]byte, int64, bool) { - ce, ok := e.r.ChunkEntryForOffset(e.e.Name, offset) - if !ok { - return nil, 0, false - } - data := make([]byte, ce.ChunkSize) - t.Logf("Offset: %v, NextOffset: %v", ce.Offset, ce.NextOffset()) - n, err := r.ReadAt(data, ce.ChunkOffset) - if err != nil { - t.Fatalf("failed to read file payload of %q (offset:%d,size:%d): %v", - e.e.Name, ce.ChunkOffset, ce.ChunkSize, err) - } - if int64(n) != ce.ChunkSize { - t.Fatalf("unexpected copied data size %d; want %d", - n, ce.ChunkSize) - } - return data[:n], offset + ce.ChunkSize, true -} - -func dumpTOCJSON(t *testing.T, tocJSON *JTOC) string { - jtocData, err := json.Marshal(*tocJSON) - if err != nil { - t.Fatalf("failed to marshal TOC JSON: %v", err) - } - buf := new(bytes.Buffer) - if _, err := io.Copy(buf, bytes.NewReader(jtocData)); err != nil { - t.Fatalf("failed to read toc json blob: %v", err) - } - return buf.String() -} - -const chunkSize = 3 - -// type check func(t *testing.T, sgzData []byte, tocDigest digest.Digest, dgstMap map[string]digest.Digest, compressionLevel int) -type check func(t *testing.T, sgzData []byte, tocDigest digest.Digest, dgstMap map[string]digest.Digest, controller TestingController, newController TestingControllerFactory) - -// testDigestAndVerify runs specified checks against sample stargz blobs. -func testDigestAndVerify(t *testing.T, controllers ...TestingControllerFactory) { - tests := []struct { - name string - tarInit func(t *testing.T, dgstMap map[string]digest.Digest) (blob []tarEntry) - checks []check - minChunkSize []int - }{ - { - name: "no-regfile", - tarInit: func(t *testing.T, dgstMap map[string]digest.Digest) (blob []tarEntry) { - return tarOf( - dir("test/"), - ) - }, - checks: []check{ - checkStargzTOC, - checkVerifyTOC, - checkVerifyInvalidStargzFail(buildTar(t, tarOf( - dir("test2/"), // modified - ), allowedPrefix[0])), - }, - }, - { - name: "small-files", - tarInit: func(t *testing.T, dgstMap map[string]digest.Digest) (blob []tarEntry) { - return tarOf( - regDigest(t, "baz.txt", "", dgstMap), - regDigest(t, "foo.txt", "a", dgstMap), - dir("test/"), - regDigest(t, "test/bar.txt", "bbb", dgstMap), - ) - }, - minChunkSize: []int{0, 64000}, - checks: []check{ - checkStargzTOC, - checkVerifyTOC, - checkVerifyInvalidStargzFail(buildTar(t, tarOf( - file("baz.txt", ""), - file("foo.txt", "M"), // modified - dir("test/"), - file("test/bar.txt", "bbb"), - ), allowedPrefix[0])), - // checkVerifyInvalidTOCEntryFail("foo.txt"), // TODO - checkVerifyBrokenContentFail("foo.txt"), - }, - }, - { - name: "big-files", - tarInit: func(t *testing.T, dgstMap map[string]digest.Digest) (blob []tarEntry) { - return tarOf( - regDigest(t, "baz.txt", "bazbazbazbazbazbazbaz", dgstMap), - regDigest(t, "foo.txt", "a", dgstMap), - dir("test/"), - regDigest(t, "test/bar.txt", "testbartestbar", dgstMap), - ) - }, - checks: []check{ - checkStargzTOC, - checkVerifyTOC, - checkVerifyInvalidStargzFail(buildTar(t, tarOf( - file("baz.txt", "bazbazbazMMMbazbazbaz"), // modified - file("foo.txt", "a"), - dir("test/"), - file("test/bar.txt", "testbartestbar"), - ), allowedPrefix[0])), - checkVerifyInvalidTOCEntryFail("test/bar.txt"), - checkVerifyBrokenContentFail("test/bar.txt"), - }, - }, - { - name: "with-non-regfiles", - minChunkSize: []int{0, 64000}, - tarInit: func(t *testing.T, dgstMap map[string]digest.Digest) (blob []tarEntry) { - return tarOf( - regDigest(t, "baz.txt", "bazbazbazbazbazbazbaz", dgstMap), - regDigest(t, "foo.txt", "a", dgstMap), - regDigest(t, "bar/foo2.txt", "b", dgstMap), - regDigest(t, "foo3.txt", "c", dgstMap), - symlink("barlink", "test/bar.txt"), - dir("test/"), - regDigest(t, "test/bar.txt", "testbartestbar", dgstMap), - dir("test2/"), - link("test2/bazlink", "baz.txt"), - ) - }, - checks: []check{ - checkStargzTOC, - checkVerifyTOC, - checkVerifyInvalidStargzFail(buildTar(t, tarOf( - file("baz.txt", "bazbazbazbazbazbazbaz"), - file("foo.txt", "a"), - file("bar/foo2.txt", "b"), - file("foo3.txt", "c"), - symlink("barlink", "test/bar.txt"), - dir("test/"), - file("test/bar.txt", "testbartestbar"), - dir("test2/"), - link("test2/bazlink", "foo.txt"), // modified - ), allowedPrefix[0])), - checkVerifyInvalidTOCEntryFail("test/bar.txt"), - checkVerifyBrokenContentFail("test/bar.txt"), - }, - }, - } - - for _, tt := range tests { - if len(tt.minChunkSize) == 0 { - tt.minChunkSize = []int{0} - } - for _, srcCompression := range srcCompressions { - srcCompression := srcCompression - for _, newCL := range controllers { - newCL := newCL - for _, prefix := range allowedPrefix { - prefix := prefix - for _, srcTarFormat := range []tar.Format{tar.FormatUSTAR, tar.FormatPAX, tar.FormatGNU} { - srcTarFormat := srcTarFormat - for _, minChunkSize := range tt.minChunkSize { - minChunkSize := minChunkSize - t.Run(tt.name+"-"+fmt.Sprintf("compression=%v,prefix=%q,format=%s,minChunkSize=%d", newCL(), prefix, srcTarFormat, minChunkSize), func(t *testing.T) { - // Get original tar file and chunk digests - dgstMap := make(map[string]digest.Digest) - tarBlob := buildTar(t, tt.tarInit(t, dgstMap), prefix, srcTarFormat) - - cl := newCL() - rc, err := Build(compressBlob(t, tarBlob, srcCompression), - WithChunkSize(chunkSize), WithCompression(cl)) - if err != nil { - t.Fatalf("failed to convert stargz: %v", err) - } - tocDigest := rc.TOCDigest() - defer rc.Close() - buf := new(bytes.Buffer) - if _, err := io.Copy(buf, rc); err != nil { - t.Fatalf("failed to copy built stargz blob: %v", err) - } - newStargz := buf.Bytes() - // NoPrefetchLandmark is added during `Bulid`, which is expected behaviour. - dgstMap[chunkID(NoPrefetchLandmark, 0, int64(len([]byte{landmarkContents})))] = digest.FromBytes([]byte{landmarkContents}) - - for _, check := range tt.checks { - check(t, newStargz, tocDigest, dgstMap, cl, newCL) - } - }) - } - } - } - } - } - } -} - -// checkStargzTOC checks the TOC JSON of the passed stargz has the expected -// digest and contains valid chunks. It walks all entries in the stargz and -// checks all chunk digests stored to the TOC JSON match the actual contents. -func checkStargzTOC(t *testing.T, sgzData []byte, tocDigest digest.Digest, dgstMap map[string]digest.Digest, controller TestingController, newController TestingControllerFactory) { - sgz, err := Open( - io.NewSectionReader(bytes.NewReader(sgzData), 0, int64(len(sgzData))), - WithDecompressors(controller), - ) - if err != nil { - t.Errorf("failed to parse converted stargz: %v", err) - return - } - digestMapTOC, err := listDigests(io.NewSectionReader( - bytes.NewReader(sgzData), 0, int64(len(sgzData))), - controller, - ) - if err != nil { - t.Fatalf("failed to list digest: %v", err) - } - found := make(map[string]bool) - for id := range dgstMap { - found[id] = false - } - zr, err := controller.Reader(bytes.NewReader(sgzData)) - if err != nil { - t.Fatalf("failed to decompress converted stargz: %v", err) - } - defer zr.Close() - tr := tar.NewReader(zr) - for { - h, err := tr.Next() - if err != nil { - if err != io.EOF { - t.Errorf("failed to read tar entry: %v", err) - return - } - break - } - if h.Name == TOCTarName { - // Check the digest of TOC JSON based on the actual contents - // It's sure that TOC JSON exists in this archive because - // Open succeeded. - dgstr := digest.Canonical.Digester() - if _, err := io.Copy(dgstr.Hash(), tr); err != nil { - t.Fatalf("failed to calculate digest of TOC JSON: %v", - err) - } - if dgstr.Digest() != tocDigest { - t.Errorf("invalid TOC JSON %q; want %q", tocDigest, dgstr.Digest()) - } - continue - } - if _, ok := sgz.Lookup(h.Name); !ok { - t.Errorf("lost stargz entry %q in the converted TOC", h.Name) - return - } - var n int64 - for n < h.Size { - ce, ok := sgz.ChunkEntryForOffset(h.Name, n) - if !ok { - t.Errorf("lost chunk %q(offset=%d) in the converted TOC", - h.Name, n) - return - } - - // Get the original digest to make sure the file contents are kept unchanged - // from the original tar, during the whole conversion steps. - id := chunkID(h.Name, n, ce.ChunkSize) - want, ok := dgstMap[id] - if !ok { - t.Errorf("Unexpected chunk %q(offset=%d,size=%d): %v", - h.Name, n, ce.ChunkSize, dgstMap) - return - } - found[id] = true - - // Check the file contents - dgstr := digest.Canonical.Digester() - if _, err := io.CopyN(dgstr.Hash(), tr, ce.ChunkSize); err != nil { - t.Fatalf("failed to calculate digest of %q (offset=%d,size=%d)", - h.Name, n, ce.ChunkSize) - } - if want != dgstr.Digest() { - t.Errorf("Invalid contents in converted stargz %q: %q; want %q", - h.Name, dgstr.Digest(), want) - return - } - - // Check the digest stored in TOC JSON - dgstTOC, ok := digestMapTOC[ce.Offset] - if !ok { - t.Errorf("digest of %q(offset=%d,size=%d,chunkOffset=%d) isn't registered", - h.Name, ce.Offset, ce.ChunkSize, ce.ChunkOffset) - } - if want != dgstTOC { - t.Errorf("Invalid digest in TOCEntry %q: %q; want %q", - h.Name, dgstTOC, want) - return - } - - n += ce.ChunkSize - } - } - - for id, ok := range found { - if !ok { - t.Errorf("required chunk %q not found in the converted stargz: %v", id, found) - } - } -} - -// checkVerifyTOC checks the verification works for the TOC JSON of the passed -// stargz. It walks all entries in the stargz and checks the verifications for -// all chunks work. -func checkVerifyTOC(t *testing.T, sgzData []byte, tocDigest digest.Digest, dgstMap map[string]digest.Digest, controller TestingController, newController TestingControllerFactory) { - sgz, err := Open( - io.NewSectionReader(bytes.NewReader(sgzData), 0, int64(len(sgzData))), - WithDecompressors(controller), - ) - if err != nil { - t.Errorf("failed to parse converted stargz: %v", err) - return - } - ev, err := sgz.VerifyTOC(tocDigest) - if err != nil { - t.Errorf("failed to verify stargz: %v", err) - return - } - - found := make(map[string]bool) - for id := range dgstMap { - found[id] = false - } - zr, err := controller.Reader(bytes.NewReader(sgzData)) - if err != nil { - t.Fatalf("failed to decompress converted stargz: %v", err) - } - defer zr.Close() - tr := tar.NewReader(zr) - for { - h, err := tr.Next() - if err != nil { - if err != io.EOF { - t.Errorf("failed to read tar entry: %v", err) - return - } - break - } - if h.Name == TOCTarName { - continue - } - if _, ok := sgz.Lookup(h.Name); !ok { - t.Errorf("lost stargz entry %q in the converted TOC", h.Name) - return - } - var n int64 - for n < h.Size { - ce, ok := sgz.ChunkEntryForOffset(h.Name, n) - if !ok { - t.Errorf("lost chunk %q(offset=%d) in the converted TOC", - h.Name, n) - return - } - - v, err := ev.Verifier(ce) - if err != nil { - t.Errorf("failed to get verifier for %q(offset=%d)", h.Name, n) - } - - found[chunkID(h.Name, n, ce.ChunkSize)] = true - - // Check the file contents - if _, err := io.CopyN(v, tr, ce.ChunkSize); err != nil { - t.Fatalf("failed to get chunk of %q (offset=%d,size=%d)", - h.Name, n, ce.ChunkSize) - } - if !v.Verified() { - t.Errorf("Invalid contents in converted stargz %q (should be succeeded)", - h.Name) - return - } - n += ce.ChunkSize - } - } - - for id, ok := range found { - if !ok { - t.Errorf("required chunk %q not found in the converted stargz: %v", id, found) - } - } -} - -// checkVerifyInvalidTOCEntryFail checks if misconfigured TOC JSON can be -// detected during the verification and the verification returns an error. -func checkVerifyInvalidTOCEntryFail(filename string) check { - return func(t *testing.T, sgzData []byte, tocDigest digest.Digest, dgstMap map[string]digest.Digest, controller TestingController, newController TestingControllerFactory) { - funcs := map[string]rewriteFunc{ - "lost digest in a entry": func(t *testing.T, toc *JTOC, sgz *io.SectionReader) { - var found bool - for _, e := range toc.Entries { - if cleanEntryName(e.Name) == filename { - if e.Type != "reg" && e.Type != "chunk" { - t.Fatalf("entry %q to break must be regfile or chunk", filename) - } - if e.ChunkDigest == "" { - t.Fatalf("entry %q is already invalid", filename) - } - e.ChunkDigest = "" - found = true - } - } - if !found { - t.Fatalf("rewrite target not found") - } - }, - "duplicated entry offset": func(t *testing.T, toc *JTOC, sgz *io.SectionReader) { - var ( - sampleEntry *TOCEntry - targetEntry *TOCEntry - ) - for _, e := range toc.Entries { - if e.Type == "reg" || e.Type == "chunk" { - if cleanEntryName(e.Name) == filename { - targetEntry = e - } else { - sampleEntry = e - } - } - } - if sampleEntry == nil { - t.Fatalf("TOC must contain at least one regfile or chunk entry other than the rewrite target") - } - if targetEntry == nil { - t.Fatalf("rewrite target not found") - } - targetEntry.Offset = sampleEntry.Offset - }, - } - - for name, rFunc := range funcs { - t.Run(name, func(t *testing.T) { - newSgz, newTocDigest := rewriteTOCJSON(t, io.NewSectionReader(bytes.NewReader(sgzData), 0, int64(len(sgzData))), rFunc, controller) - buf := new(bytes.Buffer) - if _, err := io.Copy(buf, newSgz); err != nil { - t.Fatalf("failed to get converted stargz") - } - isgz := buf.Bytes() - - sgz, err := Open( - io.NewSectionReader(bytes.NewReader(isgz), 0, int64(len(isgz))), - WithDecompressors(controller), - ) - if err != nil { - t.Fatalf("failed to parse converted stargz: %v", err) - return - } - _, err = sgz.VerifyTOC(newTocDigest) - if err == nil { - t.Errorf("must fail for invalid TOC") - return - } - }) - } - } -} - -// checkVerifyInvalidStargzFail checks if the verification detects that the -// given stargz file doesn't match to the expected digest and returns error. -func checkVerifyInvalidStargzFail(invalid *io.SectionReader) check { - return func(t *testing.T, sgzData []byte, tocDigest digest.Digest, dgstMap map[string]digest.Digest, controller TestingController, newController TestingControllerFactory) { - cl := newController() - rc, err := Build(invalid, WithChunkSize(chunkSize), WithCompression(cl)) - if err != nil { - t.Fatalf("failed to convert stargz: %v", err) - } - defer rc.Close() - buf := new(bytes.Buffer) - if _, err := io.Copy(buf, rc); err != nil { - t.Fatalf("failed to copy built stargz blob: %v", err) - } - mStargz := buf.Bytes() - - sgz, err := Open( - io.NewSectionReader(bytes.NewReader(mStargz), 0, int64(len(mStargz))), - WithDecompressors(cl), - ) - if err != nil { - t.Fatalf("failed to parse converted stargz: %v", err) - return - } - _, err = sgz.VerifyTOC(tocDigest) - if err == nil { - t.Errorf("must fail for invalid TOC") - return - } - } -} - -// checkVerifyBrokenContentFail checks if the verifier detects broken contents -// that doesn't match to the expected digest and returns error. -func checkVerifyBrokenContentFail(filename string) check { - return func(t *testing.T, sgzData []byte, tocDigest digest.Digest, dgstMap map[string]digest.Digest, controller TestingController, newController TestingControllerFactory) { - // Parse stargz file - sgz, err := Open( - io.NewSectionReader(bytes.NewReader(sgzData), 0, int64(len(sgzData))), - WithDecompressors(controller), - ) - if err != nil { - t.Fatalf("failed to parse converted stargz: %v", err) - return - } - ev, err := sgz.VerifyTOC(tocDigest) - if err != nil { - t.Fatalf("failed to verify stargz: %v", err) - return - } - - // Open the target file - sr, err := sgz.OpenFile(filename) - if err != nil { - t.Fatalf("failed to open file %q", filename) - } - ce, ok := sgz.ChunkEntryForOffset(filename, 0) - if !ok { - t.Fatalf("lost chunk %q(offset=%d) in the converted TOC", filename, 0) - return - } - if ce.ChunkSize == 0 { - t.Fatalf("file mustn't be empty") - return - } - data := make([]byte, ce.ChunkSize) - if _, err := sr.ReadAt(data, ce.ChunkOffset); err != nil { - t.Errorf("failed to get data of a chunk of %q(offset=%q)", - filename, ce.ChunkOffset) - } - - // Check the broken chunk (must fail) - v, err := ev.Verifier(ce) - if err != nil { - t.Fatalf("failed to get verifier for %q", filename) - } - broken := append([]byte{^data[0]}, data[1:]...) - if _, err := io.CopyN(v, bytes.NewReader(broken), ce.ChunkSize); err != nil { - t.Fatalf("failed to get chunk of %q (offset=%d,size=%d)", - filename, ce.ChunkOffset, ce.ChunkSize) - } - if v.Verified() { - t.Errorf("verification must fail for broken file chunk %q(org:%q,broken:%q)", - filename, data, broken) - } - } -} - -func chunkID(name string, offset, size int64) string { - return fmt.Sprintf("%s-%d-%d", cleanEntryName(name), offset, size) -} - -type rewriteFunc func(t *testing.T, toc *JTOC, sgz *io.SectionReader) - -func rewriteTOCJSON(t *testing.T, sgz *io.SectionReader, rewrite rewriteFunc, controller TestingController) (newSgz io.Reader, tocDigest digest.Digest) { - decodedJTOC, jtocOffset, err := parseStargz(sgz, controller) - if err != nil { - t.Fatalf("failed to extract TOC JSON: %v", err) - } - - rewrite(t, decodedJTOC, sgz) - - tocFooter, tocDigest, err := tocAndFooter(controller, decodedJTOC, jtocOffset) - if err != nil { - t.Fatalf("failed to create toc and footer: %v", err) - } - - // Reconstruct stargz file with the modified TOC JSON - if _, err := sgz.Seek(0, io.SeekStart); err != nil { - t.Fatalf("failed to reset the seek position of stargz: %v", err) - } - return io.MultiReader( - io.LimitReader(sgz, jtocOffset), // Original stargz (before TOC JSON) - tocFooter, // Rewritten TOC and footer - ), tocDigest -} - -func listDigests(sgz *io.SectionReader, controller TestingController) (map[int64]digest.Digest, error) { - decodedJTOC, _, err := parseStargz(sgz, controller) - if err != nil { - return nil, err - } - digestMap := make(map[int64]digest.Digest) - for _, e := range decodedJTOC.Entries { - if e.Type == "reg" || e.Type == "chunk" { - if e.Type == "reg" && e.Size == 0 { - continue // ignores empty file - } - if e.ChunkDigest == "" { - return nil, fmt.Errorf("ChunkDigest of %q(off=%d) not found in TOC JSON", - e.Name, e.Offset) - } - d, err := digest.Parse(e.ChunkDigest) - if err != nil { - return nil, err - } - digestMap[e.Offset] = d - } - } - return digestMap, nil -} - -func parseStargz(sgz *io.SectionReader, controller TestingController) (decodedJTOC *JTOC, jtocOffset int64, err error) { - fSize := controller.FooterSize() - footer := make([]byte, fSize) - if _, err := sgz.ReadAt(footer, sgz.Size()-fSize); err != nil { - return nil, 0, fmt.Errorf("error reading footer: %w", err) - } - _, tocOffset, _, err := controller.ParseFooter(footer[positive(int64(len(footer))-fSize):]) - if err != nil { - return nil, 0, fmt.Errorf("failed to parse footer: %w", err) - } - - // Decode the TOC JSON - var tocReader io.Reader - if tocOffset >= 0 { - tocReader = io.NewSectionReader(sgz, tocOffset, sgz.Size()-tocOffset-fSize) - } - decodedJTOC, _, err = controller.ParseTOC(tocReader) - if err != nil { - return nil, 0, fmt.Errorf("failed to parse TOC: %w", err) - } - return decodedJTOC, tocOffset, nil -} - -func testWriteAndOpen(t *testing.T, controllers ...TestingControllerFactory) { - const content = "Some contents" - invalidUtf8 := "\xff\xfe\xfd" - - xAttrFile := xAttr{"foo": "bar", "invalid-utf8": invalidUtf8} - sampleOwner := owner{uid: 50, gid: 100} - - data64KB := randomContents(64000) - - tests := []struct { - name string - chunkSize int - minChunkSize int - in []tarEntry - want []stargzCheck - wantNumGz int // expected number of streams - - wantNumGzLossLess int // expected number of streams (> 0) in lossless mode if it's different from wantNumGz - wantFailOnLossLess bool - wantTOCVersion int // default = 1 - }{ - { - name: "empty", - in: tarOf(), - wantNumGz: 2, // (empty tar) + TOC + footer - want: checks( - numTOCEntries(0), - ), - }, - { - name: "1dir_1empty_file", - in: tarOf( - dir("foo/"), - file("foo/bar.txt", ""), - ), - wantNumGz: 3, // dir, TOC, footer - want: checks( - numTOCEntries(2), - hasDir("foo/"), - hasFileLen("foo/bar.txt", 0), - entryHasChildren("foo", "bar.txt"), - hasFileDigest("foo/bar.txt", digestFor("")), - ), - }, - { - name: "1dir_1file", - in: tarOf( - dir("foo/"), - file("foo/bar.txt", content, xAttrFile), - ), - wantNumGz: 4, // var dir, foo.txt alone, TOC, footer - want: checks( - numTOCEntries(2), - hasDir("foo/"), - hasFileLen("foo/bar.txt", len(content)), - hasFileDigest("foo/bar.txt", digestFor(content)), - hasFileContentsRange("foo/bar.txt", 0, content), - hasFileContentsRange("foo/bar.txt", 1, content[1:]), - entryHasChildren("", "foo"), - entryHasChildren("foo", "bar.txt"), - hasFileXattrs("foo/bar.txt", "foo", "bar"), - hasFileXattrs("foo/bar.txt", "invalid-utf8", invalidUtf8), - ), - }, - { - name: "2meta_2file", - in: tarOf( - dir("bar/", sampleOwner), - dir("foo/", sampleOwner), - file("foo/bar.txt", content, sampleOwner), - ), - wantNumGz: 4, // both dirs, foo.txt alone, TOC, footer - want: checks( - numTOCEntries(3), - hasDir("bar/"), - hasDir("foo/"), - hasFileLen("foo/bar.txt", len(content)), - entryHasChildren("", "bar", "foo"), - entryHasChildren("foo", "bar.txt"), - hasChunkEntries("foo/bar.txt", 1), - hasEntryOwner("bar/", sampleOwner), - hasEntryOwner("foo/", sampleOwner), - hasEntryOwner("foo/bar.txt", sampleOwner), - ), - }, - { - name: "3dir", - in: tarOf( - dir("bar/"), - dir("foo/"), - dir("foo/bar/"), - ), - wantNumGz: 3, // 3 dirs, TOC, footer - want: checks( - hasDirLinkCount("bar/", 2), - hasDirLinkCount("foo/", 3), - hasDirLinkCount("foo/bar/", 2), - ), - }, - { - name: "symlink", - in: tarOf( - dir("foo/"), - symlink("foo/bar", "../../x"), - ), - wantNumGz: 3, // metas + TOC + footer - want: checks( - numTOCEntries(2), - hasSymlink("foo/bar", "../../x"), - entryHasChildren("", "foo"), - entryHasChildren("foo", "bar"), - ), - }, - { - name: "chunked_file", - chunkSize: 4, - in: tarOf( - dir("foo/"), - file("foo/big.txt", "This "+"is s"+"uch "+"a bi"+"g fi"+"le"), - ), - wantNumGz: 9, // dir + big.txt(6 chunks) + TOC + footer - want: checks( - numTOCEntries(7), // 1 for foo dir, 6 for the foo/big.txt file - hasDir("foo/"), - hasFileLen("foo/big.txt", len("This is such a big file")), - hasFileDigest("foo/big.txt", digestFor("This is such a big file")), - hasFileContentsRange("foo/big.txt", 0, "This is such a big file"), - hasFileContentsRange("foo/big.txt", 1, "his is such a big file"), - hasFileContentsRange("foo/big.txt", 2, "is is such a big file"), - hasFileContentsRange("foo/big.txt", 3, "s is such a big file"), - hasFileContentsRange("foo/big.txt", 4, " is such a big file"), - hasFileContentsRange("foo/big.txt", 5, "is such a big file"), - hasFileContentsRange("foo/big.txt", 6, "s such a big file"), - hasFileContentsRange("foo/big.txt", 7, " such a big file"), - hasFileContentsRange("foo/big.txt", 8, "such a big file"), - hasFileContentsRange("foo/big.txt", 9, "uch a big file"), - hasFileContentsRange("foo/big.txt", 10, "ch a big file"), - hasFileContentsRange("foo/big.txt", 11, "h a big file"), - hasFileContentsRange("foo/big.txt", 12, " a big file"), - hasFileContentsRange("foo/big.txt", len("This is such a big file")-1, ""), - hasChunkEntries("foo/big.txt", 6), - ), - }, - { - name: "recursive", - in: tarOf( - dir("/", sampleOwner), - dir("bar/", sampleOwner), - dir("foo/", sampleOwner), - file("foo/bar.txt", content, sampleOwner), - ), - wantNumGz: 4, // dirs, bar.txt alone, TOC, footer - want: checks( - maxDepth(2), // 0: root directory, 1: "foo/", 2: "bar.txt" - ), - }, - { - name: "block_char_fifo", - in: tarOf( - tarEntryFunc(func(w *tar.Writer, prefix string, format tar.Format) error { - return w.WriteHeader(&tar.Header{ - Name: prefix + "b", - Typeflag: tar.TypeBlock, - Devmajor: 123, - Devminor: 456, - Format: format, - }) - }), - tarEntryFunc(func(w *tar.Writer, prefix string, format tar.Format) error { - return w.WriteHeader(&tar.Header{ - Name: prefix + "c", - Typeflag: tar.TypeChar, - Devmajor: 111, - Devminor: 222, - Format: format, - }) - }), - tarEntryFunc(func(w *tar.Writer, prefix string, format tar.Format) error { - return w.WriteHeader(&tar.Header{ - Name: prefix + "f", - Typeflag: tar.TypeFifo, - Format: format, - }) - }), - ), - wantNumGz: 3, - want: checks( - lookupMatch("b", &TOCEntry{Name: "b", Type: "block", DevMajor: 123, DevMinor: 456, NumLink: 1}), - lookupMatch("c", &TOCEntry{Name: "c", Type: "char", DevMajor: 111, DevMinor: 222, NumLink: 1}), - lookupMatch("f", &TOCEntry{Name: "f", Type: "fifo", NumLink: 1}), - ), - }, - { - name: "modes", - in: tarOf( - dir("foo1/", 0755|os.ModeDir|os.ModeSetgid), - file("foo1/bar1", content, 0700|os.ModeSetuid), - file("foo1/bar2", content, 0755|os.ModeSetgid), - dir("foo2/", 0755|os.ModeDir|os.ModeSticky), - file("foo2/bar3", content, 0755|os.ModeSticky), - dir("foo3/", 0755|os.ModeDir), - file("foo3/bar4", content, os.FileMode(0700)), - file("foo3/bar5", content, os.FileMode(0755)), - ), - wantNumGz: 8, // dir, bar1 alone, bar2 alone + dir, bar3 alone + dir, bar4 alone, bar5 alone, TOC, footer - want: checks( - hasMode("foo1/", 0755|os.ModeDir|os.ModeSetgid), - hasMode("foo1/bar1", 0700|os.ModeSetuid), - hasMode("foo1/bar2", 0755|os.ModeSetgid), - hasMode("foo2/", 0755|os.ModeDir|os.ModeSticky), - hasMode("foo2/bar3", 0755|os.ModeSticky), - hasMode("foo3/", 0755|os.ModeDir), - hasMode("foo3/bar4", os.FileMode(0700)), - hasMode("foo3/bar5", os.FileMode(0755)), - ), - }, - { - name: "lossy", - in: tarOf( - dir("bar/", sampleOwner), - dir("foo/", sampleOwner), - file("foo/bar.txt", content, sampleOwner), - file(TOCTarName, "dummy"), // ignored by the writer. (lossless write returns error) - ), - wantNumGz: 4, // both dirs, foo.txt alone, TOC, footer - want: checks( - numTOCEntries(3), - hasDir("bar/"), - hasDir("foo/"), - hasFileLen("foo/bar.txt", len(content)), - entryHasChildren("", "bar", "foo"), - entryHasChildren("foo", "bar.txt"), - hasChunkEntries("foo/bar.txt", 1), - hasEntryOwner("bar/", sampleOwner), - hasEntryOwner("foo/", sampleOwner), - hasEntryOwner("foo/bar.txt", sampleOwner), - ), - wantFailOnLossLess: true, - }, - { - name: "hardlink should be replaced to the destination entry", - in: tarOf( - dir("foo/"), - file("foo/foo1", "test"), - link("foolink", "foo/foo1"), - ), - wantNumGz: 4, // dir, foo1 + link, TOC, footer - want: checks( - mustSameEntry("foo/foo1", "foolink"), - ), - }, - { - name: "several_files_in_chunk", - minChunkSize: 8000, - in: tarOf( - dir("foo/"), - file("foo/foo1", data64KB), - file("foo2", "bb"), - file("foo22", "ccc"), - dir("bar/"), - file("bar/bar.txt", "aaa"), - file("foo3", data64KB), - ), - // NOTE: we assume that the compressed "data64KB" is still larger than 8KB - wantNumGz: 4, // dir+foo1, foo2+foo22+dir+bar.txt+foo3, TOC, footer - want: checks( - numTOCEntries(7), // dir, foo1, foo2, foo22, dir, bar.txt, foo3 - hasDir("foo/"), - hasDir("bar/"), - hasFileLen("foo/foo1", len(data64KB)), - hasFileLen("foo2", len("bb")), - hasFileLen("foo22", len("ccc")), - hasFileLen("bar/bar.txt", len("aaa")), - hasFileLen("foo3", len(data64KB)), - hasFileDigest("foo/foo1", digestFor(data64KB)), - hasFileDigest("foo2", digestFor("bb")), - hasFileDigest("foo22", digestFor("ccc")), - hasFileDigest("bar/bar.txt", digestFor("aaa")), - hasFileDigest("foo3", digestFor(data64KB)), - hasFileContentsWithPreRead("foo22", 0, "ccc", chunkInfo{"foo2", "bb"}, chunkInfo{"bar/bar.txt", "aaa"}, chunkInfo{"foo3", data64KB}), - hasFileContentsRange("foo/foo1", 0, data64KB), - hasFileContentsRange("foo2", 0, "bb"), - hasFileContentsRange("foo2", 1, "b"), - hasFileContentsRange("foo22", 0, "ccc"), - hasFileContentsRange("foo22", 1, "cc"), - hasFileContentsRange("foo22", 2, "c"), - hasFileContentsRange("bar/bar.txt", 0, "aaa"), - hasFileContentsRange("bar/bar.txt", 1, "aa"), - hasFileContentsRange("bar/bar.txt", 2, "a"), - hasFileContentsRange("foo3", 0, data64KB), - hasFileContentsRange("foo3", 1, data64KB[1:]), - hasFileContentsRange("foo3", 2, data64KB[2:]), - hasFileContentsRange("foo3", len(data64KB)/2, data64KB[len(data64KB)/2:]), - hasFileContentsRange("foo3", len(data64KB)-1, data64KB[len(data64KB)-1:]), - ), - }, - { - name: "several_files_in_chunk_chunked", - minChunkSize: 8000, - chunkSize: 32000, - in: tarOf( - dir("foo/"), - file("foo/foo1", data64KB), - file("foo2", "bb"), - dir("bar/"), - file("foo3", data64KB), - ), - // NOTE: we assume that the compressed chunk of "data64KB" is still larger than 8KB - wantNumGz: 6, // dir+foo1(1), foo1(2), foo2+dir+foo3(1), foo3(2), TOC, footer - want: checks( - numTOCEntries(7), // dir, foo1(2 chunks), foo2, dir, foo3(2 chunks) - hasDir("foo/"), - hasDir("bar/"), - hasFileLen("foo/foo1", len(data64KB)), - hasFileLen("foo2", len("bb")), - hasFileLen("foo3", len(data64KB)), - hasFileDigest("foo/foo1", digestFor(data64KB)), - hasFileDigest("foo2", digestFor("bb")), - hasFileDigest("foo3", digestFor(data64KB)), - hasFileContentsWithPreRead("foo2", 0, "bb", chunkInfo{"foo3", data64KB[:32000]}), - hasFileContentsRange("foo/foo1", 0, data64KB), - hasFileContentsRange("foo/foo1", 1, data64KB[1:]), - hasFileContentsRange("foo/foo1", 2, data64KB[2:]), - hasFileContentsRange("foo/foo1", len(data64KB)/2, data64KB[len(data64KB)/2:]), - hasFileContentsRange("foo/foo1", len(data64KB)-1, data64KB[len(data64KB)-1:]), - hasFileContentsRange("foo2", 0, "bb"), - hasFileContentsRange("foo2", 1, "b"), - hasFileContentsRange("foo3", 0, data64KB), - hasFileContentsRange("foo3", 1, data64KB[1:]), - hasFileContentsRange("foo3", 2, data64KB[2:]), - hasFileContentsRange("foo3", len(data64KB)/2, data64KB[len(data64KB)/2:]), - hasFileContentsRange("foo3", len(data64KB)-1, data64KB[len(data64KB)-1:]), - ), - }, - } - - for _, tt := range tests { - for _, newCL := range controllers { - newCL := newCL - for _, prefix := range allowedPrefix { - prefix := prefix - for _, srcTarFormat := range []tar.Format{tar.FormatUSTAR, tar.FormatPAX, tar.FormatGNU} { - srcTarFormat := srcTarFormat - for _, lossless := range []bool{true, false} { - t.Run(tt.name+"-"+fmt.Sprintf("compression=%v,prefix=%q,lossless=%v,format=%s", newCL(), prefix, lossless, srcTarFormat), func(t *testing.T) { - var tr io.Reader = buildTar(t, tt.in, prefix, srcTarFormat) - origTarDgstr := digest.Canonical.Digester() - tr = io.TeeReader(tr, origTarDgstr.Hash()) - var stargzBuf bytes.Buffer - cl1 := newCL() - w := NewWriterWithCompressor(&stargzBuf, cl1) - w.ChunkSize = tt.chunkSize - w.MinChunkSize = tt.minChunkSize - if lossless { - err := w.AppendTarLossLess(tr) - if tt.wantFailOnLossLess { - if err != nil { - return // expected to fail - } - t.Fatalf("Append wanted to fail on lossless") - } - if err != nil { - t.Fatalf("Append(lossless): %v", err) - } - } else { - if err := w.AppendTar(tr); err != nil { - t.Fatalf("Append: %v", err) - } - } - if _, err := w.Close(); err != nil { - t.Fatalf("Writer.Close: %v", err) - } - b := stargzBuf.Bytes() - - if lossless { - // Check if the result blob reserves original tar metadata - rc, err := Unpack(io.NewSectionReader(bytes.NewReader(b), 0, int64(len(b))), cl1) - if err != nil { - t.Errorf("failed to decompress blob: %v", err) - return - } - defer rc.Close() - resultDgstr := digest.Canonical.Digester() - if _, err := io.Copy(resultDgstr.Hash(), rc); err != nil { - t.Errorf("failed to read result decompressed blob: %v", err) - return - } - if resultDgstr.Digest() != origTarDgstr.Digest() { - t.Errorf("lossy compression occurred: digest=%v; want %v", - resultDgstr.Digest(), origTarDgstr.Digest()) - return - } - } - - diffID := w.DiffID() - wantDiffID := cl1.DiffIDOf(t, b) - if diffID != wantDiffID { - t.Errorf("DiffID = %q; want %q", diffID, wantDiffID) - } - - telemetry, checkCalled := newCalledTelemetry() - sr := io.NewSectionReader(bytes.NewReader(b), 0, int64(len(b))) - r, err := Open( - sr, - WithDecompressors(cl1), - WithTelemetry(telemetry), - ) - if err != nil { - t.Fatalf("stargz.Open: %v", err) - } - wantTOCVersion := 1 - if tt.wantTOCVersion > 0 { - wantTOCVersion = tt.wantTOCVersion - } - if r.toc.Version != wantTOCVersion { - t.Fatalf("invalid TOC Version %d; wanted %d", r.toc.Version, wantTOCVersion) - } - - footerSize := cl1.FooterSize() - footerOffset := sr.Size() - footerSize - footer := make([]byte, footerSize) - if _, err := sr.ReadAt(footer, footerOffset); err != nil { - t.Errorf("failed to read footer: %v", err) - } - _, tocOffset, _, err := cl1.ParseFooter(footer) - if err != nil { - t.Errorf("failed to parse footer: %v", err) - } - if err := checkCalled(tocOffset >= 0); err != nil { - t.Errorf("telemetry failure: %v", err) - } - - wantNumGz := tt.wantNumGz - if lossless && tt.wantNumGzLossLess > 0 { - wantNumGz = tt.wantNumGzLossLess - } - streamOffsets := []int64{0} - prevOffset := int64(-1) - streams := 0 - for _, e := range r.toc.Entries { - if e.Offset > prevOffset { - streamOffsets = append(streamOffsets, e.Offset) - prevOffset = e.Offset - streams++ - } - } - streams++ // TOC - if tocOffset >= 0 { - // toc is in the blob - streamOffsets = append(streamOffsets, tocOffset) - } - streams++ // footer - streamOffsets = append(streamOffsets, footerOffset) - if streams != wantNumGz { - t.Errorf("number of streams in TOC = %d; want %d", streams, wantNumGz) - } - - t.Logf("testing streams: %+v", streamOffsets) - cl1.TestStreams(t, b, streamOffsets) - - for _, want := range tt.want { - want.check(t, r) - } - }) - } - } - } - } - } -} - -type chunkInfo struct { - name string - data string -} - -func newCalledTelemetry() (telemetry *Telemetry, check func(needsGetTOC bool) error) { - var getFooterLatencyCalled bool - var getTocLatencyCalled bool - var deserializeTocLatencyCalled bool - return &Telemetry{ - func(time.Time) { getFooterLatencyCalled = true }, - func(time.Time) { getTocLatencyCalled = true }, - func(time.Time) { deserializeTocLatencyCalled = true }, - }, func(needsGetTOC bool) error { - var allErr []error - if !getFooterLatencyCalled { - allErr = append(allErr, fmt.Errorf("metrics GetFooterLatency isn't called")) - } - if needsGetTOC { - if !getTocLatencyCalled { - allErr = append(allErr, fmt.Errorf("metrics GetTocLatency isn't called")) - } - } - if !deserializeTocLatencyCalled { - allErr = append(allErr, fmt.Errorf("metrics DeserializeTocLatency isn't called")) - } - return errorutil.Aggregate(allErr) - } -} - -func digestFor(content string) string { - sum := sha256.Sum256([]byte(content)) - return fmt.Sprintf("sha256:%x", sum) -} - -type numTOCEntries int - -func (n numTOCEntries) check(t *testing.T, r *Reader) { - if r.toc == nil { - t.Fatal("nil TOC") - } - if got, want := len(r.toc.Entries), int(n); got != want { - t.Errorf("got %d TOC entries; want %d", got, want) - } - t.Logf("got TOC entries:") - for i, ent := range r.toc.Entries { - entj, _ := json.Marshal(ent) - t.Logf(" [%d]: %s\n", i, entj) - } - if t.Failed() { - t.FailNow() - } -} - -func checks(s ...stargzCheck) []stargzCheck { return s } - -type stargzCheck interface { - check(t *testing.T, r *Reader) -} - -type stargzCheckFn func(*testing.T, *Reader) - -func (f stargzCheckFn) check(t *testing.T, r *Reader) { f(t, r) } - -func maxDepth(max int) stargzCheck { - return stargzCheckFn(func(t *testing.T, r *Reader) { - e, ok := r.Lookup("") - if !ok { - t.Fatal("root directory not found") - } - d, err := getMaxDepth(t, e, 0, 10*max) - if err != nil { - t.Errorf("failed to get max depth (wanted %d): %v", max, err) - return - } - if d != max { - t.Errorf("invalid depth %d; want %d", d, max) - return - } - }) -} - -func getMaxDepth(t *testing.T, e *TOCEntry, current, limit int) (max int, rErr error) { - if current > limit { - return -1, fmt.Errorf("walkMaxDepth: exceeds limit: current:%d > limit:%d", - current, limit) - } - max = current - e.ForeachChild(func(baseName string, ent *TOCEntry) bool { - t.Logf("%q(basename:%q) is child of %q\n", ent.Name, baseName, e.Name) - d, err := getMaxDepth(t, ent, current+1, limit) - if err != nil { - rErr = err - return false - } - if d > max { - max = d - } - return true - }) - return -} - -func hasFileLen(file string, wantLen int) stargzCheck { - return stargzCheckFn(func(t *testing.T, r *Reader) { - for _, ent := range r.toc.Entries { - if ent.Name == file { - if ent.Type != "reg" { - t.Errorf("file type of %q is %q; want \"reg\"", file, ent.Type) - } else if ent.Size != int64(wantLen) { - t.Errorf("file size of %q = %d; want %d", file, ent.Size, wantLen) - } - return - } - } - t.Errorf("file %q not found", file) - }) -} - -func hasFileXattrs(file, name, value string) stargzCheck { - return stargzCheckFn(func(t *testing.T, r *Reader) { - for _, ent := range r.toc.Entries { - if ent.Name == file { - if ent.Type != "reg" { - t.Errorf("file type of %q is %q; want \"reg\"", file, ent.Type) - } - if ent.Xattrs == nil { - t.Errorf("file %q has no xattrs", file) - return - } - valueFound, found := ent.Xattrs[name] - if !found { - t.Errorf("file %q has no xattr %q", file, name) - return - } - if string(valueFound) != value { - t.Errorf("file %q has xattr %q with value %q instead of %q", file, name, valueFound, value) - } - - return - } - } - t.Errorf("file %q not found", file) - }) -} - -func hasFileDigest(file string, digest string) stargzCheck { - return stargzCheckFn(func(t *testing.T, r *Reader) { - ent, ok := r.Lookup(file) - if !ok { - t.Fatalf("didn't find TOCEntry for file %q", file) - } - if ent.Digest != digest { - t.Fatalf("Digest(%q) = %q, want %q", file, ent.Digest, digest) - } - }) -} - -func hasFileContentsWithPreRead(file string, offset int, want string, extra ...chunkInfo) stargzCheck { - return stargzCheckFn(func(t *testing.T, r *Reader) { - extraMap := make(map[string]chunkInfo) - for _, e := range extra { - extraMap[e.name] = e - } - var extraNames []string - for n := range extraMap { - extraNames = append(extraNames, n) - } - f, err := r.OpenFileWithPreReader(file, func(e *TOCEntry, cr io.Reader) error { - t.Logf("On %q: got preread of %q", file, e.Name) - ex, ok := extraMap[e.Name] - if !ok { - t.Fatalf("fail on %q: unexpected entry %q: %+v, %+v", file, e.Name, e, extraNames) - } - got, err := io.ReadAll(cr) - if err != nil { - t.Fatalf("fail on %q: failed to read %q: %v", file, e.Name, err) - } - if ex.data != string(got) { - t.Fatalf("fail on %q: unexpected contents of %q: len=%d; want=%d", file, e.Name, len(got), len(ex.data)) - } - delete(extraMap, e.Name) - return nil - }) - if err != nil { - t.Fatal(err) - } - got := make([]byte, len(want)) - n, err := f.ReadAt(got, int64(offset)) - if err != nil { - t.Fatalf("ReadAt(len %d, offset %d, size %d) = %v, %v", len(got), offset, f.Size(), n, err) - } - if string(got) != want { - t.Fatalf("ReadAt(len %d, offset %d) = %q, want %q", len(got), offset, viewContent(got), viewContent([]byte(want))) - } - if len(extraMap) != 0 { - var exNames []string - for _, ex := range extraMap { - exNames = append(exNames, ex.name) - } - t.Fatalf("fail on %q: some entries aren't read: %+v", file, exNames) - } - }) -} - -func hasFileContentsRange(file string, offset int, want string) stargzCheck { - return stargzCheckFn(func(t *testing.T, r *Reader) { - f, err := r.OpenFile(file) - if err != nil { - t.Fatal(err) - } - got := make([]byte, len(want)) - n, err := f.ReadAt(got, int64(offset)) - if err != nil { - t.Fatalf("ReadAt(len %d, offset %d) = %v, %v", len(got), offset, n, err) - } - if string(got) != want { - t.Fatalf("ReadAt(len %d, offset %d) = %q, want %q", len(got), offset, viewContent(got), viewContent([]byte(want))) - } - }) -} - -func hasChunkEntries(file string, wantChunks int) stargzCheck { - return stargzCheckFn(func(t *testing.T, r *Reader) { - ent, ok := r.Lookup(file) - if !ok { - t.Fatalf("no file for %q", file) - } - if ent.Type != "reg" { - t.Fatalf("file %q has unexpected type %q; want reg", file, ent.Type) - } - chunks := r.getChunks(ent) - if len(chunks) != wantChunks { - t.Errorf("len(r.getChunks(%q)) = %d; want %d", file, len(chunks), wantChunks) - return - } - f := chunks[0] - - var gotChunks []*TOCEntry - var last *TOCEntry - for off := int64(0); off < f.Size; off++ { - e, ok := r.ChunkEntryForOffset(file, off) - if !ok { - t.Errorf("no ChunkEntryForOffset at %d", off) - return - } - if last != e { - gotChunks = append(gotChunks, e) - last = e - } - } - if !reflect.DeepEqual(chunks, gotChunks) { - t.Errorf("gotChunks=%d, want=%d; contents mismatch", len(gotChunks), wantChunks) - } - - // And verify the NextOffset - for i := 0; i < len(gotChunks)-1; i++ { - ci := gotChunks[i] - cnext := gotChunks[i+1] - if ci.NextOffset() != cnext.Offset { - t.Errorf("chunk %d NextOffset %d != next chunk's Offset of %d", i, ci.NextOffset(), cnext.Offset) - } - } - }) -} - -func entryHasChildren(dir string, want ...string) stargzCheck { - return stargzCheckFn(func(t *testing.T, r *Reader) { - want := append([]string(nil), want...) - var got []string - ent, ok := r.Lookup(dir) - if !ok { - t.Fatalf("didn't find TOCEntry for dir node %q", dir) - } - for baseName := range ent.children { - got = append(got, baseName) - } - sort.Strings(got) - sort.Strings(want) - if !reflect.DeepEqual(got, want) { - t.Errorf("children of %q = %q; want %q", dir, got, want) - } - }) -} - -func hasDir(file string) stargzCheck { - return stargzCheckFn(func(t *testing.T, r *Reader) { - for _, ent := range r.toc.Entries { - if ent.Name == cleanEntryName(file) { - if ent.Type != "dir" { - t.Errorf("file type of %q is %q; want \"dir\"", file, ent.Type) - } - return - } - } - t.Errorf("directory %q not found", file) - }) -} - -func hasDirLinkCount(file string, count int) stargzCheck { - return stargzCheckFn(func(t *testing.T, r *Reader) { - for _, ent := range r.toc.Entries { - if ent.Name == cleanEntryName(file) { - if ent.Type != "dir" { - t.Errorf("file type of %q is %q; want \"dir\"", file, ent.Type) - return - } - if ent.NumLink != count { - t.Errorf("link count of %q = %d; want %d", file, ent.NumLink, count) - } - return - } - } - t.Errorf("directory %q not found", file) - }) -} - -func hasMode(file string, mode os.FileMode) stargzCheck { - return stargzCheckFn(func(t *testing.T, r *Reader) { - for _, ent := range r.toc.Entries { - if ent.Name == cleanEntryName(file) { - if ent.Stat().Mode() != mode { - t.Errorf("invalid mode: got %v; want %v", ent.Stat().Mode(), mode) - return - } - return - } - } - t.Errorf("file %q not found", file) - }) -} - -func hasSymlink(file, target string) stargzCheck { - return stargzCheckFn(func(t *testing.T, r *Reader) { - for _, ent := range r.toc.Entries { - if ent.Name == file { - if ent.Type != "symlink" { - t.Errorf("file type of %q is %q; want \"symlink\"", file, ent.Type) - } else if ent.LinkName != target { - t.Errorf("link target of symlink %q is %q; want %q", file, ent.LinkName, target) - } - return - } - } - t.Errorf("symlink %q not found", file) - }) -} - -func lookupMatch(name string, want *TOCEntry) stargzCheck { - return stargzCheckFn(func(t *testing.T, r *Reader) { - e, ok := r.Lookup(name) - if !ok { - t.Fatalf("failed to Lookup entry %q", name) - } - if !reflect.DeepEqual(e, want) { - t.Errorf("entry %q mismatch.\n got: %+v\nwant: %+v\n", name, e, want) - } - - }) -} - -func hasEntryOwner(entry string, owner owner) stargzCheck { - return stargzCheckFn(func(t *testing.T, r *Reader) { - ent, ok := r.Lookup(strings.TrimSuffix(entry, "/")) - if !ok { - t.Errorf("entry %q not found", entry) - return - } - if ent.UID != owner.uid || ent.GID != owner.gid { - t.Errorf("entry %q has invalid owner (uid:%d, gid:%d) instead of (uid:%d, gid:%d)", entry, ent.UID, ent.GID, owner.uid, owner.gid) - return - } - }) -} - -func mustSameEntry(files ...string) stargzCheck { - return stargzCheckFn(func(t *testing.T, r *Reader) { - var first *TOCEntry - for _, f := range files { - if first == nil { - var ok bool - first, ok = r.Lookup(f) - if !ok { - t.Errorf("unknown first file on Lookup: %q", f) - return - } - } - - // Test Lookup - e, ok := r.Lookup(f) - if !ok { - t.Errorf("unknown file on Lookup: %q", f) - return - } - if e != first { - t.Errorf("Lookup: %+v(%p) != %+v(%p)", e, e, first, first) - return - } - - // Test LookupChild - pe, ok := r.Lookup(filepath.Dir(filepath.Clean(f))) - if !ok { - t.Errorf("failed to get parent of %q", f) - return - } - e, ok = pe.LookupChild(filepath.Base(filepath.Clean(f))) - if !ok { - t.Errorf("failed to get %q as the child of %+v", f, pe) - return - } - if e != first { - t.Errorf("LookupChild: %+v(%p) != %+v(%p)", e, e, first, first) - return - } - - // Test ForeachChild - pe.ForeachChild(func(baseName string, e *TOCEntry) bool { - if baseName == filepath.Base(filepath.Clean(f)) { - if e != first { - t.Errorf("ForeachChild: %+v(%p) != %+v(%p)", e, e, first, first) - return false - } - } - return true - }) - } - }) -} - -func viewContent(c []byte) string { - if len(c) < 100 { - return string(c) - } - return string(c[:50]) + "...(omit)..." + string(c[50:100]) -} - -func tarOf(s ...tarEntry) []tarEntry { return s } - -type tarEntry interface { - appendTar(tw *tar.Writer, prefix string, format tar.Format) error -} - -type tarEntryFunc func(*tar.Writer, string, tar.Format) error - -func (f tarEntryFunc) appendTar(tw *tar.Writer, prefix string, format tar.Format) error { - return f(tw, prefix, format) -} - -func buildTar(t *testing.T, ents []tarEntry, prefix string, opts ...interface{}) *io.SectionReader { - format := tar.FormatUnknown - for _, opt := range opts { - switch v := opt.(type) { - case tar.Format: - format = v - default: - panic(fmt.Errorf("unsupported opt for buildTar: %v", opt)) - } - } - buf := new(bytes.Buffer) - tw := tar.NewWriter(buf) - for _, ent := range ents { - if err := ent.appendTar(tw, prefix, format); err != nil { - t.Fatalf("building input tar: %v", err) - } - } - if err := tw.Close(); err != nil { - t.Errorf("closing write of input tar: %v", err) - } - data := append(buf.Bytes(), make([]byte, 100)...) // append empty bytes at the tail to see lossless works - return io.NewSectionReader(bytes.NewReader(data), 0, int64(len(data))) -} - -func dir(name string, opts ...interface{}) tarEntry { - return tarEntryFunc(func(tw *tar.Writer, prefix string, format tar.Format) error { - var o owner - mode := os.FileMode(0755) - for _, opt := range opts { - switch v := opt.(type) { - case owner: - o = v - case os.FileMode: - mode = v - default: - return errors.New("unsupported opt") - } - } - if !strings.HasSuffix(name, "/") { - panic(fmt.Sprintf("missing trailing slash in dir %q ", name)) - } - tm, err := fileModeToTarMode(mode) - if err != nil { - return err - } - return tw.WriteHeader(&tar.Header{ - Typeflag: tar.TypeDir, - Name: prefix + name, - Mode: tm, - Uid: o.uid, - Gid: o.gid, - Format: format, - }) - }) -} - -// xAttr are extended attributes to set on test files created with the file func. -type xAttr map[string]string - -// owner is owner ot set on test files and directories with the file and dir functions. -type owner struct { - uid int - gid int -} - -func file(name, contents string, opts ...interface{}) tarEntry { - return tarEntryFunc(func(tw *tar.Writer, prefix string, format tar.Format) error { - var xattrs xAttr - var o owner - mode := os.FileMode(0644) - for _, opt := range opts { - switch v := opt.(type) { - case xAttr: - xattrs = v - case owner: - o = v - case os.FileMode: - mode = v - default: - return errors.New("unsupported opt") - } - } - if strings.HasSuffix(name, "/") { - return fmt.Errorf("bogus trailing slash in file %q", name) - } - tm, err := fileModeToTarMode(mode) - if err != nil { - return err - } - if len(xattrs) > 0 { - format = tar.FormatPAX // only PAX supports xattrs - } - if err := tw.WriteHeader(&tar.Header{ - Typeflag: tar.TypeReg, - Name: prefix + name, - Mode: tm, - Xattrs: xattrs, - Size: int64(len(contents)), - Uid: o.uid, - Gid: o.gid, - Format: format, - }); err != nil { - return err - } - _, err = io.WriteString(tw, contents) - return err - }) -} - -func symlink(name, target string) tarEntry { - return tarEntryFunc(func(tw *tar.Writer, prefix string, format tar.Format) error { - return tw.WriteHeader(&tar.Header{ - Typeflag: tar.TypeSymlink, - Name: prefix + name, - Linkname: target, - Mode: 0644, - Format: format, - }) - }) -} - -func link(name string, linkname string) tarEntry { - now := time.Now() - return tarEntryFunc(func(w *tar.Writer, prefix string, format tar.Format) error { - return w.WriteHeader(&tar.Header{ - Typeflag: tar.TypeLink, - Name: prefix + name, - Linkname: linkname, - ModTime: now, - Format: format, - }) - }) -} - -func chardev(name string, major, minor int64) tarEntry { - now := time.Now() - return tarEntryFunc(func(w *tar.Writer, prefix string, format tar.Format) error { - return w.WriteHeader(&tar.Header{ - Typeflag: tar.TypeChar, - Name: prefix + name, - Devmajor: major, - Devminor: minor, - ModTime: now, - Format: format, - }) - }) -} - -func blockdev(name string, major, minor int64) tarEntry { - now := time.Now() - return tarEntryFunc(func(w *tar.Writer, prefix string, format tar.Format) error { - return w.WriteHeader(&tar.Header{ - Typeflag: tar.TypeBlock, - Name: prefix + name, - Devmajor: major, - Devminor: minor, - ModTime: now, - Format: format, - }) - }) -} -func fifo(name string) tarEntry { - now := time.Now() - return tarEntryFunc(func(w *tar.Writer, prefix string, format tar.Format) error { - return w.WriteHeader(&tar.Header{ - Typeflag: tar.TypeFifo, - Name: prefix + name, - ModTime: now, - Format: format, - }) - }) -} - -func prefetchLandmark() tarEntry { - return tarEntryFunc(func(w *tar.Writer, prefix string, format tar.Format) error { - if err := w.WriteHeader(&tar.Header{ - Name: PrefetchLandmark, - Typeflag: tar.TypeReg, - Size: int64(len([]byte{landmarkContents})), - Format: format, - }); err != nil { - return err - } - contents := []byte{landmarkContents} - if _, err := io.CopyN(w, bytes.NewReader(contents), int64(len(contents))); err != nil { - return err - } - return nil - }) -} - -func noPrefetchLandmark() tarEntry { - return tarEntryFunc(func(w *tar.Writer, prefix string, format tar.Format) error { - if err := w.WriteHeader(&tar.Header{ - Name: NoPrefetchLandmark, - Typeflag: tar.TypeReg, - Size: int64(len([]byte{landmarkContents})), - Format: format, - }); err != nil { - return err - } - contents := []byte{landmarkContents} - if _, err := io.CopyN(w, bytes.NewReader(contents), int64(len(contents))); err != nil { - return err - } - return nil - }) -} - -func regDigest(t *testing.T, name string, contentStr string, digestMap map[string]digest.Digest) tarEntry { - if digestMap == nil { - t.Fatalf("digest map mustn't be nil") - } - content := []byte(contentStr) - - var n int64 - for n < int64(len(content)) { - size := int64(chunkSize) - remain := int64(len(content)) - n - if remain < size { - size = remain - } - dgstr := digest.Canonical.Digester() - if _, err := io.CopyN(dgstr.Hash(), bytes.NewReader(content[n:n+size]), size); err != nil { - t.Fatalf("failed to calculate digest of %q (name=%q,offset=%d,size=%d)", - string(content[n:n+size]), name, n, size) - } - digestMap[chunkID(name, n, size)] = dgstr.Digest() - n += size - } - - return tarEntryFunc(func(w *tar.Writer, prefix string, format tar.Format) error { - if err := w.WriteHeader(&tar.Header{ - Typeflag: tar.TypeReg, - Name: prefix + name, - Size: int64(len(content)), - Format: format, - }); err != nil { - return err - } - if _, err := io.CopyN(w, bytes.NewReader(content), int64(len(content))); err != nil { - return err - } - return nil - }) -} - -var runes = []rune("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") - -func randomContents(n int) string { - b := make([]rune, n) - for i := range b { - b[i] = runes[rand.Intn(len(runes))] - } - return string(b) -} - -func fileModeToTarMode(mode os.FileMode) (int64, error) { - h, err := tar.FileInfoHeader(fileInfoOnlyMode(mode), "") - if err != nil { - return 0, err - } - return h.Mode, nil -} - -// fileInfoOnlyMode is os.FileMode that populates only file mode. -type fileInfoOnlyMode os.FileMode - -func (f fileInfoOnlyMode) Name() string { return "" } -func (f fileInfoOnlyMode) Size() int64 { return 0 } -func (f fileInfoOnlyMode) Mode() os.FileMode { return os.FileMode(f) } -func (f fileInfoOnlyMode) ModTime() time.Time { return time.Now() } -func (f fileInfoOnlyMode) IsDir() bool { return os.FileMode(f).IsDir() } -func (f fileInfoOnlyMode) Sys() interface{} { return nil } - -func CheckGzipHasStreams(t *testing.T, b []byte, streams []int64) { - if len(streams) == 0 { - return // nop - } - - wants := map[int64]struct{}{} - for _, s := range streams { - wants[s] = struct{}{} - } - - len0 := len(b) - br := bytes.NewReader(b) - zr := new(gzip.Reader) - t.Logf("got gzip streams:") - numStreams := 0 - for { - zoff := len0 - br.Len() - if err := zr.Reset(br); err != nil { - if err == io.EOF { - return - } - t.Fatalf("countStreams(gzip), Reset: %v", err) - } - zr.Multistream(false) - n, err := io.Copy(io.Discard, zr) - if err != nil { - t.Fatalf("countStreams(gzip), Copy: %v", err) - } - var extra string - if len(zr.Header.Extra) > 0 { - extra = fmt.Sprintf("; extra=%q", zr.Header.Extra) - } - t.Logf(" [%d] at %d in stargz, uncompressed length %d%s", numStreams, zoff, n, extra) - delete(wants, int64(zoff)) - numStreams++ - } -} - -func GzipDiffIDOf(t *testing.T, b []byte) string { - h := sha256.New() - zr, err := gzip.NewReader(bytes.NewReader(b)) - if err != nil { - t.Fatalf("diffIDOf(gzip): %v", err) - } - defer zr.Close() - if _, err := io.Copy(h, zr); err != nil { - t.Fatalf("diffIDOf(gzip).Copy: %v", err) - } - return fmt.Sprintf("sha256:%x", h.Sum(nil)) -} diff --git a/vendor/github.com/containerd/stargz-snapshotter/estargz/types.go b/vendor/github.com/containerd/stargz-snapshotter/estargz/types.go deleted file mode 100644 index 57e0aa614..000000000 --- a/vendor/github.com/containerd/stargz-snapshotter/estargz/types.go +++ /dev/null @@ -1,342 +0,0 @@ -/* - Copyright The containerd 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. -*/ - -/* - Copyright 2019 The Go Authors. All rights reserved. - Use of this source code is governed by a BSD-style - license that can be found in the LICENSE file. -*/ - -package estargz - -import ( - "archive/tar" - "hash" - "io" - "os" - "path" - "time" - - digest "github.com/opencontainers/go-digest" -) - -const ( - // TOCTarName is the name of the JSON file in the tar archive in the - // table of contents gzip stream. - TOCTarName = "stargz.index.json" - - // FooterSize is the number of bytes in the footer - // - // The footer is an empty gzip stream with no compression and an Extra - // header of the form "%016xSTARGZ", where the 64 bit hex-encoded - // number is the offset to the gzip stream of JSON TOC. - // - // 51 comes from: - // - // 10 bytes gzip header - // 2 bytes XLEN (length of Extra field) = 26 (4 bytes header + 16 hex digits + len("STARGZ")) - // 2 bytes Extra: SI1 = 'S', SI2 = 'G' - // 2 bytes Extra: LEN = 22 (16 hex digits + len("STARGZ")) - // 22 bytes Extra: subfield = fmt.Sprintf("%016xSTARGZ", offsetOfTOC) - // 5 bytes flate header - // 8 bytes gzip footer - // (End of the eStargz blob) - // - // NOTE: For Extra fields, subfield IDs SI1='S' SI2='G' is used for eStargz. - FooterSize = 51 - - // legacyFooterSize is the number of bytes in the legacy stargz footer. - // - // 47 comes from: - // - // 10 byte gzip header + - // 2 byte (LE16) length of extra, encoding 22 (16 hex digits + len("STARGZ")) == "\x16\x00" + - // 22 bytes of extra (fmt.Sprintf("%016xSTARGZ", tocGzipOffset)) - // 5 byte flate header - // 8 byte gzip footer (two little endian uint32s: digest, size) - legacyFooterSize = 47 - - // TOCJSONDigestAnnotation is an annotation for an image layer. This stores the - // digest of the TOC JSON. - // This annotation is valid only when it is specified in `.[]layers.annotations` - // of an image manifest. - TOCJSONDigestAnnotation = "containerd.io/snapshot/stargz/toc.digest" - - // StoreUncompressedSizeAnnotation is an additional annotation key for eStargz to enable lazy - // pulling on containers/storage. Stargz Store is required to expose the layer's uncompressed size - // to the runtime but current OCI image doesn't ship this information by default. So we store this - // to the special annotation. - StoreUncompressedSizeAnnotation = "io.containers.estargz.uncompressed-size" - - // PrefetchLandmark is a file entry which indicates the end position of - // prefetch in the stargz file. - PrefetchLandmark = ".prefetch.landmark" - - // NoPrefetchLandmark is a file entry which indicates that no prefetch should - // occur in the stargz file. - NoPrefetchLandmark = ".no.prefetch.landmark" - - landmarkContents = 0xf -) - -// JTOC is the JSON-serialized table of contents index of the files in the stargz file. -type JTOC struct { - Version int `json:"version"` - Entries []*TOCEntry `json:"entries"` -} - -// TOCEntry is an entry in the stargz file's TOC (Table of Contents). -type TOCEntry struct { - // Name is the tar entry's name. It is the complete path - // stored in the tar file, not just the base name. - Name string `json:"name"` - - // Type is one of "dir", "reg", "symlink", "hardlink", "char", - // "block", "fifo", or "chunk". - // The "chunk" type is used for regular file data chunks past the first - // TOCEntry; the 2nd chunk and on have only Type ("chunk"), Offset, - // ChunkOffset, and ChunkSize populated. - Type string `json:"type"` - - // Size, for regular files, is the logical size of the file. - Size int64 `json:"size,omitempty"` - - // ModTime3339 is the modification time of the tar entry. Empty - // means zero or unknown. Otherwise it's in UTC RFC3339 - // format. Use the ModTime method to access the time.Time value. - ModTime3339 string `json:"modtime,omitempty"` - modTime time.Time - - // LinkName, for symlinks and hardlinks, is the link target. - LinkName string `json:"linkName,omitempty"` - - // Mode is the permission and mode bits. - Mode int64 `json:"mode,omitempty"` - - // UID is the user ID of the owner. - UID int `json:"uid,omitempty"` - - // GID is the group ID of the owner. - GID int `json:"gid,omitempty"` - - // Uname is the username of the owner. - // - // In the serialized JSON, this field may only be present for - // the first entry with the same UID. - Uname string `json:"userName,omitempty"` - - // Gname is the group name of the owner. - // - // In the serialized JSON, this field may only be present for - // the first entry with the same GID. - Gname string `json:"groupName,omitempty"` - - // Offset, for regular files, provides the offset in the - // stargz file to the file's data bytes. See ChunkOffset and - // ChunkSize. - Offset int64 `json:"offset,omitempty"` - - // InnerOffset is an optional field indicates uncompressed offset - // of this "reg" or "chunk" payload in a stream starts from Offset. - // This field enables to put multiple "reg" or "chunk" payloads - // in one chunk with having the same Offset but different InnerOffset. - InnerOffset int64 `json:"innerOffset,omitempty"` - - nextOffset int64 // the Offset of the next entry with a non-zero Offset - - // DevMajor is the major device number for "char" and "block" types. - DevMajor int `json:"devMajor,omitempty"` - - // DevMinor is the major device number for "char" and "block" types. - DevMinor int `json:"devMinor,omitempty"` - - // NumLink is the number of entry names pointing to this entry. - // Zero means one name references this entry. - // This field is calculated during runtime and not recorded in TOC JSON. - NumLink int `json:"-"` - - // Xattrs are the extended attribute for the entry. - Xattrs map[string][]byte `json:"xattrs,omitempty"` - - // Digest stores the OCI checksum for regular files payload. - // It has the form "sha256:abcdef01234....". - Digest string `json:"digest,omitempty"` - - // ChunkOffset is non-zero if this is a chunk of a large, - // regular file. If so, the Offset is where the gzip header of - // ChunkSize bytes at ChunkOffset in Name begin. - // - // In serialized form, a "chunkSize" JSON field of zero means - // that the chunk goes to the end of the file. After reading - // from the stargz TOC, though, the ChunkSize is initialized - // to a non-zero file for when Type is either "reg" or - // "chunk". - ChunkOffset int64 `json:"chunkOffset,omitempty"` - ChunkSize int64 `json:"chunkSize,omitempty"` - - // ChunkDigest stores an OCI digest of the chunk. This must be formed - // as "sha256:0123abcd...". - ChunkDigest string `json:"chunkDigest,omitempty"` - - children map[string]*TOCEntry - - // chunkTopIndex is index of the entry where Offset starts in the blob. - chunkTopIndex int -} - -// ModTime returns the entry's modification time. -func (e *TOCEntry) ModTime() time.Time { return e.modTime } - -// NextOffset returns the position (relative to the start of the -// stargz file) of the next gzip boundary after e.Offset. -func (e *TOCEntry) NextOffset() int64 { return e.nextOffset } - -func (e *TOCEntry) addChild(baseName string, child *TOCEntry) { - if e.children == nil { - e.children = make(map[string]*TOCEntry) - } - if child.Type == "dir" { - e.NumLink++ // Entry ".." in the subdirectory links to this directory - } - e.children[baseName] = child -} - -// isDataType reports whether TOCEntry is a regular file or chunk (something that -// contains regular file data). -func (e *TOCEntry) isDataType() bool { return e.Type == "reg" || e.Type == "chunk" } - -// Stat returns a FileInfo value representing e. -func (e *TOCEntry) Stat() os.FileInfo { return fileInfo{e} } - -// ForeachChild calls f for each child item. If f returns false, iteration ends. -// If e is not a directory, f is not called. -func (e *TOCEntry) ForeachChild(f func(baseName string, ent *TOCEntry) bool) { - for name, ent := range e.children { - if !f(name, ent) { - return - } - } -} - -// LookupChild returns the directory e's child by its base name. -func (e *TOCEntry) LookupChild(baseName string) (child *TOCEntry, ok bool) { - child, ok = e.children[baseName] - return -} - -// fileInfo implements os.FileInfo using the wrapped *TOCEntry. -type fileInfo struct{ e *TOCEntry } - -var _ os.FileInfo = fileInfo{} - -func (fi fileInfo) Name() string { return path.Base(fi.e.Name) } -func (fi fileInfo) IsDir() bool { return fi.e.Type == "dir" } -func (fi fileInfo) Size() int64 { return fi.e.Size } -func (fi fileInfo) ModTime() time.Time { return fi.e.ModTime() } -func (fi fileInfo) Sys() interface{} { return fi.e } -func (fi fileInfo) Mode() (m os.FileMode) { - // TOCEntry.Mode is tar.Header.Mode so we can understand the these bits using `tar` pkg. - m = (&tar.Header{Mode: fi.e.Mode}).FileInfo().Mode() & - (os.ModePerm | os.ModeSetuid | os.ModeSetgid | os.ModeSticky) - switch fi.e.Type { - case "dir": - m |= os.ModeDir - case "symlink": - m |= os.ModeSymlink - case "char": - m |= os.ModeDevice | os.ModeCharDevice - case "block": - m |= os.ModeDevice - case "fifo": - m |= os.ModeNamedPipe - } - return m -} - -// TOCEntryVerifier holds verifiers that are usable for verifying chunks contained -// in a eStargz blob. -type TOCEntryVerifier interface { - - // Verifier provides a content verifier that can be used for verifying the - // contents of the specified TOCEntry. - Verifier(ce *TOCEntry) (digest.Verifier, error) -} - -// Compression provides the compression helper to be used creating and parsing eStargz. -// This package provides gzip-based Compression by default, but any compression -// algorithm (e.g. zstd) can be used as long as it implements Compression. -type Compression interface { - Compressor - Decompressor -} - -// Compressor represents the helper mothods to be used for creating eStargz. -type Compressor interface { - // Writer returns WriteCloser to be used for writing a chunk to eStargz. - // Everytime a chunk is written, the WriteCloser is closed and Writer is - // called again for writing the next chunk. - // - // The returned writer should implement "Flush() error" function that flushes - // any pending compressed data to the underlying writer. - Writer(w io.Writer) (WriteFlushCloser, error) - - // WriteTOCAndFooter is called to write JTOC to the passed Writer. - // diffHash calculates the DiffID (uncompressed sha256 hash) of the blob - // WriteTOCAndFooter can optionally write anything that affects DiffID calculation - // (e.g. uncompressed TOC JSON). - // - // This function returns tocDgst that represents the digest of TOC that will be used - // to verify this blob when it's parsed. - WriteTOCAndFooter(w io.Writer, off int64, toc *JTOC, diffHash hash.Hash) (tocDgst digest.Digest, err error) -} - -// Decompressor represents the helper mothods to be used for parsing eStargz. -type Decompressor interface { - // Reader returns ReadCloser to be used for decompressing file payload. - Reader(r io.Reader) (io.ReadCloser, error) - - // FooterSize returns the size of the footer of this blob. - FooterSize() int64 - - // ParseFooter parses the footer and returns the offset and (compressed) size of TOC. - // payloadBlobSize is the (compressed) size of the blob payload (i.e. the size between - // the top until the TOC JSON). - // - // If tocOffset < 0, we assume that TOC isn't contained in the blob and pass nil reader - // to ParseTOC. We expect that ParseTOC acquire TOC from the external location and return it. - // - // tocSize is optional. If tocSize <= 0, it's by default the size of the range from tocOffset until the beginning of the - // footer (blob size - tocOff - FooterSize). - // If blobPayloadSize < 0, blobPayloadSize become the blob size. - ParseFooter(p []byte) (blobPayloadSize, tocOffset, tocSize int64, err error) - - // ParseTOC parses TOC from the passed reader. The reader provides the partial contents - // of the underlying blob that has the range specified by ParseFooter method. - // - // This function returns tocDgst that represents the digest of TOC that will be used - // to verify this blob. This must match to the value returned from - // Compressor.WriteTOCAndFooter that is used when creating this blob. - // - // If tocOffset returned by ParseFooter is < 0, we assume that TOC isn't contained in the blob. - // Pass nil reader to ParseTOC then we expect that ParseTOC acquire TOC from the external location - // and return it. - ParseTOC(r io.Reader) (toc *JTOC, tocDgst digest.Digest, err error) -} - -type WriteFlushCloser interface { - io.WriteCloser - Flush() error -} diff --git a/vendor/github.com/docker/cli/AUTHORS b/vendor/github.com/docker/cli/AUTHORS deleted file mode 100644 index 483743c99..000000000 --- a/vendor/github.com/docker/cli/AUTHORS +++ /dev/null @@ -1,852 +0,0 @@ -# File @generated by scripts/docs/generate-authors.sh. DO NOT EDIT. -# This file lists all contributors to the repository. -# See scripts/docs/generate-authors.sh to make modifications. - -Aanand Prasad -Aaron L. Xu -Aaron Lehmann -Aaron.L.Xu -Abdur Rehman -Abhinandan Prativadi -Abin Shahab -Abreto FU -Ace Tang -Addam Hardy -Adolfo Ochagavía -Adrian Plata -Adrien Duermael -Adrien Folie -Ahmet Alp Balkan -Aidan Feldman -Aidan Hobson Sayers -AJ Bowen -Akhil Mohan -Akihiro Suda -Akim Demaille -Alan Thompson -Albert Callarisa -Alberto Roura -Albin Kerouanton -Aleksa Sarai -Aleksander Piotrowski -Alessandro Boch -Alex Couture-Beil -Alex Mavrogiannis -Alex Mayer -Alexander Boyd -Alexander Larsson -Alexander Morozov -Alexander Ryabov -Alexandre González -Alexey Igrychev -Alexis Couvreur -Alfred Landrum -Alicia Lauerman -Allen Sun -Alvin Deng -Amen Belayneh -Amey Shrivastava <72866602+AmeyShrivastava@users.noreply.github.com> -Amir Goldstein -Amit Krishnan -Amit Shukla -Amy Lindburg -Anca Iordache -Anda Xu -Andrea Luzzardi -Andreas Köhler -Andres G. Aragoneses -Andres Leon Rangel -Andrew France -Andrew Hsu -Andrew Macpherson -Andrew McDonnell -Andrew Po -Andrey Petrov -Andrii Berehuliak -André Martins -Andy Goldstein -Andy Rothfusz -Anil Madhavapeddy -Ankush Agarwal -Anne Henmi -Anton Polonskiy -Antonio Murdaca -Antonis Kalipetis -Anusha Ragunathan -Ao Li -Arash Deshmeh -Arko Dasgupta -Arnaud Porterie -Arnaud Rebillout -Arthur Peka -Ashwini Oruganti -Azat Khuyiyakhmetov -Bardia Keyoumarsi -Barnaby Gray -Bastiaan Bakker -BastianHofmann -Ben Bodenmiller -Ben Bonnefoy -Ben Creasy -Ben Firshman -Benjamin Boudreau -Benjamin Böhmke -Benjamin Nater -Benoit Sigoure -Bhumika Bayani -Bill Wang -Bin Liu -Bingshen Wang -Bishal Das -Boaz Shuster -Bogdan Anton -Boris Pruessmann -Brad Baker -Bradley Cicenas -Brandon Mitchell -Brandon Philips -Brent Salisbury -Bret Fisher -Brian (bex) Exelbierd -Brian Goff -Brian Wieder -Bruno Sousa -Bryan Bess -Bryan Boreham -Bryan Murphy -bryfry -Cameron Spear -Cao Weiwei -Carlo Mion -Carlos Alexandro Becker -Carlos de Paula -Ce Gao -Cedric Davies -Cezar Sa Espinola -Chad Faragher -Chao Wang -Charles Chan -Charles Law -Charles Smith -Charlie Drage -Charlotte Mach -ChaYoung You -Chee Hau Lim -Chen Chuanliang -Chen Hanxiao -Chen Mingjie -Chen Qiu -Chris Couzens -Chris Gavin -Chris Gibson -Chris McKinnel -Chris Snow -Chris Vermilion -Chris Weyl -Christian Persson -Christian Stefanescu -Christophe Robin -Christophe Vidal -Christopher Biscardi -Christopher Crone -Christopher Jones -Christopher Svensson -Christy Norman -Chun Chen -Clinton Kitson -Coenraad Loubser -Colin Hebert -Collin Guarino -Colm Hally -Comical Derskeal <27731088+derskeal@users.noreply.github.com> -Conner Crosby -Corey Farrell -Corey Quon -Cory Bennet -Craig Wilhite -Cristian Staretu -Daehyeok Mun -Dafydd Crosby -Daisuke Ito -dalanlan -Damien Nadé -Dan Cotora -Daniel Artine -Daniel Cassidy -Daniel Dao -Daniel Farrell -Daniel Gasienica -Daniel Goosen -Daniel Helfand -Daniel Hiltgen -Daniel J Walsh -Daniel Nephin -Daniel Norberg -Daniel Watkins -Daniel Zhang -Daniil Nikolenko -Danny Berger -Darren Shepherd -Darren Stahl -Dattatraya Kumbhar -Dave Goodchild -Dave Henderson -Dave Tucker -David Alvarez -David Beitey -David Calavera -David Cramer -David Dooling -David Gageot -David Karlsson -David Lechner -David Scott -David Sheets -David Williamson -David Xia -David Young -Deng Guangxing -Denis Defreyne -Denis Gladkikh -Denis Ollier -Dennis Docter -Derek McGowan -Des Preston -Deshi Xiao -Dharmit Shah -Dhawal Yogesh Bhanushali -Dieter Reuter -Dima Stopel -Dimitry Andric -Ding Fei -Diogo Monica -Djordje Lukic -Dmitriy Fishman -Dmitry Gusev -Dmitry Smirnov -Dmitry V. Krivenok -Dominik Braun -Don Kjer -Dong Chen -DongGeon Lee -Doug Davis -Drew Erny -Ed Costello -Elango Sivanandam -Eli Uriegas -Eli Uriegas -Elias Faxö -Elliot Luo <956941328@qq.com> -Eric Curtin -Eric Engestrom -Eric G. Noriega -Eric Rosenberg -Eric Sage -Eric-Olivier Lamey -Erica Windisch -Erik Hollensbe -Erik Humphrey -Erik St. Martin -Essam A. Hassan -Ethan Haynes -Euan Kemp -Eugene Yakubovich -Evan Allrich -Evan Hazlett -Evan Krall -Evelyn Xu -Everett Toews -Fabio Falci -Fabrizio Soppelsa -Felix Geyer -Felix Hupfeld -Felix Rabe -fezzik1620 -Filip Jareš -Flavio Crisciani -Florian Klein -Forest Johnson -Foysal Iqbal -François Scala -Fred Lifton -Frederic Hemberger -Frederick F. Kautz IV -Frederik Nordahl Jul Sabroe -Frieder Bluemle -Gabriel Gore -Gabriel Nicolas Avellaneda -Gaetan de Villele -Gang Qiao -Gary Schaetz -Genki Takiuchi -George MacRorie -George Xie -Gianluca Borello -Gildas Cuisinier -Gio d'Amelio -Gleb Stsenov -Goksu Toprak -Gou Rao -Govind Rai -Grant Reaber -Greg Pflaum -Gsealy -Guilhem Lettron -Guillaume J. Charmes -Guillaume Le Floch -Guillaume Tardif -gwx296173 -Günther Jungbluth -Hakan Özler -Hao Zhang <21521210@zju.edu.cn> -Harald Albers -Harold Cooper -Harry Zhang -He Simei -Hector S -Helen Xie -Henning Sprang -Henry N -Hernan Garcia -Hongbin Lu -Hu Keping -Huayi Zhang -Hugo Gabriel Eyherabide -huqun -Huu Nguyen -Hyzhou Zhy -Iain Samuel McLean Elder -Ian Campbell -Ian Philpot -Ignacio Capurro -Ilya Dmitrichenko -Ilya Khlopotov -Ilya Sotkov -Ioan Eugen Stan -Isabel Jimenez -Ivan Grcic -Ivan Grund -Ivan Markin -Jacob Atzen -Jacob Tomlinson -Jaivish Kothari -Jake Lambert -Jake Sanders -James Nesbitt -James Turnbull -Jamie Hannaford -Jan Koprowski -Jan Pazdziora -Jan-Jaap Driessen -Jana Radhakrishnan -Jared Hocutt -Jasmine Hegman -Jason Hall -Jason Heiss -Jason Plum -Jay Kamat -Jean Lecordier -Jean Rouge -Jean-Christophe Sirot -Jean-Pierre Huynh -Jeff Lindsay -Jeff Nickoloff -Jeff Silberman -Jennings Zhang -Jeremy Chambers -Jeremy Unruh -Jeremy Yallop -Jeroen Franse -Jesse Adametz -Jessica Frazelle -Jezeniel Zapanta -Jian Zhang -Jie Luo -Jilles Oldenbeuving -Jim Galasyn -Jim Lin -Jimmy Leger -Jimmy Song -jimmyxian -Jintao Zhang -Joao Fernandes -Joe Abbey -Joe Doliner -Joe Gordon -Joel Handwell -Joey Geiger -Joffrey F -Johan Euphrosine -Johannes 'fish' Ziemke -John Feminella -John Harris -John Howard -John Howard -John Laswell -John Maguire -John Mulhausen -John Starks -John Stephens -John Tims -John V. Martinez -John Willis -Jon Johnson -Jon Zeolla -Jonatas Baldin -Jonathan Boulle -Jonathan Lee -Jonathan Lomas -Jonathan McCrohan -Jonathan Warriss-Simmons -Jonh Wendell -Jordan Jennings -Jorge Vallecillo -Jose J. Escobar <53836904+jescobar-docker@users.noreply.github.com> -Joseph Kern -Josh Bodah -Josh Chorlton -Josh Hawn -Josh Horwitz -Josh Soref -Julien Barbier -Julien Kassar -Julien Maitrehenry -Justas Brazauskas -Justin Cormack -Justin Simonelis -Justyn Temme -Jyrki Puttonen -Jérémie Drouet -Jérôme Petazzoni -Jörg Thalheim -Kai Blin -Kai Qiang Wu (Kennan) -Kara Alexandra -Kareem Khazem -Karthik Nayak -Kat Samperi -Kathryn Spiers -Katie McLaughlin -Ke Xu -Kei Ohmura -Keith Hudgins -Kelton Bassingthwaite -Ken Cochrane -Ken ICHIKAWA -Kenfe-Mickaël Laventure -Kevin Alvarez -Kevin Burke -Kevin Feyrer -Kevin Kern -Kevin Kirsche -Kevin Meredith -Kevin Richardson -Kevin Woblick -khaled souf -Kim Eik -Kir Kolyshkin -Kotaro Yoshimatsu -Krasi Georgiev -Kris-Mikael Krister -Kun Zhang -Kunal Kushwaha -Kyle Mitofsky -Lachlan Cooper -Lai Jiangshan -Lars Kellogg-Stedman -Laura Frank -Laurent Erignoux -Lee Gaines -Lei Jitang -Lennie -Leo Gallucci -Leonid Skorospelov -Lewis Daly -Li Yi -Li Yi -Liang-Chi Hsieh -Lifubang -Lihua Tang -Lily Guo -Lin Lu -Linus Heckemann -Liping Xue -Liron Levin -liwenqi -lixiaobing10051267 -Lloyd Dewolf -Lorenzo Fontana -Louis Opter -Luca Favatella -Luca Marturana -Lucas Chan -Luka Hartwig -Lukas Heeren -Lukasz Zajaczkowski -Lydell Manganti -Lénaïc Huard -Ma Shimiao -Mabin -Maciej Kalisz -Madhav Puri -Madhu Venugopal -Madhur Batra -Malte Janduda -Manjunath A Kumatagi -Mansi Nahar -mapk0y -Marc Bihlmaier -Marc Cornellà -Marco Mariani -Marco Vedovati -Marcus Martins -Marianna Tessel -Marius Ileana -Marius Sturm -Mark Oates -Marsh Macy -Martin Mosegaard Amdisen -Mary Anthony -Mason Fish -Mason Malone -Mateusz Major -Mathieu Champlon -Mathieu Rollet -Matt Gucci -Matt Robenolt -Matteo Orefice -Matthew Heon -Matthieu Hauglustaine -Mauro Porras P -Max Shytikov -Maxime Petazzoni -Maximillian Fan Xavier -Mei ChunTao -Metal <2466052+tedhexaflow@users.noreply.github.com> -Micah Zoltu -Michael A. Smith -Michael Bridgen -Michael Crosby -Michael Friis -Michael Irwin -Michael Käufl -Michael Prokop -Michael Scharf -Michael Spetsiotis -Michael Steinert -Michael West -Michal Minář -Michał Czeraszkiewicz -Miguel Angel Alvarez Cabrerizo -Mihai Borobocea -Mihuleacc Sergiu -Mike Brown -Mike Casas -Mike Dalton -Mike Danese -Mike Dillon -Mike Goelzer -Mike MacCana -mikelinjie <294893458@qq.com> -Mikhail Vasin -Milind Chawre -Mindaugas Rukas -Miroslav Gula -Misty Stanley-Jones -Mohammad Banikazemi -Mohammed Aaqib Ansari -Mohini Anne Dsouza -Moorthy RS -Morgan Bauer -Morten Hekkvang -Morten Linderud -Moysés Borges -Mozi <29089388+pzhlkj6612@users.noreply.github.com> -Mrunal Patel -muicoder -Murukesh Mohanan -Muthukumar R -Máximo Cuadros -Mårten Cassel -Nace Oroz -Nahum Shalman -Nalin Dahyabhai -Nao YONASHIRO -Nassim 'Nass' Eddequiouaq -Natalie Parker -Nate Brennand -Nathan Hsieh -Nathan LeClaire -Nathan McCauley -Neil Peterson -Nick Adcock -Nick Santos -Nico Stapelbroek -Nicola Kabar -Nicolas Borboën -Nicolas De Loof -Nikhil Chawla -Nikolas Garofil -Nikolay Milovanov -Nir Soffer -Nishant Totla -NIWA Hideyuki -Noah Treuhaft -O.S. Tezer -Odin Ugedal -ohmystack -OKA Naoya -Oliver Pomeroy -Olle Jonsson -Olli Janatuinen -Oscar Wieman -Otto Kekäläinen -Ovidio Mallo -Pascal Borreli -Patrick Böänziger -Patrick Hemmer -Patrick Lang -Paul -Paul Kehrer -Paul Lietar -Paul Mulders -Paul Weaver -Pavel Pospisil -Paweł Gronowski -Paweł Pokrywka -Paweł Szczekutowicz -Peeyush Gupta -Per Lundberg -Peter Dave Hello -Peter Edge -Peter Hsu -Peter Jaffe -Peter Kehl -Peter Nagy -Peter Salvatore -Peter Waller -Phil Estes -Philip Alexander Etling -Philipp Gillé -Philipp Schmied -Phong Tran -pidster -Pieter E Smit -pixelistik -Pratik Karki -Prayag Verma -Preston Cowley -Pure White -Qiang Huang -Qinglan Peng -qudongfang -Raghavendra K T -Rahul Kadyan -Rahul Zoldyck -Ravi Shekhar Jethani -Ray Tsang -Reficul -Remy Suen -Renaud Gaubert -Ricardo N Feliciano -Rich Moyse -Richard Chen Zheng <58443436+rchenzheng@users.noreply.github.com> -Richard Mathie -Richard Scothern -Rick Wieman -Ritesh H Shukla -Riyaz Faizullabhoy -Rob Gulewich -Robert Wallis -Robin Naundorf -Robin Speekenbrink -Roch Feuillade -Rodolfo Ortiz -Rogelio Canedo -Rohan Verma -Roland Kammerer -Roman Dudin -Rory Hunter -Ross Boucher -Rubens Figueiredo -Rui Cao -Ryan Belgrave -Ryan Detzel -Ryan Stelly -Ryan Wilson-Perkin -Ryan Zhang -Sainath Grandhi -Sakeven Jiang -Sally O'Malley -Sam Neirinck -Sam Thibault -Samarth Shah -Sambuddha Basu -Sami Tabet -Samuel Cochran -Samuel Karp -Sandro Jäckel -Santhosh Manohar -Sargun Dhillon -Saswat Bhattacharya -Scott Brenner -Scott Collier -Sean Christopherson -Sean Rodman -Sebastiaan van Stijn -Sergey Tryuber -Serhat Gülçiçek -Sevki Hasirci -Shaun Kaasten -Sheng Yang -Shijiang Wei -Shishir Mahajan -Shoubhik Bose -Shukui Yang -Sian Lerk Lau -Sidhartha Mani -sidharthamani -Silvin Lubecki -Simei He -Simon Ferquel -Simon Heimberg -Sindhu S -Slava Semushin -Solomon Hykes -Song Gao -Spencer Brown -Spring Lee -squeegels -Srini Brahmaroutu -Stefan S. -Stefan Scherer -Stefan Weil -Stephane Jeandeaux -Stephen Day -Stephen Rust -Steve Durrheimer -Steve Richards -Steven Burgess -Stoica-Marcu Floris-Andrei -Subhajit Ghosh -Sun Jianbo -Sune Keller -Sungwon Han -Sunny Gogoi -Sven Dowideit -Sylvain Baubeau -Sébastien HOUZÉ -T K Sourabh -TAGOMORI Satoshi -taiji-tech -Takeshi Koenuma -Takuya Noguchi -Taylor Jones -Teiva Harsanyi -Tejaswini Duggaraju -Tengfei Wang -Teppei Fukuda -Thatcher Peskens -Thibault Coupin -Thomas Gazagnaire -Thomas Krzero -Thomas Leonard -Thomas Léveil -Thomas Riccardi -Thomas Swift -Tianon Gravi -Tianyi Wang -Tibor Vass -Tim Dettrick -Tim Hockin -Tim Sampson -Tim Smith -Tim Waugh -Tim Wraight -timfeirg -Timothy Hobbs -Tobias Bradtke -Tobias Gesellchen -Todd Whiteman -Tom Denham -Tom Fotherby -Tom Klingenberg -Tom Milligan -Tom X. Tobin -Tomas Bäckman -Tomas Tomecek -Tomasz Kopczynski -Tomáš Hrčka -Tony Abboud -Tõnis Tiigi -Trapier Marshall -Travis Cline -Tristan Carel -Tycho Andersen -Tycho Andersen -uhayate -Ulrich Bareth -Ulysses Souza -Umesh Yadav -Valentin Lorentz -Vardan Pogosian -Venkateswara Reddy Bukkasamudram -Veres Lajos -Victor Vieux -Victoria Bialas -Viktor Stanchev -Vimal Raghubir -Vincent Batts -Vincent Bernat -Vincent Demeester -Vincent Woo -Vishnu Kannan -Vivek Goyal -Wang Jie -Wang Lei -Wang Long -Wang Ping -Wang Xing -Wang Yuexiao -Wang Yumu <37442693@qq.com> -Wataru Ishida -Wayne Song -Wen Cheng Ma -Wenzhi Liang -Wes Morgan -Wewang Xiaorenfine -William Henry -Xianglin Gao -Xiaodong Liu -Xiaodong Zhang -Xiaoxi He -Xinbo Weng -Xuecong Liao -Yan Feng -Yanqiang Miao -Yassine Tijani -Yi EungJun -Ying Li -Yong Tang -Yosef Fertel -Yu Peng -Yuan Sun -Yue Zhang -Yunxiang Huang -Zachary Romero -Zander Mackie -zebrilee -Zeel B Patel -Zhang Kun -Zhang Wei -Zhang Wentao -ZhangHang -zhenghenghuo -Zhou Hao -Zhoulin Xie -Zhu Guihua -Álex González -Álvaro Lázaro -Átila Camurça Alves -Александр Менщиков <__Singleton__@hackerdom.ru> -徐俊杰 diff --git a/vendor/github.com/docker/cli/LICENSE b/vendor/github.com/docker/cli/LICENSE deleted file mode 100644 index 9c8e20ab8..000000000 --- a/vendor/github.com/docker/cli/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2013-2017 Docker, Inc. - - 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 - - https://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. diff --git a/vendor/github.com/docker/cli/NOTICE b/vendor/github.com/docker/cli/NOTICE deleted file mode 100644 index 58b19b6d1..000000000 --- a/vendor/github.com/docker/cli/NOTICE +++ /dev/null @@ -1,19 +0,0 @@ -Docker -Copyright 2012-2017 Docker, Inc. - -This product includes software developed at Docker, Inc. (https://www.docker.com). - -This product contains software (https://github.com/creack/pty) developed -by Keith Rarick, licensed under the MIT License. - -The following is courtesy of our legal counsel: - - -Use and transfer of Docker may be subject to certain restrictions by the -United States and other governments. -It is your responsibility to ensure that your use and/or transfer does not -violate applicable laws. - -For more information, please see https://www.bis.doc.gov - -See also https://www.apache.org/dev/crypto.html and/or seek legal counsel. diff --git a/vendor/github.com/docker/cli/cli/config/config.go b/vendor/github.com/docker/cli/cli/config/config.go deleted file mode 100644 index b7c05c3f8..000000000 --- a/vendor/github.com/docker/cli/cli/config/config.go +++ /dev/null @@ -1,153 +0,0 @@ -package config - -import ( - "fmt" - "io" - "os" - "path/filepath" - "strings" - "sync" - - "github.com/docker/cli/cli/config/configfile" - "github.com/docker/cli/cli/config/credentials" - "github.com/docker/cli/cli/config/types" - "github.com/docker/docker/pkg/homedir" - "github.com/pkg/errors" -) - -const ( - // ConfigFileName is the name of config file - ConfigFileName = "config.json" - configFileDir = ".docker" - oldConfigfile = ".dockercfg" // Deprecated: remove once we stop printing deprecation warning - contextsDir = "contexts" -) - -var ( - initConfigDir = new(sync.Once) - configDir string - homeDir string -) - -// resetHomeDir is used in testing to reset the "homeDir" package variable to -// force re-lookup of the home directory between tests. -func resetHomeDir() { - homeDir = "" -} - -func getHomeDir() string { - if homeDir == "" { - homeDir = homedir.Get() - } - return homeDir -} - -// resetConfigDir is used in testing to reset the "configDir" package variable -// and its sync.Once to force re-lookup between tests. -func resetConfigDir() { - configDir = "" - initConfigDir = new(sync.Once) -} - -func setConfigDir() { - if configDir != "" { - return - } - configDir = os.Getenv("DOCKER_CONFIG") - if configDir == "" { - configDir = filepath.Join(getHomeDir(), configFileDir) - } -} - -// Dir returns the directory the configuration file is stored in -func Dir() string { - initConfigDir.Do(setConfigDir) - return configDir -} - -// ContextStoreDir returns the directory the docker contexts are stored in -func ContextStoreDir() string { - return filepath.Join(Dir(), contextsDir) -} - -// SetDir sets the directory the configuration file is stored in -func SetDir(dir string) { - configDir = filepath.Clean(dir) -} - -// Path returns the path to a file relative to the config dir -func Path(p ...string) (string, error) { - path := filepath.Join(append([]string{Dir()}, p...)...) - if !strings.HasPrefix(path, Dir()+string(filepath.Separator)) { - return "", errors.Errorf("path %q is outside of root config directory %q", path, Dir()) - } - return path, nil -} - -// LoadFromReader is a convenience function that creates a ConfigFile object from -// a reader -func LoadFromReader(configData io.Reader) (*configfile.ConfigFile, error) { - configFile := configfile.ConfigFile{ - AuthConfigs: make(map[string]types.AuthConfig), - } - err := configFile.LoadFromReader(configData) - return &configFile, err -} - -// Load reads the configuration files in the given directory, and sets up -// the auth config information and returns values. -// FIXME: use the internal golang config parser -func Load(configDir string) (*configfile.ConfigFile, error) { - cfg, _, err := load(configDir) - return cfg, err -} - -// TODO remove this temporary hack, which is used to warn about the deprecated ~/.dockercfg file -// so we can remove the bool return value and collapse this back into `Load` -func load(configDir string) (*configfile.ConfigFile, bool, error) { - printLegacyFileWarning := false - - if configDir == "" { - configDir = Dir() - } - - filename := filepath.Join(configDir, ConfigFileName) - configFile := configfile.New(filename) - - // Try happy path first - latest config file - if file, err := os.Open(filename); err == nil { - defer file.Close() - err = configFile.LoadFromReader(file) - if err != nil { - err = errors.Wrap(err, filename) - } - return configFile, printLegacyFileWarning, err - } else if !os.IsNotExist(err) { - // if file is there but we can't stat it for any reason other - // than it doesn't exist then stop - return configFile, printLegacyFileWarning, errors.Wrap(err, filename) - } - - // Can't find latest config file so check for the old one - filename = filepath.Join(getHomeDir(), oldConfigfile) - if _, err := os.Stat(filename); err == nil { - printLegacyFileWarning = true - } - return configFile, printLegacyFileWarning, nil -} - -// LoadDefaultConfigFile attempts to load the default config file and returns -// an initialized ConfigFile struct if none is found. -func LoadDefaultConfigFile(stderr io.Writer) *configfile.ConfigFile { - configFile, printLegacyFileWarning, err := load(Dir()) - if err != nil { - fmt.Fprintf(stderr, "WARNING: Error loading config file: %v\n", err) - } - if printLegacyFileWarning { - _, _ = fmt.Fprintln(stderr, "WARNING: Support for the legacy ~/.dockercfg configuration file and file-format has been removed and the configuration file will be ignored") - } - if !configFile.ContainsAuth() { - configFile.CredentialsStore = credentials.DetectDefaultStore(configFile.CredentialsStore) - } - return configFile -} diff --git a/vendor/github.com/docker/cli/cli/config/configfile/file.go b/vendor/github.com/docker/cli/cli/config/configfile/file.go deleted file mode 100644 index 442c31110..000000000 --- a/vendor/github.com/docker/cli/cli/config/configfile/file.go +++ /dev/null @@ -1,352 +0,0 @@ -package configfile - -import ( - "encoding/base64" - "encoding/json" - "io" - "os" - "path/filepath" - "strings" - - "github.com/docker/cli/cli/config/credentials" - "github.com/docker/cli/cli/config/types" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -// ConfigFile ~/.docker/config.json file info -type ConfigFile struct { - AuthConfigs map[string]types.AuthConfig `json:"auths"` - HTTPHeaders map[string]string `json:"HttpHeaders,omitempty"` - PsFormat string `json:"psFormat,omitempty"` - ImagesFormat string `json:"imagesFormat,omitempty"` - NetworksFormat string `json:"networksFormat,omitempty"` - PluginsFormat string `json:"pluginsFormat,omitempty"` - VolumesFormat string `json:"volumesFormat,omitempty"` - StatsFormat string `json:"statsFormat,omitempty"` - DetachKeys string `json:"detachKeys,omitempty"` - CredentialsStore string `json:"credsStore,omitempty"` - CredentialHelpers map[string]string `json:"credHelpers,omitempty"` - Filename string `json:"-"` // Note: for internal use only - ServiceInspectFormat string `json:"serviceInspectFormat,omitempty"` - ServicesFormat string `json:"servicesFormat,omitempty"` - TasksFormat string `json:"tasksFormat,omitempty"` - SecretFormat string `json:"secretFormat,omitempty"` - ConfigFormat string `json:"configFormat,omitempty"` - NodesFormat string `json:"nodesFormat,omitempty"` - PruneFilters []string `json:"pruneFilters,omitempty"` - Proxies map[string]ProxyConfig `json:"proxies,omitempty"` - Experimental string `json:"experimental,omitempty"` - CurrentContext string `json:"currentContext,omitempty"` - CLIPluginsExtraDirs []string `json:"cliPluginsExtraDirs,omitempty"` - Plugins map[string]map[string]string `json:"plugins,omitempty"` - Aliases map[string]string `json:"aliases,omitempty"` -} - -// ProxyConfig contains proxy configuration settings -type ProxyConfig struct { - HTTPProxy string `json:"httpProxy,omitempty"` - HTTPSProxy string `json:"httpsProxy,omitempty"` - NoProxy string `json:"noProxy,omitempty"` - FTPProxy string `json:"ftpProxy,omitempty"` - AllProxy string `json:"allProxy,omitempty"` -} - -// New initializes an empty configuration file for the given filename 'fn' -func New(fn string) *ConfigFile { - return &ConfigFile{ - AuthConfigs: make(map[string]types.AuthConfig), - HTTPHeaders: make(map[string]string), - Filename: fn, - Plugins: make(map[string]map[string]string), - Aliases: make(map[string]string), - } -} - -// LoadFromReader reads the configuration data given and sets up the auth config -// information with given directory and populates the receiver object -func (configFile *ConfigFile) LoadFromReader(configData io.Reader) error { - if err := json.NewDecoder(configData).Decode(configFile); err != nil && !errors.Is(err, io.EOF) { - return err - } - var err error - for addr, ac := range configFile.AuthConfigs { - if ac.Auth != "" { - ac.Username, ac.Password, err = decodeAuth(ac.Auth) - if err != nil { - return err - } - } - ac.Auth = "" - ac.ServerAddress = addr - configFile.AuthConfigs[addr] = ac - } - return nil -} - -// ContainsAuth returns whether there is authentication configured -// in this file or not. -func (configFile *ConfigFile) ContainsAuth() bool { - return configFile.CredentialsStore != "" || - len(configFile.CredentialHelpers) > 0 || - len(configFile.AuthConfigs) > 0 -} - -// GetAuthConfigs returns the mapping of repo to auth configuration -func (configFile *ConfigFile) GetAuthConfigs() map[string]types.AuthConfig { - if configFile.AuthConfigs == nil { - configFile.AuthConfigs = make(map[string]types.AuthConfig) - } - return configFile.AuthConfigs -} - -// SaveToWriter encodes and writes out all the authorization information to -// the given writer -func (configFile *ConfigFile) SaveToWriter(writer io.Writer) error { - // Encode sensitive data into a new/temp struct - tmpAuthConfigs := make(map[string]types.AuthConfig, len(configFile.AuthConfigs)) - for k, authConfig := range configFile.AuthConfigs { - authCopy := authConfig - // encode and save the authstring, while blanking out the original fields - authCopy.Auth = encodeAuth(&authCopy) - authCopy.Username = "" - authCopy.Password = "" - authCopy.ServerAddress = "" - tmpAuthConfigs[k] = authCopy - } - - saveAuthConfigs := configFile.AuthConfigs - configFile.AuthConfigs = tmpAuthConfigs - defer func() { configFile.AuthConfigs = saveAuthConfigs }() - - // User-Agent header is automatically set, and should not be stored in the configuration - for v := range configFile.HTTPHeaders { - if strings.EqualFold(v, "User-Agent") { - delete(configFile.HTTPHeaders, v) - } - } - - data, err := json.MarshalIndent(configFile, "", "\t") - if err != nil { - return err - } - _, err = writer.Write(data) - return err -} - -// Save encodes and writes out all the authorization information -func (configFile *ConfigFile) Save() (retErr error) { - if configFile.Filename == "" { - return errors.Errorf("Can't save config with empty filename") - } - - dir := filepath.Dir(configFile.Filename) - if err := os.MkdirAll(dir, 0o700); err != nil { - return err - } - temp, err := os.CreateTemp(dir, filepath.Base(configFile.Filename)) - if err != nil { - return err - } - defer func() { - temp.Close() - if retErr != nil { - if err := os.Remove(temp.Name()); err != nil { - logrus.WithError(err).WithField("file", temp.Name()).Debug("Error cleaning up temp file") - } - } - }() - - err = configFile.SaveToWriter(temp) - if err != nil { - return err - } - - if err := temp.Close(); err != nil { - return errors.Wrap(err, "error closing temp file") - } - - // Handle situation where the configfile is a symlink - cfgFile := configFile.Filename - if f, err := os.Readlink(cfgFile); err == nil { - cfgFile = f - } - - // Try copying the current config file (if any) ownership and permissions - copyFilePermissions(cfgFile, temp.Name()) - return os.Rename(temp.Name(), cfgFile) -} - -// ParseProxyConfig computes proxy configuration by retrieving the config for the provided host and -// then checking this against any environment variables provided to the container -func (configFile *ConfigFile) ParseProxyConfig(host string, runOpts map[string]*string) map[string]*string { - var cfgKey string - - if _, ok := configFile.Proxies[host]; !ok { - cfgKey = "default" - } else { - cfgKey = host - } - - config := configFile.Proxies[cfgKey] - permitted := map[string]*string{ - "HTTP_PROXY": &config.HTTPProxy, - "HTTPS_PROXY": &config.HTTPSProxy, - "NO_PROXY": &config.NoProxy, - "FTP_PROXY": &config.FTPProxy, - "ALL_PROXY": &config.AllProxy, - } - m := runOpts - if m == nil { - m = make(map[string]*string) - } - for k := range permitted { - if *permitted[k] == "" { - continue - } - if _, ok := m[k]; !ok { - m[k] = permitted[k] - } - if _, ok := m[strings.ToLower(k)]; !ok { - m[strings.ToLower(k)] = permitted[k] - } - } - return m -} - -// encodeAuth creates a base64 encoded string to containing authorization information -func encodeAuth(authConfig *types.AuthConfig) string { - if authConfig.Username == "" && authConfig.Password == "" { - return "" - } - - authStr := authConfig.Username + ":" + authConfig.Password - msg := []byte(authStr) - encoded := make([]byte, base64.StdEncoding.EncodedLen(len(msg))) - base64.StdEncoding.Encode(encoded, msg) - return string(encoded) -} - -// decodeAuth decodes a base64 encoded string and returns username and password -func decodeAuth(authStr string) (string, string, error) { - if authStr == "" { - return "", "", nil - } - - decLen := base64.StdEncoding.DecodedLen(len(authStr)) - decoded := make([]byte, decLen) - authByte := []byte(authStr) - n, err := base64.StdEncoding.Decode(decoded, authByte) - if err != nil { - return "", "", err - } - if n > decLen { - return "", "", errors.Errorf("Something went wrong decoding auth config") - } - userName, password, ok := strings.Cut(string(decoded), ":") - if !ok || userName == "" { - return "", "", errors.Errorf("Invalid auth configuration file") - } - return userName, strings.Trim(password, "\x00"), nil -} - -// GetCredentialsStore returns a new credentials store from the settings in the -// configuration file -func (configFile *ConfigFile) GetCredentialsStore(registryHostname string) credentials.Store { - if helper := getConfiguredCredentialStore(configFile, registryHostname); helper != "" { - return newNativeStore(configFile, helper) - } - return credentials.NewFileStore(configFile) -} - -// var for unit testing. -var newNativeStore = func(configFile *ConfigFile, helperSuffix string) credentials.Store { - return credentials.NewNativeStore(configFile, helperSuffix) -} - -// GetAuthConfig for a repository from the credential store -func (configFile *ConfigFile) GetAuthConfig(registryHostname string) (types.AuthConfig, error) { - return configFile.GetCredentialsStore(registryHostname).Get(registryHostname) -} - -// getConfiguredCredentialStore returns the credential helper configured for the -// given registry, the default credsStore, or the empty string if neither are -// configured. -func getConfiguredCredentialStore(c *ConfigFile, registryHostname string) string { - if c.CredentialHelpers != nil && registryHostname != "" { - if helper, exists := c.CredentialHelpers[registryHostname]; exists { - return helper - } - } - return c.CredentialsStore -} - -// GetAllCredentials returns all of the credentials stored in all of the -// configured credential stores. -func (configFile *ConfigFile) GetAllCredentials() (map[string]types.AuthConfig, error) { - auths := make(map[string]types.AuthConfig) - addAll := func(from map[string]types.AuthConfig) { - for reg, ac := range from { - auths[reg] = ac - } - } - - defaultStore := configFile.GetCredentialsStore("") - newAuths, err := defaultStore.GetAll() - if err != nil { - return nil, err - } - addAll(newAuths) - - // Auth configs from a registry-specific helper should override those from the default store. - for registryHostname := range configFile.CredentialHelpers { - newAuth, err := configFile.GetAuthConfig(registryHostname) - if err != nil { - logrus.WithError(err).Warnf("Failed to get credentials for registry: %s", registryHostname) - continue - } - auths[registryHostname] = newAuth - } - return auths, nil -} - -// GetFilename returns the file name that this config file is based on. -func (configFile *ConfigFile) GetFilename() string { - return configFile.Filename -} - -// PluginConfig retrieves the requested option for the given plugin. -func (configFile *ConfigFile) PluginConfig(pluginname, option string) (string, bool) { - if configFile.Plugins == nil { - return "", false - } - pluginConfig, ok := configFile.Plugins[pluginname] - if !ok { - return "", false - } - value, ok := pluginConfig[option] - return value, ok -} - -// SetPluginConfig sets the option to the given value for the given -// plugin. Passing a value of "" will remove the option. If removing -// the final config item for a given plugin then also cleans up the -// overall plugin entry. -func (configFile *ConfigFile) SetPluginConfig(pluginname, option, value string) { - if configFile.Plugins == nil { - configFile.Plugins = make(map[string]map[string]string) - } - pluginConfig, ok := configFile.Plugins[pluginname] - if !ok { - pluginConfig = make(map[string]string) - configFile.Plugins[pluginname] = pluginConfig - } - if value != "" { - pluginConfig[option] = value - } else { - delete(pluginConfig, option) - } - if len(pluginConfig) == 0 { - delete(configFile.Plugins, pluginname) - } -} diff --git a/vendor/github.com/docker/cli/cli/config/configfile/file_unix.go b/vendor/github.com/docker/cli/cli/config/configfile/file_unix.go deleted file mode 100644 index 353887547..000000000 --- a/vendor/github.com/docker/cli/cli/config/configfile/file_unix.go +++ /dev/null @@ -1,36 +0,0 @@ -//go:build !windows -// +build !windows - -package configfile - -import ( - "os" - "syscall" -) - -// copyFilePermissions copies file ownership and permissions from "src" to "dst", -// ignoring any error during the process. -func copyFilePermissions(src, dst string) { - var ( - mode os.FileMode = 0o600 - uid, gid int - ) - - fi, err := os.Stat(src) - if err != nil { - return - } - if fi.Mode().IsRegular() { - mode = fi.Mode() - } - if err := os.Chmod(dst, mode); err != nil { - return - } - - uid = int(fi.Sys().(*syscall.Stat_t).Uid) - gid = int(fi.Sys().(*syscall.Stat_t).Gid) - - if uid > 0 && gid > 0 { - _ = os.Chown(dst, uid, gid) - } -} diff --git a/vendor/github.com/docker/cli/cli/config/configfile/file_windows.go b/vendor/github.com/docker/cli/cli/config/configfile/file_windows.go deleted file mode 100644 index 42fffc39a..000000000 --- a/vendor/github.com/docker/cli/cli/config/configfile/file_windows.go +++ /dev/null @@ -1,5 +0,0 @@ -package configfile - -func copyFilePermissions(src, dst string) { - // TODO implement for Windows -} diff --git a/vendor/github.com/docker/cli/cli/config/credentials/credentials.go b/vendor/github.com/docker/cli/cli/config/credentials/credentials.go deleted file mode 100644 index 28d58ec48..000000000 --- a/vendor/github.com/docker/cli/cli/config/credentials/credentials.go +++ /dev/null @@ -1,17 +0,0 @@ -package credentials - -import ( - "github.com/docker/cli/cli/config/types" -) - -// Store is the interface that any credentials store must implement. -type Store interface { - // Erase removes credentials from the store for a given server. - Erase(serverAddress string) error - // Get retrieves credentials from the store for a given server. - Get(serverAddress string) (types.AuthConfig, error) - // GetAll retrieves all the credentials from the store. - GetAll() (map[string]types.AuthConfig, error) - // Store saves credentials in the store. - Store(authConfig types.AuthConfig) error -} diff --git a/vendor/github.com/docker/cli/cli/config/credentials/default_store.go b/vendor/github.com/docker/cli/cli/config/credentials/default_store.go deleted file mode 100644 index 402235bff..000000000 --- a/vendor/github.com/docker/cli/cli/config/credentials/default_store.go +++ /dev/null @@ -1,21 +0,0 @@ -package credentials - -import ( - exec "golang.org/x/sys/execabs" -) - -// DetectDefaultStore return the default credentials store for the platform if -// the store executable is available. -func DetectDefaultStore(store string) string { - platformDefault := defaultCredentialsStore() - - // user defined or no default for platform - if store != "" || platformDefault == "" { - return store - } - - if _, err := exec.LookPath(remoteCredentialsPrefix + platformDefault); err == nil { - return platformDefault - } - return "" -} diff --git a/vendor/github.com/docker/cli/cli/config/credentials/default_store_darwin.go b/vendor/github.com/docker/cli/cli/config/credentials/default_store_darwin.go deleted file mode 100644 index 5d42dec62..000000000 --- a/vendor/github.com/docker/cli/cli/config/credentials/default_store_darwin.go +++ /dev/null @@ -1,5 +0,0 @@ -package credentials - -func defaultCredentialsStore() string { - return "osxkeychain" -} diff --git a/vendor/github.com/docker/cli/cli/config/credentials/default_store_linux.go b/vendor/github.com/docker/cli/cli/config/credentials/default_store_linux.go deleted file mode 100644 index a9012c6d4..000000000 --- a/vendor/github.com/docker/cli/cli/config/credentials/default_store_linux.go +++ /dev/null @@ -1,13 +0,0 @@ -package credentials - -import ( - "os/exec" -) - -func defaultCredentialsStore() string { - if _, err := exec.LookPath("pass"); err == nil { - return "pass" - } - - return "secretservice" -} diff --git a/vendor/github.com/docker/cli/cli/config/credentials/default_store_unsupported.go b/vendor/github.com/docker/cli/cli/config/credentials/default_store_unsupported.go deleted file mode 100644 index c9630ea51..000000000 --- a/vendor/github.com/docker/cli/cli/config/credentials/default_store_unsupported.go +++ /dev/null @@ -1,8 +0,0 @@ -//go:build !windows && !darwin && !linux -// +build !windows,!darwin,!linux - -package credentials - -func defaultCredentialsStore() string { - return "" -} diff --git a/vendor/github.com/docker/cli/cli/config/credentials/default_store_windows.go b/vendor/github.com/docker/cli/cli/config/credentials/default_store_windows.go deleted file mode 100644 index bb799ca61..000000000 --- a/vendor/github.com/docker/cli/cli/config/credentials/default_store_windows.go +++ /dev/null @@ -1,5 +0,0 @@ -package credentials - -func defaultCredentialsStore() string { - return "wincred" -} diff --git a/vendor/github.com/docker/cli/cli/config/credentials/file_store.go b/vendor/github.com/docker/cli/cli/config/credentials/file_store.go deleted file mode 100644 index ea30fc300..000000000 --- a/vendor/github.com/docker/cli/cli/config/credentials/file_store.go +++ /dev/null @@ -1,81 +0,0 @@ -package credentials - -import ( - "strings" - - "github.com/docker/cli/cli/config/types" -) - -type store interface { - Save() error - GetAuthConfigs() map[string]types.AuthConfig - GetFilename() string -} - -// fileStore implements a credentials store using -// the docker configuration file to keep the credentials in plain text. -type fileStore struct { - file store -} - -// NewFileStore creates a new file credentials store. -func NewFileStore(file store) Store { - return &fileStore{file: file} -} - -// Erase removes the given credentials from the file store. -func (c *fileStore) Erase(serverAddress string) error { - delete(c.file.GetAuthConfigs(), serverAddress) - return c.file.Save() -} - -// Get retrieves credentials for a specific server from the file store. -func (c *fileStore) Get(serverAddress string) (types.AuthConfig, error) { - authConfig, ok := c.file.GetAuthConfigs()[serverAddress] - if !ok { - // Maybe they have a legacy config file, we will iterate the keys converting - // them to the new format and testing - for r, ac := range c.file.GetAuthConfigs() { - if serverAddress == ConvertToHostname(r) { - return ac, nil - } - } - - authConfig = types.AuthConfig{} - } - return authConfig, nil -} - -func (c *fileStore) GetAll() (map[string]types.AuthConfig, error) { - return c.file.GetAuthConfigs(), nil -} - -// Store saves the given credentials in the file store. -func (c *fileStore) Store(authConfig types.AuthConfig) error { - authConfigs := c.file.GetAuthConfigs() - authConfigs[authConfig.ServerAddress] = authConfig - return c.file.Save() -} - -func (c *fileStore) GetFilename() string { - return c.file.GetFilename() -} - -func (c *fileStore) IsFileStore() bool { - return true -} - -// ConvertToHostname converts a registry url which has http|https prepended -// to just an hostname. -// Copied from github.com/docker/docker/registry.ConvertToHostname to reduce dependencies. -func ConvertToHostname(url string) string { - stripped := url - if strings.HasPrefix(url, "http://") { - stripped = strings.TrimPrefix(url, "http://") - } else if strings.HasPrefix(url, "https://") { - stripped = strings.TrimPrefix(url, "https://") - } - - hostName, _, _ := strings.Cut(stripped, "/") - return hostName -} diff --git a/vendor/github.com/docker/cli/cli/config/credentials/native_store.go b/vendor/github.com/docker/cli/cli/config/credentials/native_store.go deleted file mode 100644 index b9af145b9..000000000 --- a/vendor/github.com/docker/cli/cli/config/credentials/native_store.go +++ /dev/null @@ -1,147 +0,0 @@ -package credentials - -import ( - "github.com/docker/cli/cli/config/types" - "github.com/docker/docker-credential-helpers/client" - "github.com/docker/docker-credential-helpers/credentials" -) - -const ( - remoteCredentialsPrefix = "docker-credential-" //nolint:gosec // ignore G101: Potential hardcoded credentials - tokenUsername = "" -) - -// nativeStore implements a credentials store -// using native keychain to keep credentials secure. -// It piggybacks into a file store to keep users' emails. -type nativeStore struct { - programFunc client.ProgramFunc - fileStore Store -} - -// NewNativeStore creates a new native store that -// uses a remote helper program to manage credentials. -func NewNativeStore(file store, helperSuffix string) Store { - name := remoteCredentialsPrefix + helperSuffix - return &nativeStore{ - programFunc: client.NewShellProgramFunc(name), - fileStore: NewFileStore(file), - } -} - -// Erase removes the given credentials from the native store. -func (c *nativeStore) Erase(serverAddress string) error { - if err := client.Erase(c.programFunc, serverAddress); err != nil { - return err - } - - // Fallback to plain text store to remove email - return c.fileStore.Erase(serverAddress) -} - -// Get retrieves credentials for a specific server from the native store. -func (c *nativeStore) Get(serverAddress string) (types.AuthConfig, error) { - // load user email if it exist or an empty auth config. - auth, _ := c.fileStore.Get(serverAddress) - - creds, err := c.getCredentialsFromStore(serverAddress) - if err != nil { - return auth, err - } - auth.Username = creds.Username - auth.IdentityToken = creds.IdentityToken - auth.Password = creds.Password - auth.ServerAddress = creds.ServerAddress - - return auth, nil -} - -// GetAll retrieves all the credentials from the native store. -func (c *nativeStore) GetAll() (map[string]types.AuthConfig, error) { - auths, err := c.listCredentialsInStore() - if err != nil { - return nil, err - } - - // Emails are only stored in the file store. - // This call can be safely eliminated when emails are removed. - fileConfigs, _ := c.fileStore.GetAll() - - authConfigs := make(map[string]types.AuthConfig) - for registry := range auths { - creds, err := c.getCredentialsFromStore(registry) - if err != nil { - return nil, err - } - ac := fileConfigs[registry] // might contain Email - ac.Username = creds.Username - ac.Password = creds.Password - ac.IdentityToken = creds.IdentityToken - if ac.ServerAddress == "" { - ac.ServerAddress = creds.ServerAddress - } - authConfigs[registry] = ac - } - - return authConfigs, nil -} - -// Store saves the given credentials in the file store. -func (c *nativeStore) Store(authConfig types.AuthConfig) error { - if err := c.storeCredentialsInStore(authConfig); err != nil { - return err - } - authConfig.Username = "" - authConfig.Password = "" - authConfig.IdentityToken = "" - - // Fallback to old credential in plain text to save only the email - return c.fileStore.Store(authConfig) -} - -// storeCredentialsInStore executes the command to store the credentials in the native store. -func (c *nativeStore) storeCredentialsInStore(config types.AuthConfig) error { - creds := &credentials.Credentials{ - ServerURL: config.ServerAddress, - Username: config.Username, - Secret: config.Password, - } - - if config.IdentityToken != "" { - creds.Username = tokenUsername - creds.Secret = config.IdentityToken - } - - return client.Store(c.programFunc, creds) -} - -// getCredentialsFromStore executes the command to get the credentials from the native store. -func (c *nativeStore) getCredentialsFromStore(serverAddress string) (types.AuthConfig, error) { - var ret types.AuthConfig - - creds, err := client.Get(c.programFunc, serverAddress) - if err != nil { - if credentials.IsErrCredentialsNotFound(err) { - // do not return an error if the credentials are not - // in the keychain. Let docker ask for new credentials. - return ret, nil - } - return ret, err - } - - if creds.Username == tokenUsername { - ret.IdentityToken = creds.Secret - } else { - ret.Password = creds.Secret - ret.Username = creds.Username - } - - ret.ServerAddress = serverAddress - return ret, nil -} - -// listCredentialsInStore returns a listing of stored credentials as a map of -// URL -> username. -func (c *nativeStore) listCredentialsInStore() (map[string]string, error) { - return client.List(c.programFunc) -} diff --git a/vendor/github.com/docker/cli/cli/config/types/authconfig.go b/vendor/github.com/docker/cli/cli/config/types/authconfig.go deleted file mode 100644 index 056af6b84..000000000 --- a/vendor/github.com/docker/cli/cli/config/types/authconfig.go +++ /dev/null @@ -1,22 +0,0 @@ -package types - -// AuthConfig contains authorization information for connecting to a Registry -type AuthConfig struct { - Username string `json:"username,omitempty"` - Password string `json:"password,omitempty"` - Auth string `json:"auth,omitempty"` - - // Email is an optional value associated with the username. - // This field is deprecated and will be removed in a later - // version of docker. - Email string `json:"email,omitempty"` - - ServerAddress string `json:"serveraddress,omitempty"` - - // IdentityToken is used to authenticate the user and get - // an access token for the registry. - IdentityToken string `json:"identitytoken,omitempty"` - - // RegistryToken is a bearer token to be sent to a registry - RegistryToken string `json:"registrytoken,omitempty"` -} diff --git a/vendor/github.com/docker/distribution/LICENSE b/vendor/github.com/docker/distribution/LICENSE deleted file mode 100644 index e06d20818..000000000 --- a/vendor/github.com/docker/distribution/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - 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 "{}" - 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 - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - 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. - diff --git a/vendor/github.com/docker/distribution/registry/client/auth/challenge/addr.go b/vendor/github.com/docker/distribution/registry/client/auth/challenge/addr.go deleted file mode 100644 index 2c3ebe165..000000000 --- a/vendor/github.com/docker/distribution/registry/client/auth/challenge/addr.go +++ /dev/null @@ -1,27 +0,0 @@ -package challenge - -import ( - "net/url" - "strings" -) - -// FROM: https://golang.org/src/net/http/http.go -// Given a string of the form "host", "host:port", or "[ipv6::address]:port", -// return true if the string includes a port. -func hasPort(s string) bool { return strings.LastIndex(s, ":") > strings.LastIndex(s, "]") } - -// FROM: http://golang.org/src/net/http/transport.go -var portMap = map[string]string{ - "http": "80", - "https": "443", -} - -// canonicalAddr returns url.Host but always with a ":port" suffix -// FROM: http://golang.org/src/net/http/transport.go -func canonicalAddr(url *url.URL) string { - addr := url.Host - if !hasPort(addr) { - return addr + ":" + portMap[url.Scheme] - } - return addr -} diff --git a/vendor/github.com/docker/distribution/registry/client/auth/challenge/authchallenge.go b/vendor/github.com/docker/distribution/registry/client/auth/challenge/authchallenge.go deleted file mode 100644 index fe238210c..000000000 --- a/vendor/github.com/docker/distribution/registry/client/auth/challenge/authchallenge.go +++ /dev/null @@ -1,237 +0,0 @@ -package challenge - -import ( - "fmt" - "net/http" - "net/url" - "strings" - "sync" -) - -// Challenge carries information from a WWW-Authenticate response header. -// See RFC 2617. -type Challenge struct { - // Scheme is the auth-scheme according to RFC 2617 - Scheme string - - // Parameters are the auth-params according to RFC 2617 - Parameters map[string]string -} - -// Manager manages the challenges for endpoints. -// The challenges are pulled out of HTTP responses. Only -// responses which expect challenges should be added to -// the manager, since a non-unauthorized request will be -// viewed as not requiring challenges. -type Manager interface { - // GetChallenges returns the challenges for the given - // endpoint URL. - GetChallenges(endpoint url.URL) ([]Challenge, error) - - // AddResponse adds the response to the challenge - // manager. The challenges will be parsed out of - // the WWW-Authenicate headers and added to the - // URL which was produced the response. If the - // response was authorized, any challenges for the - // endpoint will be cleared. - AddResponse(resp *http.Response) error -} - -// NewSimpleManager returns an instance of -// Manger which only maps endpoints to challenges -// based on the responses which have been added the -// manager. The simple manager will make no attempt to -// perform requests on the endpoints or cache the responses -// to a backend. -func NewSimpleManager() Manager { - return &simpleManager{ - Challenges: make(map[string][]Challenge), - } -} - -type simpleManager struct { - sync.RWMutex - Challenges map[string][]Challenge -} - -func normalizeURL(endpoint *url.URL) { - endpoint.Host = strings.ToLower(endpoint.Host) - endpoint.Host = canonicalAddr(endpoint) -} - -func (m *simpleManager) GetChallenges(endpoint url.URL) ([]Challenge, error) { - normalizeURL(&endpoint) - - m.RLock() - defer m.RUnlock() - challenges := m.Challenges[endpoint.String()] - return challenges, nil -} - -func (m *simpleManager) AddResponse(resp *http.Response) error { - challenges := ResponseChallenges(resp) - if resp.Request == nil { - return fmt.Errorf("missing request reference") - } - urlCopy := url.URL{ - Path: resp.Request.URL.Path, - Host: resp.Request.URL.Host, - Scheme: resp.Request.URL.Scheme, - } - normalizeURL(&urlCopy) - - m.Lock() - defer m.Unlock() - m.Challenges[urlCopy.String()] = challenges - return nil -} - -// Octet types from RFC 2616. -type octetType byte - -var octetTypes [256]octetType - -const ( - isToken octetType = 1 << iota - isSpace -) - -func init() { - // OCTET = - // CHAR = - // CTL = - // CR = - // LF = - // SP = - // HT = - // <"> = - // CRLF = CR LF - // LWS = [CRLF] 1*( SP | HT ) - // TEXT = - // separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> - // | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT - // token = 1* - // qdtext = > - - for c := 0; c < 256; c++ { - var t octetType - isCtl := c <= 31 || c == 127 - isChar := 0 <= c && c <= 127 - isSeparator := strings.ContainsRune(" \t\"(),/:;<=>?@[]\\{}", rune(c)) - if strings.ContainsRune(" \t\r\n", rune(c)) { - t |= isSpace - } - if isChar && !isCtl && !isSeparator { - t |= isToken - } - octetTypes[c] = t - } -} - -// ResponseChallenges returns a list of authorization challenges -// for the given http Response. Challenges are only checked if -// the response status code was a 401. -func ResponseChallenges(resp *http.Response) []Challenge { - if resp.StatusCode == http.StatusUnauthorized { - // Parse the WWW-Authenticate Header and store the challenges - // on this endpoint object. - return parseAuthHeader(resp.Header) - } - - return nil -} - -func parseAuthHeader(header http.Header) []Challenge { - challenges := []Challenge{} - for _, h := range header[http.CanonicalHeaderKey("WWW-Authenticate")] { - v, p := parseValueAndParams(h) - if v != "" { - challenges = append(challenges, Challenge{Scheme: v, Parameters: p}) - } - } - return challenges -} - -func parseValueAndParams(header string) (value string, params map[string]string) { - params = make(map[string]string) - value, s := expectToken(header) - if value == "" { - return - } - value = strings.ToLower(value) - s = "," + skipSpace(s) - for strings.HasPrefix(s, ",") { - var pkey string - pkey, s = expectToken(skipSpace(s[1:])) - if pkey == "" { - return - } - if !strings.HasPrefix(s, "=") { - return - } - var pvalue string - pvalue, s = expectTokenOrQuoted(s[1:]) - if pvalue == "" { - return - } - pkey = strings.ToLower(pkey) - params[pkey] = pvalue - s = skipSpace(s) - } - return -} - -func skipSpace(s string) (rest string) { - i := 0 - for ; i < len(s); i++ { - if octetTypes[s[i]]&isSpace == 0 { - break - } - } - return s[i:] -} - -func expectToken(s string) (token, rest string) { - i := 0 - for ; i < len(s); i++ { - if octetTypes[s[i]]&isToken == 0 { - break - } - } - return s[:i], s[i:] -} - -func expectTokenOrQuoted(s string) (value string, rest string) { - if !strings.HasPrefix(s, "\"") { - return expectToken(s) - } - s = s[1:] - for i := 0; i < len(s); i++ { - switch s[i] { - case '"': - return s[:i], s[i+1:] - case '\\': - p := make([]byte, len(s)-1) - j := copy(p, s[:i]) - escape := true - for i = i + 1; i < len(s); i++ { - b := s[i] - switch { - case escape: - escape = false - p[j] = b - j++ - case b == '\\': - escape = true - case b == '"': - return string(p[:j]), s[i+1:] - default: - p[j] = b - j++ - } - } - return "", "" - } - } - return "", "" -} diff --git a/vendor/github.com/docker/docker-credential-helpers/LICENSE b/vendor/github.com/docker/docker-credential-helpers/LICENSE deleted file mode 100644 index 1ea555e2a..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2016 David Calavera - -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. diff --git a/vendor/github.com/docker/docker-credential-helpers/client/client.go b/vendor/github.com/docker/docker-credential-helpers/client/client.go deleted file mode 100644 index d1d0434cb..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/client/client.go +++ /dev/null @@ -1,121 +0,0 @@ -package client - -import ( - "bytes" - "encoding/json" - "fmt" - "strings" - - "github.com/docker/docker-credential-helpers/credentials" -) - -// isValidCredsMessage checks if 'msg' contains invalid credentials error message. -// It returns whether the logs are free of invalid credentials errors and the error if it isn't. -// error values can be errCredentialsMissingServerURL or errCredentialsMissingUsername. -func isValidCredsMessage(msg string) error { - if credentials.IsCredentialsMissingServerURLMessage(msg) { - return credentials.NewErrCredentialsMissingServerURL() - } - - if credentials.IsCredentialsMissingUsernameMessage(msg) { - return credentials.NewErrCredentialsMissingUsername() - } - - return nil -} - -// Store uses an external program to save credentials. -func Store(program ProgramFunc, creds *credentials.Credentials) error { - cmd := program("store") - - buffer := new(bytes.Buffer) - if err := json.NewEncoder(buffer).Encode(creds); err != nil { - return err - } - cmd.Input(buffer) - - out, err := cmd.Output() - if err != nil { - t := strings.TrimSpace(string(out)) - - if isValidErr := isValidCredsMessage(t); isValidErr != nil { - err = isValidErr - } - - return fmt.Errorf("error storing credentials - err: %v, out: `%s`", err, t) - } - - return nil -} - -// Get executes an external program to get the credentials from a native store. -func Get(program ProgramFunc, serverURL string) (*credentials.Credentials, error) { - cmd := program("get") - cmd.Input(strings.NewReader(serverURL)) - - out, err := cmd.Output() - if err != nil { - t := strings.TrimSpace(string(out)) - - if credentials.IsErrCredentialsNotFoundMessage(t) { - return nil, credentials.NewErrCredentialsNotFound() - } - - if isValidErr := isValidCredsMessage(t); isValidErr != nil { - err = isValidErr - } - - return nil, fmt.Errorf("error getting credentials - err: %v, out: `%s`", err, t) - } - - resp := &credentials.Credentials{ - ServerURL: serverURL, - } - - if err := json.NewDecoder(bytes.NewReader(out)).Decode(resp); err != nil { - return nil, err - } - - return resp, nil -} - -// Erase executes a program to remove the server credentials from the native store. -func Erase(program ProgramFunc, serverURL string) error { - cmd := program("erase") - cmd.Input(strings.NewReader(serverURL)) - out, err := cmd.Output() - if err != nil { - t := strings.TrimSpace(string(out)) - - if isValidErr := isValidCredsMessage(t); isValidErr != nil { - err = isValidErr - } - - return fmt.Errorf("error erasing credentials - err: %v, out: `%s`", err, t) - } - - return nil -} - -// List executes a program to list server credentials in the native store. -func List(program ProgramFunc) (map[string]string, error) { - cmd := program("list") - cmd.Input(strings.NewReader("unused")) - out, err := cmd.Output() - if err != nil { - t := strings.TrimSpace(string(out)) - - if isValidErr := isValidCredsMessage(t); isValidErr != nil { - err = isValidErr - } - - return nil, fmt.Errorf("error listing credentials - err: %v, out: `%s`", err, t) - } - - var resp map[string]string - if err = json.NewDecoder(bytes.NewReader(out)).Decode(&resp); err != nil { - return nil, err - } - - return resp, nil -} diff --git a/vendor/github.com/docker/docker-credential-helpers/client/command.go b/vendor/github.com/docker/docker-credential-helpers/client/command.go deleted file mode 100644 index 0183c0639..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/client/command.go +++ /dev/null @@ -1,57 +0,0 @@ -package client - -import ( - "fmt" - "io" - "os" - - exec "golang.org/x/sys/execabs" -) - -// Program is an interface to execute external programs. -type Program interface { - Output() ([]byte, error) - Input(in io.Reader) -} - -// ProgramFunc is a type of function that initializes programs based on arguments. -type ProgramFunc func(args ...string) Program - -// NewShellProgramFunc creates programs that are executed in a Shell. -func NewShellProgramFunc(name string) ProgramFunc { - return NewShellProgramFuncWithEnv(name, nil) -} - -// NewShellProgramFuncWithEnv creates programs that are executed in a Shell with environment variables -func NewShellProgramFuncWithEnv(name string, env *map[string]string) ProgramFunc { - return func(args ...string) Program { - return &Shell{cmd: createProgramCmdRedirectErr(name, args, env)} - } -} - -func createProgramCmdRedirectErr(commandName string, args []string, env *map[string]string) *exec.Cmd { - programCmd := exec.Command(commandName, args...) - programCmd.Env = os.Environ() - if env != nil { - for k, v := range *env { - programCmd.Env = append(programCmd.Env, fmt.Sprintf("%s=%s", k, v)) - } - } - programCmd.Stderr = os.Stderr - return programCmd -} - -// Shell invokes shell commands to talk with a remote credentials helper. -type Shell struct { - cmd *exec.Cmd -} - -// Output returns responses from the remote credentials helper. -func (s *Shell) Output() ([]byte, error) { - return s.cmd.Output() -} - -// Input sets the input to send to a remote credentials helper. -func (s *Shell) Input(in io.Reader) { - s.cmd.Stdin = in -} diff --git a/vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go b/vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go deleted file mode 100644 index 91d9d4bba..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go +++ /dev/null @@ -1,186 +0,0 @@ -package credentials - -import ( - "bufio" - "bytes" - "encoding/json" - "fmt" - "io" - "os" - "strings" -) - -// Credentials holds the information shared between docker and the credentials store. -type Credentials struct { - ServerURL string - Username string - Secret string -} - -// isValid checks the integrity of Credentials object such that no credentials lack -// a server URL or a username. -// It returns whether the credentials are valid and the error if it isn't. -// error values can be errCredentialsMissingServerURL or errCredentialsMissingUsername -func (c *Credentials) isValid() (bool, error) { - if len(c.ServerURL) == 0 { - return false, NewErrCredentialsMissingServerURL() - } - - if len(c.Username) == 0 { - return false, NewErrCredentialsMissingUsername() - } - - return true, nil -} - -// CredsLabel holds the way Docker credentials should be labeled as such in credentials stores that allow labelling. -// That label allows to filter out non-Docker credentials too at lookup/search in macOS keychain, -// Windows credentials manager and Linux libsecret. Default value is "Docker Credentials" -var CredsLabel = "Docker Credentials" - -// SetCredsLabel is a simple setter for CredsLabel -func SetCredsLabel(label string) { - CredsLabel = label -} - -// Serve initializes the credentials helper and parses the action argument. -// This function is designed to be called from a command line interface. -// It uses os.Args[1] as the key for the action. -// It uses os.Stdin as input and os.Stdout as output. -// This function terminates the program with os.Exit(1) if there is an error. -func Serve(helper Helper) { - var err error - if len(os.Args) != 2 { - err = fmt.Errorf("Usage: %s ", os.Args[0]) - } - - if err == nil { - err = HandleCommand(helper, os.Args[1], os.Stdin, os.Stdout) - } - - if err != nil { - fmt.Fprintf(os.Stdout, "%v\n", err) - os.Exit(1) - } -} - -// HandleCommand uses a helper and a key to run a credential action. -func HandleCommand(helper Helper, key string, in io.Reader, out io.Writer) error { - switch key { - case "store": - return Store(helper, in) - case "get": - return Get(helper, in, out) - case "erase": - return Erase(helper, in) - case "list": - return List(helper, out) - case "version": - return PrintVersion(out) - } - return fmt.Errorf("Unknown credential action `%s`", key) -} - -// Store uses a helper and an input reader to save credentials. -// The reader must contain the JSON serialization of a Credentials struct. -func Store(helper Helper, reader io.Reader) error { - scanner := bufio.NewScanner(reader) - - buffer := new(bytes.Buffer) - for scanner.Scan() { - buffer.Write(scanner.Bytes()) - } - - if err := scanner.Err(); err != nil && err != io.EOF { - return err - } - - var creds Credentials - if err := json.NewDecoder(buffer).Decode(&creds); err != nil { - return err - } - - if ok, err := creds.isValid(); !ok { - return err - } - - return helper.Add(&creds) -} - -// Get retrieves the credentials for a given server url. -// The reader must contain the server URL to search. -// The writer is used to write the JSON serialization of the credentials. -func Get(helper Helper, reader io.Reader, writer io.Writer) error { - scanner := bufio.NewScanner(reader) - - buffer := new(bytes.Buffer) - for scanner.Scan() { - buffer.Write(scanner.Bytes()) - } - - if err := scanner.Err(); err != nil && err != io.EOF { - return err - } - - serverURL := strings.TrimSpace(buffer.String()) - if len(serverURL) == 0 { - return NewErrCredentialsMissingServerURL() - } - - username, secret, err := helper.Get(serverURL) - if err != nil { - return err - } - - resp := Credentials{ - ServerURL: serverURL, - Username: username, - Secret: secret, - } - - buffer.Reset() - if err := json.NewEncoder(buffer).Encode(resp); err != nil { - return err - } - - fmt.Fprint(writer, buffer.String()) - return nil -} - -// Erase removes credentials from the store. -// The reader must contain the server URL to remove. -func Erase(helper Helper, reader io.Reader) error { - scanner := bufio.NewScanner(reader) - - buffer := new(bytes.Buffer) - for scanner.Scan() { - buffer.Write(scanner.Bytes()) - } - - if err := scanner.Err(); err != nil && err != io.EOF { - return err - } - - serverURL := strings.TrimSpace(buffer.String()) - if len(serverURL) == 0 { - return NewErrCredentialsMissingServerURL() - } - - return helper.Delete(serverURL) -} - -// List returns all the serverURLs of keys in -// the OS store as a list of strings -func List(helper Helper, writer io.Writer) error { - accts, err := helper.List() - if err != nil { - return err - } - return json.NewEncoder(writer).Encode(accts) -} - -// PrintVersion outputs the current version. -func PrintVersion(writer io.Writer) error { - fmt.Fprintf(writer, "%s (%s) %s\n", Name, Package, Version) - return nil -} diff --git a/vendor/github.com/docker/docker-credential-helpers/credentials/error.go b/vendor/github.com/docker/docker-credential-helpers/credentials/error.go deleted file mode 100644 index fe6a5aef4..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/credentials/error.go +++ /dev/null @@ -1,102 +0,0 @@ -package credentials - -const ( - // ErrCredentialsNotFound standardizes the not found error, so every helper returns - // the same message and docker can handle it properly. - errCredentialsNotFoundMessage = "credentials not found in native keychain" - - // ErrCredentialsMissingServerURL and ErrCredentialsMissingUsername standardize - // invalid credentials or credentials management operations - errCredentialsMissingServerURLMessage = "no credentials server URL" - errCredentialsMissingUsernameMessage = "no credentials username" -) - -// errCredentialsNotFound represents an error -// raised when credentials are not in the store. -type errCredentialsNotFound struct{} - -// Error returns the standard error message -// for when the credentials are not in the store. -func (errCredentialsNotFound) Error() string { - return errCredentialsNotFoundMessage -} - -// NewErrCredentialsNotFound creates a new error -// for when the credentials are not in the store. -func NewErrCredentialsNotFound() error { - return errCredentialsNotFound{} -} - -// IsErrCredentialsNotFound returns true if the error -// was caused by not having a set of credentials in a store. -func IsErrCredentialsNotFound(err error) bool { - _, ok := err.(errCredentialsNotFound) - return ok -} - -// IsErrCredentialsNotFoundMessage returns true if the error -// was caused by not having a set of credentials in a store. -// -// This function helps to check messages returned by an -// external program via its standard output. -func IsErrCredentialsNotFoundMessage(err string) bool { - return err == errCredentialsNotFoundMessage -} - -// errCredentialsMissingServerURL represents an error raised -// when the credentials object has no server URL or when no -// server URL is provided to a credentials operation requiring -// one. -type errCredentialsMissingServerURL struct{} - -func (errCredentialsMissingServerURL) Error() string { - return errCredentialsMissingServerURLMessage -} - -// errCredentialsMissingUsername represents an error raised -// when the credentials object has no username or when no -// username is provided to a credentials operation requiring -// one. -type errCredentialsMissingUsername struct{} - -func (errCredentialsMissingUsername) Error() string { - return errCredentialsMissingUsernameMessage -} - -// NewErrCredentialsMissingServerURL creates a new error for -// errCredentialsMissingServerURL. -func NewErrCredentialsMissingServerURL() error { - return errCredentialsMissingServerURL{} -} - -// NewErrCredentialsMissingUsername creates a new error for -// errCredentialsMissingUsername. -func NewErrCredentialsMissingUsername() error { - return errCredentialsMissingUsername{} -} - -// IsCredentialsMissingServerURL returns true if the error -// was an errCredentialsMissingServerURL. -func IsCredentialsMissingServerURL(err error) bool { - _, ok := err.(errCredentialsMissingServerURL) - return ok -} - -// IsCredentialsMissingServerURLMessage checks for an -// errCredentialsMissingServerURL in the error message. -func IsCredentialsMissingServerURLMessage(err string) bool { - return err == errCredentialsMissingServerURLMessage -} - -// IsCredentialsMissingUsername returns true if the error -// was an errCredentialsMissingUsername. -func IsCredentialsMissingUsername(err error) bool { - _, ok := err.(errCredentialsMissingUsername) - return ok -} - -// IsCredentialsMissingUsernameMessage checks for an -// errCredentialsMissingUsername in the error message. -func IsCredentialsMissingUsernameMessage(err string) bool { - return err == errCredentialsMissingUsernameMessage -} diff --git a/vendor/github.com/docker/docker-credential-helpers/credentials/helper.go b/vendor/github.com/docker/docker-credential-helpers/credentials/helper.go deleted file mode 100644 index 135acd254..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/credentials/helper.go +++ /dev/null @@ -1,14 +0,0 @@ -package credentials - -// Helper is the interface a credentials store helper must implement. -type Helper interface { - // Add appends credentials to the store. - Add(*Credentials) error - // Delete removes credentials from the store. - Delete(serverURL string) error - // Get retrieves credentials from the store. - // It returns username and secret as strings. - Get(serverURL string) (string, string, error) - // List returns the stored serverURLs and their associated usernames. - List() (map[string]string, error) -} diff --git a/vendor/github.com/docker/docker-credential-helpers/credentials/version.go b/vendor/github.com/docker/docker-credential-helpers/credentials/version.go deleted file mode 100644 index 84377c263..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/credentials/version.go +++ /dev/null @@ -1,16 +0,0 @@ -package credentials - -var ( - // Name is filled at linking time - Name = "" - - // Package is filled at linking time - Package = "github.com/docker/docker-credential-helpers" - - // Version holds the complete version number. Filled in at linking time. - Version = "v0.0.0+unknown" - - // Revision is filled with the VCS (e.g. git) revision being used to build - // the program at linking time. - Revision = "" -) diff --git a/vendor/github.com/docker/docker/AUTHORS b/vendor/github.com/docker/docker/AUTHORS deleted file mode 100644 index b31418192..000000000 --- a/vendor/github.com/docker/docker/AUTHORS +++ /dev/null @@ -1,2390 +0,0 @@ -# File @generated by hack/generate-authors.sh. DO NOT EDIT. -# This file lists all contributors to the repository. -# See hack/generate-authors.sh to make modifications. - -Aanand Prasad -Aaron Davidson -Aaron Feng -Aaron Hnatiw -Aaron Huslage -Aaron L. Xu -Aaron Lehmann -Aaron Welch -Abel Muiño -Abhijeet Kasurde -Abhinandan Prativadi -Abhinav Ajgaonkar -Abhishek Chanda -Abhishek Sharma -Abin Shahab -Abirdcfly -Ada Mancini -Adam Avilla -Adam Dobrawy -Adam Eijdenberg -Adam Kunk -Adam Miller -Adam Mills -Adam Pointer -Adam Singer -Adam Walz -Adam Williams -AdamKorcz -Addam Hardy -Aditi Rajagopal -Aditya -Adnan Khan -Adolfo Ochagavía -Adria Casas -Adrian Moisey -Adrian Mouat -Adrian Oprea -Adrien Folie -Adrien Gallouët -Ahmed Kamal -Ahmet Alp Balkan -Aidan Feldman -Aidan Hobson Sayers -AJ Bowen -Ajey Charantimath -ajneu -Akash Gupta -Akhil Mohan -Akihiro Matsushima -Akihiro Suda -Akim Demaille -Akira Koyasu -Akshay Karle -Akshay Moghe -Al Tobey -alambike -Alan Hoyle -Alan Scherger -Alan Thompson -Albert Callarisa -Albert Zhang -Albin Kerouanton -Alec Benson -Alejandro González Hevia -Aleksa Sarai -Aleksandr Chebotov -Aleksandrs Fadins -Alena Prokharchyk -Alessandro Boch -Alessio Biancalana -Alex Chan -Alex Chen -Alex Coventry -Alex Crawford -Alex Ellis -Alex Gaynor -Alex Goodman -Alex Nordlund -Alex Olshansky -Alex Samorukov -Alex Stockinger -Alex Warhawk -Alexander Artemenko -Alexander Boyd -Alexander Larsson -Alexander Midlash -Alexander Morozov -Alexander Polakov -Alexander Shopov -Alexandre Beslic -Alexandre Garnier -Alexandre González -Alexandre Jomin -Alexandru Sfirlogea -Alexei Margasov -Alexey Guskov -Alexey Kotlyarov -Alexey Shamrin -Alexis Ries -Alexis Thomas -Alfred Landrum -Ali Dehghani -Alicia Lauerman -Alihan Demir -Allen Madsen -Allen Sun -almoehi -Alvaro Saurin -Alvin Deng -Alvin Richards -amangoel -Amen Belayneh -Ameya Gawde -Amir Goldstein -Amit Bakshi -Amit Krishnan -Amit Shukla -Amr Gawish -Amy Lindburg -Anand Patil -AnandkumarPatel -Anatoly Borodin -Anca Iordache -Anchal Agrawal -Anda Xu -Anders Janmyr -Andre Dublin <81dublin@gmail.com> -Andre Granovsky -Andrea Denisse Gómez -Andrea Luzzardi -Andrea Turli -Andreas Elvers -Andreas Köhler -Andreas Savvides -Andreas Tiefenthaler -Andrei Gherzan -Andrei Ushakov -Andrei Vagin -Andrew C. Bodine -Andrew Clay Shafer -Andrew Duckworth -Andrew France -Andrew Gerrand -Andrew Guenther -Andrew He -Andrew Hsu -Andrew Kim -Andrew Kuklewicz -Andrew Macgregor -Andrew Macpherson -Andrew Martin -Andrew McDonnell -Andrew Munsell -Andrew Pennebaker -Andrew Po -Andrew Weiss -Andrew Williams -Andrews Medina -Andrey Kolomentsev -Andrey Petrov -Andrey Stolbovsky -André Martins -Andy Chambers -andy diller -Andy Goldstein -Andy Kipp -Andy Lindeman -Andy Rothfusz -Andy Smith -Andy Wilson -Andy Zhang -Anes Hasicic -Angel Velazquez -Anil Belur -Anil Madhavapeddy -Ankit Jain -Ankush Agarwal -Anonmily -Anran Qiao -Anshul Pundir -Anthon van der Neut -Anthony Baire -Anthony Bishopric -Anthony Dahanne -Anthony Sottile -Anton Löfgren -Anton Nikitin -Anton Polonskiy -Anton Tiurin -Antonio Murdaca -Antonis Kalipetis -Antony Messerli -Anuj Bahuguna -Anuj Varma -Anusha Ragunathan -Anyu Wang -apocas -Arash Deshmeh -arcosx -ArikaChen -Arko Dasgupta -Arnaud Lefebvre -Arnaud Porterie -Arnaud Rebillout -Artem Khramov -Arthur Barr -Arthur Gautier -Artur Meyster -Arun Gupta -Asad Saeeduddin -Asbjørn Enge -Austin Vazquez -averagehuman -Avi Das -Avi Kivity -Avi Miller -Avi Vaid -ayoshitake -Azat Khuyiyakhmetov -Bao Yonglei -Bardia Keyoumarsi -Barnaby Gray -Barry Allard -Bartłomiej Piotrowski -Bastiaan Bakker -Bastien Pascard -bdevloed -Bearice Ren -Ben Bonnefoy -Ben Firshman -Ben Golub -Ben Gould -Ben Hall -Ben Langfeld -Ben Sargent -Ben Severson -Ben Toews -Ben Wiklund -Benjamin Atkin -Benjamin Baker -Benjamin Boudreau -Benjamin Böhmke -Benjamin Wang -Benjamin Yolken -Benny Ng -Benoit Chesneau -Bernerd Schaefer -Bernhard M. Wiedemann -Bert Goethals -Bertrand Roussel -Bevisy Zhang -Bharath Thiruveedula -Bhiraj Butala -Bhumika Bayani -Bilal Amarni -Bill Wang -Billy Ridgway -Bily Zhang -Bin Liu -Bingshen Wang -Bjorn Neergaard -Blake Geno -Boaz Shuster -bobby abbott -Bojun Zhu -Boqin Qin -Boris Pruessmann -Boshi Lian -Bouke Haarsma -Boyd Hemphill -boynux -Bradley Cicenas -Bradley Wright -Brandon Liu -Brandon Philips -Brandon Rhodes -Brendan Dixon -Brent Salisbury -Brett Higgins -Brett Kochendorfer -Brett Milford -Brett Randall -Brian (bex) Exelbierd -Brian Bland -Brian DeHamer -Brian Dorsey -Brian Flad -Brian Goff -Brian McCallister -Brian Olsen -Brian Schwind -Brian Shumate -Brian Torres-Gil -Brian Trump -Brice Jaglin -Briehan Lombaard -Brielle Broder -Bruno Bigras -Bruno Binet -Bruno Gazzera -Bruno Renié -Bruno Tavares -Bryan Bess -Bryan Boreham -Bryan Matsuo -Bryan Murphy -Burke Libbey -Byung Kang -Caleb Spare -Calen Pennington -Cameron Boehmer -Cameron Sparr -Cameron Spear -Campbell Allen -Candid Dauth -Cao Weiwei -Carl Henrik Lunde -Carl Loa Odin -Carl X. Su -Carlo Mion -Carlos Alexandro Becker -Carlos de Paula -Carlos Sanchez -Carol Fager-Higgins -Cary -Casey Bisson -Catalin Pirvu -Ce Gao -Cedric Davies -Cezar Sa Espinola -Chad Swenson -Chance Zibolski -Chander Govindarajan -Chanhun Jeong -Chao Wang -Charles Chan -Charles Hooper -Charles Law -Charles Lindsay -Charles Merriam -Charles Sarrazin -Charles Smith -Charlie Drage -Charlie Lewis -Chase Bolt -ChaYoung You -Chee Hau Lim -Chen Chao -Chen Chuanliang -Chen Hanxiao -Chen Min -Chen Mingjie -Chen Qiu -Cheng-mean Liu -Chengfei Shang -Chengguang Xu -Chenyang Yan -chenyuzhu -Chetan Birajdar -Chewey -Chia-liang Kao -chli -Cholerae Hu -Chris Alfonso -Chris Armstrong -Chris Dias -Chris Dituri -Chris Fordham -Chris Gavin -Chris Gibson -Chris Khoo -Chris Kreussling (Flatbush Gardener) -Chris McKinnel -Chris McKinnel -Chris Price -Chris Seto -Chris Snow -Chris St. Pierre -Chris Stivers -Chris Swan -Chris Telfer -Chris Wahl -Chris Weyl -Chris White -Christian Becker -Christian Berendt -Christian Brauner -Christian Böhme -Christian Muehlhaeuser -Christian Persson -Christian Rotzoll -Christian Simon -Christian Stefanescu -Christoph Ziebuhr -Christophe Mehay -Christophe Troestler -Christophe Vidal -Christopher Biscardi -Christopher Crone -Christopher Currie -Christopher Jones -Christopher Latham -Christopher Rigor -Christy Norman -Chun Chen -Ciro S. Costa -Clayton Coleman -Clint Armstrong -Clinton Kitson -clubby789 -Cody Roseborough -Coenraad Loubser -Colin Dunklau -Colin Hebert -Colin Panisset -Colin Rice -Colin Walters -Collin Guarino -Colm Hally -companycy -Conor Evans -Corbin Coleman -Corey Farrell -Cory Forsyth -Cory Snider -cressie176 -Cristian Ariza -Cristian Staretu -cristiano balducci -Cristina Yenyxe Gonzalez Garcia -Cruceru Calin-Cristian -CUI Wei -cuishuang -Cuong Manh Le -Cyprian Gracz -Cyril F -Da McGrady -Daan van Berkel -Daehyeok Mun -Dafydd Crosby -dalanlan -Damian Smyth -Damien Nadé -Damien Nozay -Damjan Georgievski -Dan Anolik -Dan Buch -Dan Cotora -Dan Feldman -Dan Griffin -Dan Hirsch -Dan Keder -Dan Levy -Dan McPherson -Dan Plamadeala -Dan Stine -Dan Williams -Dani Hodovic -Dani Louca -Daniel Antlinger -Daniel Black -Daniel Dao -Daniel Exner -Daniel Farrell -Daniel Garcia -Daniel Gasienica -Daniel Grunwell -Daniel Helfand -Daniel Hiltgen -Daniel J Walsh -Daniel Menet -Daniel Mizyrycki -Daniel Nephin -Daniel Norberg -Daniel Nordberg -Daniel P. Berrangé -Daniel Robinson -Daniel S -Daniel Sweet -Daniel Von Fange -Daniel Watkins -Daniel X Moore -Daniel YC Lin -Daniel Zhang -Daniele Rondina -Danny Berger -Danny Milosavljevic -Danny Yates -Danyal Khaliq -Darren Coxall -Darren Shepherd -Darren Stahl -Dattatraya Kumbhar -Davanum Srinivas -Dave Barboza -Dave Goodchild -Dave Henderson -Dave MacDonald -Dave Tucker -David Anderson -David Bellotti -David Calavera -David Chung -David Corking -David Cramer -David Currie -David Davis -David Dooling -David Gageot -David Gebler -David Glasser -David Lawrence -David Lechner -David M. Karr -David Mackey -David Manouchehri -David Mat -David Mcanulty -David McKay -David O'Rourke -David P Hilton -David Pelaez -David R. Jenni -David Röthlisberger -David Sheets -David Sissitka -David Trott -David Wang <00107082@163.com> -David Williamson -David Xia -David Young -Davide Ceretti -Dawn Chen -dbdd -dcylabs -Debayan De -Deborah Gertrude Digges -deed02392 -Deep Debroy -Deng Guangxing -Deni Bertovic -Denis Defreyne -Denis Gladkikh -Denis Ollier -Dennis Chen -Dennis Chen -Dennis Docter -Derek -Derek -Derek Ch -Derek McGowan -Deric Crago -Deshi Xiao -Devon Estes -Devvyn Murphy -Dharmit Shah -Dhawal Yogesh Bhanushali -Dhilip Kumars -Diego Romero -Diego Siqueira -Dieter Reuter -Dillon Dixon -Dima Stopel -Dimitri John Ledkov -Dimitris Mandalidis -Dimitris Rozakis -Dimitry Andric -Dinesh Subhraveti -Ding Fei -dingwei -Diogo Monica -DiuDiugirl -Djibril Koné -Djordje Lukic -dkumor -Dmitri Logvinenko -Dmitri Shuralyov -Dmitry Demeshchuk -Dmitry Gusev -Dmitry Kononenko -Dmitry Sharshakov -Dmitry Shyshkin -Dmitry Smirnov -Dmitry V. Krivenok -Dmitry Vorobev -Dmytro Iakovliev -docker-unir[bot] -Dolph Mathews -Dominic Tubach -Dominic Yin -Dominik Dingel -Dominik Finkbeiner -Dominik Honnef -Don Kirkby -Don Kjer -Don Spaulding -Donald Huang -Dong Chen -Donghwa Kim -Donovan Jones -Doron Podoleanu -Doug Davis -Doug MacEachern -Doug Tangren -Douglas Curtis -Dr Nic Williams -dragon788 -Dražen Lučanin -Drew Erny -Drew Hubl -Dustin Sallings -Ed Costello -Edmund Wagner -Eiichi Tsukata -Eike Herzbach -Eivin Giske Skaaren -Eivind Uggedal -Elan Ruusamäe -Elango Sivanandam -Elena Morozova -Eli Uriegas -Elias Faxö -Elias Koromilas -Elias Probst -Elijah Zupancic -eluck -Elvir Kuric -Emil Davtyan -Emil Hernvall -Emily Maier -Emily Rose -Emir Ozer -Eng Zer Jun -Enguerran -Eohyung Lee -epeterso -er0k -Eric Barch -Eric Curtin -Eric G. Noriega -Eric Hanchrow -Eric Lee -Eric Mountain -Eric Myhre -Eric Paris -Eric Rafaloff -Eric Rosenberg -Eric Sage -Eric Soderstrom -Eric Yang -Eric-Olivier Lamey -Erica Windisch -Erich Cordoba -Erik Bray -Erik Dubbelboer -Erik Hollensbe -Erik Inge Bolsø -Erik Kristensen -Erik Sipsma -Erik St. Martin -Erik Weathers -Erno Hopearuoho -Erwin van der Koogh -Espen Suenson -Ethan Bell -Ethan Mosbaugh -Euan Harris -Euan Kemp -Eugen Krizo -Eugene Yakubovich -Evan Allrich -Evan Carmi -Evan Hazlett -Evan Krall -Evan Phoenix -Evan Wies -Evelyn Xu -Everett Toews -Evgeniy Makhrov -Evgeny Shmarnev -Evgeny Vereshchagin -Ewa Czechowska -Eystein Måløy Stenberg -ezbercih -Ezra Silvera -Fabian Kramm -Fabian Lauer -Fabian Raetz -Fabiano Rosas -Fabio Falci -Fabio Kung -Fabio Rapposelli -Fabio Rehm -Fabrizio Regini -Fabrizio Soppelsa -Faiz Khan -falmp -Fangming Fang -Fangyuan Gao <21551127@zju.edu.cn> -fanjiyun -Fareed Dudhia -Fathi Boudra -Federico Gimenez -Felipe Oliveira -Felipe Ruhland -Felix Abecassis -Felix Geisendörfer -Felix Hupfeld -Felix Rabe -Felix Ruess -Felix Schindler -Feng Yan -Fengtu Wang -Ferenc Szabo -Fernando -Fero Volar -Feroz Salam -Ferran Rodenas -Filipe Brandenburger -Filipe Oliveira -Flavio Castelli -Flavio Crisciani -Florian -Florian Klein -Florian Maier -Florian Noeding -Florian Schmaus -Florian Weingarten -Florin Asavoaie -Florin Patan -fonglh -Foysal Iqbal -Francesc Campoy -Francesco Degrassi -Francesco Mari -Francis Chuang -Francisco Carriedo -Francisco Souza -Frank Groeneveld -Frank Herrmann -Frank Macreery -Frank Rosquin -Frank Yang -Fred Lifton -Frederick F. Kautz IV -Frederico F. de Oliveira -Frederik Loeffert -Frederik Nordahl Jul Sabroe -Freek Kalter -Frieder Bluemle -frobnicaty <92033765+frobnicaty@users.noreply.github.com> -Frédéric Dalleau -Fu JinLin -Félix Baylac-Jacqué -Félix Cantournet -Gabe Rosenhouse -Gabor Nagy -Gabriel Adrian Samfira -Gabriel Goller -Gabriel L. Somlo -Gabriel Linder -Gabriel Monroy -Gabriel Nicolas Avellaneda -Gaetan de Villele -Galen Sampson -Gang Qiao -Gareth Rushgrove -Garrett Barboza -Gary Schaetz -Gaurav -Gaurav Singh -Gaël PORTAY -Genki Takiuchi -GennadySpb -Geoff Levand -Geoffrey Bachelet -Geon Kim -George Kontridze -George MacRorie -George Xie -Georgi Hristozov -Georgy Yakovlev -Gereon Frey -German DZ -Gert van Valkenhoef -Gerwim Feiken -Ghislain Bourgeois -Giampaolo Mancini -Gianluca Borello -Gildas Cuisinier -Giovan Isa Musthofa -gissehel -Giuseppe Mazzotta -Giuseppe Scrivano -Gleb Fotengauer-Malinovskiy -Gleb M Borisov -Glyn Normington -GoBella -Goffert van Gool -Goldwyn Rodrigues -Gopikannan Venugopalsamy -Gosuke Miyashita -Gou Rao -Govinda Fichtner -Grant Millar -Grant Reaber -Graydon Hoare -Greg Fausak -Greg Pflaum -Greg Stephens -Greg Thornton -Grzegorz Jaśkiewicz -Guilhem Lettron -Guilherme Salgado -Guillaume Dufour -Guillaume J. Charmes -Gunadhya S. <6939749+gunadhya@users.noreply.github.com> -Guoqiang QI -guoxiuyan -Guri -Gurjeet Singh -Guruprasad -Gustav Sinder -gwx296173 -Günter Zöchbauer -Haichao Yang -haikuoliu -haining.cao -Hakan Özler -Hamish Hutchings -Hannes Ljungberg -Hans Kristian Flaatten -Hans Rødtang -Hao Shu Wei -Hao Zhang <21521210@zju.edu.cn> -Harald Albers -Harald Niesche -Harley Laue -Harold Cooper -Harrison Turton -Harry Zhang -Harshal Patil -Harshal Patil -He Simei -He Xiaoxi -He Xin -heartlock <21521209@zju.edu.cn> -Hector Castro -Helen Xie -Henning Sprang -Hiroshi Hatake -Hiroyuki Sasagawa -Hobofan -Hollie Teal -Hong Xu -Hongbin Lu -Hongxu Jia -Honza Pokorny -Hsing-Hui Hsu -Hsing-Yu (David) Chen -hsinko <21551195@zju.edu.cn> -Hu Keping -Hu Tao -HuanHuan Ye -Huanzhong Zhang -Huayi Zhang -Hugo Barrera -Hugo Duncan -Hugo Marisco <0x6875676f@gmail.com> -Hui Kang -Hunter Blanks -huqun -Huu Nguyen -Hyeongkyu Lee -Hyzhou Zhy -Iago López Galeiras -Ian Bishop -Ian Bull -Ian Calvert -Ian Campbell -Ian Chen -Ian Lee -Ian Main -Ian Philpot -Ian Truslove -Iavael -Icaro Seara -Ignacio Capurro -Igor Dolzhikov -Igor Karpovich -Iliana Weller -Ilkka Laukkanen -Illia Antypenko -Illo Abdulrahim -Ilya Dmitrichenko -Ilya Gusev -Ilya Khlopotov -imre Fitos -inglesp -Ingo Gottwald -Innovimax -Isaac Dupree -Isabel Jimenez -Isaiah Grace -Isao Jonas -Iskander Sharipov -Ivan Babrou -Ivan Fraixedes -Ivan Grcic -Ivan Markin -J Bruni -J. Nunn -Jack Danger Canty -Jack Laxson -Jacob Atzen -Jacob Edelman -Jacob Tomlinson -Jacob Vallejo -Jacob Wen -Jaime Cepeda -Jaivish Kothari -Jake Champlin -Jake Moshenko -Jake Sanders -Jakub Drahos -Jakub Guzik -James Allen -James Carey -James Carr -James DeFelice -James Harrison Fisher -James Kyburz -James Kyle -James Lal -James Mills -James Nesbitt -James Nugent -James Sanders -James Turnbull -James Watkins-Harvey -Jamie Hannaford -Jamshid Afshar -Jan Breig -Jan Chren -Jan Garcia -Jan Götte -Jan Keromnes -Jan Koprowski -Jan Pazdziora -Jan Toebes -Jan-Gerd Tenberge -Jan-Jaap Driessen -Jana Radhakrishnan -Jannick Fahlbusch -Januar Wayong -Jared Biel -Jared Hocutt -Jaroslaw Zabiello -Jasmine Hegman -Jason A. Donenfeld -Jason Divock -Jason Giedymin -Jason Green -Jason Hall -Jason Heiss -Jason Livesay -Jason McVetta -Jason Plum -Jason Shepherd -Jason Smith -Jason Sommer -Jason Stangroome -Javier Bassi -jaxgeller -Jay -Jay Kamat -Jay Lim -Jean Rouge -Jean-Baptiste Barth -Jean-Baptiste Dalido -Jean-Christophe Berthon -Jean-Paul Calderone -Jean-Pierre Huynh -Jean-Tiare Le Bigot -Jeeva S. Chelladhurai -Jeff Anderson -Jeff Hajewski -Jeff Johnston -Jeff Lindsay -Jeff Mickey -Jeff Minard -Jeff Nickoloff -Jeff Silberman -Jeff Welch -Jeff Zvier -Jeffrey Bolle -Jeffrey Morgan -Jeffrey van Gogh -Jenny Gebske -Jeremy Chambers -Jeremy Grosser -Jeremy Huntwork -Jeremy Price -Jeremy Qian -Jeremy Unruh -Jeremy Yallop -Jeroen Franse -Jeroen Jacobs -Jesse Dearing -Jesse Dubay -Jessica Frazelle -Jezeniel Zapanta -Jhon Honce -Ji.Zhilong -Jian Liao -Jian Zhang -Jiang Jinyang -Jianyong Wu -Jie Luo -Jie Ma -Jihyun Hwang -Jilles Oldenbeuving -Jim Alateras -Jim Carroll -Jim Ehrismann -Jim Galasyn -Jim Lin -Jim Minter -Jim Perrin -Jimmy Cuadra -Jimmy Puckett -Jimmy Song -Jinsoo Park -Jintao Zhang -Jiri Appl -Jiri Popelka -Jiuyue Ma -Jiří Župka -Joakim Roubert -Joao Fernandes -Joao Trindade -Joe Beda -Joe Doliner -Joe Ferguson -Joe Gordon -Joe Shaw -Joe Van Dyk -Joel Friedly -Joel Handwell -Joel Hansson -Joel Wurtz -Joey Geiger -Joey Geiger -Joey Gibson -Joffrey F -Johan Euphrosine -Johan Rydberg -Johanan Lieberman -Johannes 'fish' Ziemke -John Costa -John Feminella -John Gardiner Myers -John Gossman -John Harris -John Howard -John Laswell -John Maguire -John Mulhausen -John OBrien III -John Starks -John Stephens -John Tims -John V. Martinez -John Warwick -John Willis -Jon Johnson -Jon Surrell -Jon Wedaman -Jonas Dohse -Jonas Heinrich -Jonas Pfenniger -Jonathan A. Schweder -Jonathan A. Sternberg -Jonathan Boulle -Jonathan Camp -Jonathan Choy -Jonathan Dowland -Jonathan Lebon -Jonathan Lomas -Jonathan McCrohan -Jonathan Mueller -Jonathan Pares -Jonathan Rudenberg -Jonathan Stoppani -Jonh Wendell -Joni Sar -Joost Cassee -Jordan Arentsen -Jordan Jennings -Jordan Sissel -Jordi Massaguer Pla -Jorge Marin -Jorit Kleine-Möllhoff -Jose Diaz-Gonzalez -Joseph Anthony Pasquale Holsten -Joseph Hager -Joseph Kern -Joseph Rothrock -Josh -Josh Bodah -Josh Bonczkowski -Josh Chorlton -Josh Eveleth -Josh Hawn -Josh Horwitz -Josh Poimboeuf -Josh Soref -Josh Wilson -Josiah Kiehl -José Tomás Albornoz -Joyce Jang -JP -Julian Taylor -Julien Barbier -Julien Bisconti -Julien Bordellier -Julien Dubois -Julien Kassar -Julien Maitrehenry -Julien Pervillé -Julien Pivotto -Julio Guerra -Julio Montes -Jun Du -Jun-Ru Chang -junxu -Jussi Nummelin -Justas Brazauskas -Justen Martin -Justin Cormack -Justin Force -Justin Keller <85903732+jk-vb@users.noreply.github.com> -Justin Menga -Justin Plock -Justin Simonelis -Justin Terry -Justyn Temme -Jyrki Puttonen -Jérémy Leherpeur -Jérôme Petazzoni -Jörg Thalheim -K. Heller -Kai Blin -Kai Qiang Wu (Kennan) -Kaijie Chen -Kamil Domański -Kamjar Gerami -Kanstantsin Shautsou -Kara Alexandra -Karan Lyons -Kareem Khazem -kargakis -Karl Grzeszczak -Karol Duleba -Karthik Karanth -Karthik Nayak -Kasper Fabæch Brandt -Kate Heddleston -Katie McLaughlin -Kato Kazuyoshi -Katrina Owen -Kawsar Saiyeed -Kay Yan -kayrus -Kazuhiro Sera -Kazuyoshi Kato -Ke Li -Ke Xu -Kei Ohmura -Keith Hudgins -Keli Hu -Ken Cochrane -Ken Herner -Ken ICHIKAWA -Ken Reese -Kenfe-Mickaël Laventure -Kenjiro Nakayama -Kent Johnson -Kenta Tada -Kevin "qwazerty" Houdebert -Kevin Alvarez -Kevin Burke -Kevin Clark -Kevin Feyrer -Kevin J. Lynagh -Kevin Jing Qiu -Kevin Kern -Kevin Menard -Kevin Meredith -Kevin P. Kucharczyk -Kevin Parsons -Kevin Richardson -Kevin Shi -Kevin Wallace -Kevin Yap -Keyvan Fatehi -kies -Kim BKC Carlbacker -Kim Eik -Kimbro Staken -Kir Kolyshkin -Kiran Gangadharan -Kirill SIbirev -Kirk Easterson -knappe -Kohei Tsuruta -Koichi Shiraishi -Konrad Kleine -Konrad Ponichtera -Konstantin Gribov -Konstantin L -Konstantin Pelykh -Kostadin Plachkov -Krasi Georgiev -Krasimir Georgiev -Kris-Mikael Krister -Kristian Haugene -Kristina Zabunova -Krystian Wojcicki -Kunal Kushwaha -Kunal Tyagi -Kyle Conroy -Kyle Linden -Kyle Squizzato -Kyle Wuolle -kyu -Lachlan Coote -Lai Jiangshan -Lajos Papp -Lakshan Perera -Lalatendu Mohanty -Lance Chen -Lance Kinley -Lars Butler -Lars Kellogg-Stedman -Lars R. Damerow -Lars-Magnus Skog -Laszlo Meszaros -Laura Brehm -Laura Frank -Laurent Bernaille -Laurent Erignoux -Laurie Voss -Leandro Motta Barros -Leandro Siqueira -Lee Calcote -Lee Chao <932819864@qq.com> -Lee, Meng-Han -Lei Gong -Lei Jitang -Leiiwang -Len Weincier -Lennie -Leo Gallucci -Leonardo Nodari -Leonardo Taccari -Leszek Kowalski -Levi Blackstone -Levi Gross -Levi Harrison -Lewis Daly -Lewis Marshall -Lewis Peckover -Li Yi -Liam Macgillavry -Liana Lo -Liang Mingqiang -Liang-Chi Hsieh -liangwei -Liao Qingwei -Lifubang -Lihua Tang -Lily Guo -limeidan -Lin Lu -LingFaKe -Linus Heckemann -Liran Tal -Liron Levin -Liu Bo -Liu Hua -liwenqi -lixiaobing10051267 -Liz Zhang -LIZAO LI -Lizzie Dixon <_@lizzie.io> -Lloyd Dewolf -Lokesh Mandvekar -longliqiang88 <394564827@qq.com> -Lorenz Leutgeb -Lorenzo Fontana -Lotus Fenn -Louis Delossantos -Louis Opter -Luca Favatella -Luca Marturana -Luca Orlandi -Luca-Bogdan Grigorescu -Lucas Chan -Lucas Chi -Lucas Molas -Lucas Silvestre -Luciano Mores -Luis Henrique Mulinari -Luis Martínez de Bartolomé Izquierdo -Luiz Svoboda -Lukas Heeren -Lukas Waslowski -lukaspustina -Lukasz Zajaczkowski -Luke Marsden -Lyn -Lynda O'Leary -Lénaïc Huard -Ma Müller -Ma Shimiao -Mabin -Madhan Raj Mookkandy -Madhav Puri -Madhu Venugopal -Mageee -Mahesh Tiyyagura -malnick -Malte Janduda -Manfred Touron -Manfred Zabarauskas -Manjunath A Kumatagi -Mansi Nahar -Manuel Meurer -Manuel Rüger -Manuel Woelker -mapk0y -Marc Abramowitz -Marc Kuo -Marc Tamsky -Marcel Edmund Franke -Marcelo Horacio Fortino -Marcelo Salazar -Marco Hennings -Marcus Cobden -Marcus Farkas -Marcus Linke -Marcus Martins -Marcus Ramberg -Marek Goldmann -Marian Marinov -Marianna Tessel -Mario Loriedo -Marius Gundersen -Marius Sturm -Marius Voila -Mark Allen -Mark Feit -Mark Jeromin -Mark McGranaghan -Mark McKinstry -Mark Milstein -Mark Oates -Mark Parker -Mark Vainomaa -Mark West -Markan Patel -Marko Mikulicic -Marko Tibold -Markus Fix -Markus Kortlang -Martijn Dwars -Martijn van Oosterhout -Martin Braun -Martin Dojcak -Martin Honermeyer -Martin Kelly -Martin Mosegaard Amdisen -Martin Muzatko -Martin Redmond -Maru Newby -Mary Anthony -Masahito Zembutsu -Masato Ohba -Masayuki Morita -Mason Malone -Mateusz Sulima -Mathias Monnerville -Mathieu Champlon -Mathieu Le Marec - Pasquet -Mathieu Parent -Mathieu Paturel -Matt Apperson -Matt Bachmann -Matt Bajor -Matt Bentley -Matt Haggard -Matt Hoyle -Matt McCormick -Matt Moore -Matt Morrison <3maven@gmail.com> -Matt Richardson -Matt Rickard -Matt Robenolt -Matt Schurenko -Matt Williams -Matthew Heon -Matthew Lapworth -Matthew Mayer -Matthew Mosesohn -Matthew Mueller -Matthew Riley -Matthias Klumpp -Matthias Kühnle -Matthias Rampke -Matthieu Fronton -Matthieu Hauglustaine -Mattias Jernberg -Mauricio Garavaglia -mauriyouth -Max Harmathy -Max Shytikov -Max Timchenko -Maxim Fedchyshyn -Maxim Ivanov -Maxim Kulkin -Maxim Treskin -Maxime Petazzoni -Maximiliano Maccanti -Maxwell -Meaglith Ma -meejah -Megan Kostick -Mehul Kar -Mei ChunTao -Mengdi Gao -Menghui Chen -Mert Yazıcıoğlu -mgniu -Micah Zoltu -Michael A. Smith -Michael Beskin -Michael Bridgen -Michael Brown -Michael Chiang -Michael Crosby -Michael Currie -Michael Friis -Michael Gorsuch -Michael Grauer -Michael Holzheu -Michael Hudson-Doyle -Michael Huettermann -Michael Irwin -Michael Kuehn -Michael Käufl -Michael Neale -Michael Nussbaum -Michael Prokop -Michael Scharf -Michael Spetsiotis -Michael Stapelberg -Michael Steinert -Michael Thies -Michael Weidmann -Michael West -Michael Zhao -Michal Fojtik -Michal Gebauer -Michal Jemala -Michal Kostrzewa -Michal Minář -Michal Rostecki -Michal Wieczorek -Michaël Pailloncy -Michał Czeraszkiewicz -Michał Gryko -Michał Kosek -Michiel de Jong -Mickaël Fortunato -Mickaël Remars -Miguel Angel Fernández -Miguel Morales -Miguel Perez -Mihai Borobocea -Mihuleacc Sergiu -Mikael Davranche -Mike Brown -Mike Bush -Mike Casas -Mike Chelen -Mike Danese -Mike Dillon -Mike Dougherty -Mike Estes -Mike Gaffney -Mike Goelzer -Mike Leone -Mike Lundy -Mike MacCana -Mike Naberezny -Mike Snitzer -mikelinjie <294893458@qq.com> -Mikhail Sobolev -Miklos Szegedi -Milas Bowman -Milind Chawre -Miloslav Trmač -mingqing -Mingzhen Feng -Misty Stanley-Jones -Mitch Capper -Mizuki Urushida -mlarcher -Mohammad Banikazemi -Mohammad Nasirifar -Mohammed Aaqib Ansari -Mohit Soni -Moorthy RS -Morgan Bauer -Morgante Pell -Morgy93 -Morten Siebuhr -Morton Fox -Moysés Borges -mrfly -Mrunal Patel -Muayyad Alsadi -Muhammad Zohaib Aslam -Mustafa Akın -Muthukumar R -Máximo Cuadros -Médi-Rémi Hashim -Nace Oroz -Nahum Shalman -Nakul Pathak -Nalin Dahyabhai -Nan Monnand Deng -Naoki Orii -Natalie Parker -Natanael Copa -Natasha Jarus -Nate Brennand -Nate Eagleson -Nate Jones -Nathan Carlson -Nathan Herald -Nathan Hsieh -Nathan Kleyn -Nathan LeClaire -Nathan McCauley -Nathan Williams -Naveed Jamil -Neal McBurnett -Neil Horman -Neil Peterson -Nelson Chen -Neyazul Haque -Nghia Tran -Niall O'Higgins -Nicholas E. Rabenau -Nick Adcock -Nick DeCoursin -Nick Irvine -Nick Neisen -Nick Parker -Nick Payne -Nick Russo -Nick Santos -Nick Stenning -Nick Stinemates -Nick Wood -NickrenREN -Nicola Kabar -Nicolas Borboën -Nicolas De Loof -Nicolas Dudebout -Nicolas Goy -Nicolas Kaiser -Nicolas Sterchele -Nicolas V Castet -Nicolás Hock Isaza -Niel Drummond -Nigel Poulton -Nik Nyby -Nikhil Chawla -NikolaMandic -Nikolas Garofil -Nikolay Edigaryev -Nikolay Milovanov -ningmingxiao -Nirmal Mehta -Nishant Totla -NIWA Hideyuki -Noah Meyerhans -Noah Treuhaft -NobodyOnSE -noducks -Nolan Darilek -Noriki Nakamura -nponeccop -Nurahmadie -Nuutti Kotivuori -nzwsch -O.S. Tezer -objectified -Odin Ugedal -Oguz Bilgic -Oh Jinkyun -Ohad Schneider -ohmystack -Ole Reifschneider -Oliver Neal -Oliver Reason -Olivier Gambier -Olle Jonsson -Olli Janatuinen -Olly Pomeroy -Omri Shiv -Onur Filiz -Oriol Francès -Oscar Bonilla <6f6231@gmail.com> -oscar.chen <2972789494@qq.com> -Oskar Niburski -Otto Kekäläinen -Ouyang Liduo -Ovidio Mallo -Panagiotis Moustafellos -Paolo G. Giarrusso -Pascal -Pascal Bach -Pascal Borreli -Pascal Hartig -Patrick Böänziger -Patrick Devine -Patrick Haas -Patrick Hemmer -Patrick Stapleton -Patrik Cyvoct -pattichen -Paul "TBBle" Hampson -Paul -paul -Paul Annesley -Paul Bellamy -Paul Bowsher -Paul Furtado -Paul Hammond -Paul Jimenez -Paul Kehrer -Paul Lietar -Paul Liljenberg -Paul Morie -Paul Nasrat -Paul Weaver -Paulo Gomes -Paulo Ribeiro -Pavel Lobashov -Pavel Matěja -Pavel Pletenev -Pavel Pospisil -Pavel Sutyrin -Pavel Tikhomirov -Pavlos Ratis -Pavol Vargovcik -Pawel Konczalski -Paweł Gronowski -Peeyush Gupta -Peggy Li -Pei Su -Peng Tao -Penghan Wang -Per Weijnitz -perhapszzy@sina.com -Pete Woods -Peter Bourgon -Peter Braden -Peter Bücker -Peter Choi -Peter Dave Hello -Peter Edge -Peter Ericson -Peter Esbensen -Peter Jaffe -Peter Kang -Peter Malmgren -Peter Salvatore -Peter Volpe -Peter Waller -Petr Švihlík -Petros Angelatos -Phil -Phil Estes -Phil Sphicas -Phil Spitler -Philip Alexander Etling -Philip Monroe -Philipp Gillé -Philipp Wahala -Philipp Weissensteiner -Phillip Alexander -phineas -pidster -Piergiuliano Bossi -Pierre -Pierre Carrier -Pierre Dal-Pra -Pierre Wacrenier -Pierre-Alain RIVIERE -Piotr Bogdan -Piotr Karbowski -Porjo -Poul Kjeldager Sørensen -Pradeep Chhetri -Pradip Dhara -Pradipta Kr. Banerjee -Prasanna Gautam -Pratik Karki -Prayag Verma -Priya Wadhwa -Projjol Banerji -Przemek Hejman -Puneet Pruthi -Pure White -pysqz -Qiang Huang -Qin TianHuan -Qinglan Peng -Quan Tian -qudongfang -Quentin Brossard -Quentin Perez -Quentin Tayssier -r0n22 -Radostin Stoyanov -Rafal Jeczalik -Rafe Colton -Raghavendra K T -Raghuram Devarakonda -Raja Sami -Rajat Pandit -Rajdeep Dua -Ralf Sippl -Ralle -Ralph Bean -Ramkumar Ramachandra -Ramon Brooker -Ramon van Alteren -RaviTeja Pothana -Ray Tsang -ReadmeCritic -realityone -Recursive Madman -Reficul -Regan McCooey -Remi Rampin -Remy Suen -Renato Riccieri Santos Zannon -Renaud Gaubert -Rhys Hiltner -Ri Xu -Ricardo N Feliciano -Rich Horwood -Rich Moyse -Rich Seymour -Richard Burnison -Richard Harvey -Richard Mathie -Richard Metzler -Richard Scothern -Richo Healey -Rick Bradley -Rick van de Loo -Rick Wieman -Rik Nijessen -Riku Voipio -Riley Guerin -Ritesh H Shukla -Riyaz Faizullabhoy -Rob Cowsill <42620235+rcowsill@users.noreply.github.com> -Rob Gulewich -Rob Vesse -Robert Bachmann -Robert Bittle -Robert Obryk -Robert Schneider -Robert Shade -Robert Stern -Robert Terhaar -Robert Wallis -Robert Wang -Roberto G. Hashioka -Roberto Muñoz Fernández -Robin Naundorf -Robin Schneider -Robin Speekenbrink -Robin Thoni -robpc -Rodolfo Carvalho -Rodrigo Campos -Rodrigo Vaz -Roel Van Nyen -Roger Peppe -Rohit Jnagal -Rohit Kadam -Rohit Kapur -Rojin George -Roland Huß -Roland Kammerer -Roland Moriz -Roma Sokolov -Roman Dudin -Roman Mazur -Roman Strashkin -Roman Volosatovs -Roman Zabaluev -Ron Smits -Ron Williams -Rong Gao -Rong Zhang -Rongxiang Song -Rony Weng -root -root -root -root -Rory Hunter -Rory McCune -Ross Boucher -Rovanion Luckey -Roy Reznik -Royce Remer -Rozhnov Alexandr -Rudolph Gottesheim -Rui Cao -Rui Lopes -Ruilin Li -Runshen Zhu -Russ Magee -Ryan Abrams -Ryan Anderson -Ryan Aslett -Ryan Barry -Ryan Belgrave -Ryan Campbell -Ryan Detzel -Ryan Fowler -Ryan Liu -Ryan McLaughlin -Ryan O'Donnell -Ryan Seto -Ryan Shea -Ryan Simmen -Ryan Stelly -Ryan Thomas -Ryan Trauntvein -Ryan Wallner -Ryan Zhang -ryancooper7 -RyanDeng -Ryo Nakao -Ryoga Saito -Rémy Greinhofer -s. rannou -Sabin Basyal -Sachin Joshi -Sagar Hani -Sainath Grandhi -Sakeven Jiang -Salahuddin Khan -Sally O'Malley -Sam Abed -Sam Alba -Sam Bailey -Sam J Sharpe -Sam Neirinck -Sam Reis -Sam Rijs -Sam Whited -Sambuddha Basu -Sami Wagiaalla -Samuel Andaya -Samuel Dion-Girardeau -Samuel Karp -Samuel PHAN -sanchayanghosh -Sandeep Bansal -Sankar சங்கர் -Sanket Saurav -Santhosh Manohar -sapphiredev -Sargun Dhillon -Sascha Andres -Sascha Grunert -SataQiu -Satnam Singh -Satoshi Amemiya -Satoshi Tagomori -Scott Bessler -Scott Collier -Scott Johnston -Scott Percival -Scott Stamp -Scott Walls -sdreyesg -Sean Christopherson -Sean Cronin -Sean Lee -Sean McIntyre -Sean OMeara -Sean P. Kane -Sean Rodman -Sebastiaan van Steenis -Sebastiaan van Stijn -Sebastian Höffner -Sebastian Radloff -Sebastien Goasguen -Senthil Kumar Selvaraj -Senthil Kumaran -SeongJae Park -Seongyeol Lim -Serge Hallyn -Sergey Alekseev -Sergey Evstifeev -Sergii Kabashniuk -Sergio Lopez -Serhat Gülçiçek -SeungUkLee -Sevki Hasirci -Shane Canon -Shane da Silva -Shaun Kaasten -shaunol -Shawn Landden -Shawn Siefkas -shawnhe -Shayan Pooya -Shayne Wang -Shekhar Gulati -Sheng Yang -Shengbo Song -Shengjing Zhu -Shev Yan -Shih-Yuan Lee -Shihao Xia -Shijiang Wei -Shijun Qin -Shishir Mahajan -Shoubhik Bose -Shourya Sarcar -Shu-Wai Chow -shuai-z -Shukui Yang -Sian Lerk Lau -Siarhei Rasiukevich -Sidhartha Mani -sidharthamani -Silas Sewell -Silvan Jegen -Simão Reis -Simon Barendse -Simon Eskildsen -Simon Ferquel -Simon Leinen -Simon Menke -Simon Taranto -Simon Vikstrom -Sindhu S -Sjoerd Langkemper -skanehira -Smark Meng -Solganik Alexander -Solomon Hykes -Song Gao -Soshi Katsuta -Sotiris Salloumis -Soulou -Spencer Brown -Spencer Smith -Spike Curtis -Sridatta Thatipamala -Sridhar Ratnakumar -Srini Brahmaroutu -Srinivasan Srivatsan -Staf Wagemakers -Stanislav Bondarenko -Stanislav Levin -Steeve Morin -Stefan Berger -Stefan J. Wernli -Stefan Praszalowicz -Stefan S. -Stefan Scherer -Stefan Staudenmeyer -Stefan Weil -Steffen Butzer -Stephan Spindler -Stephen Benjamin -Stephen Crosby -Stephen Day -Stephen Drake -Stephen Rust -Steve Desmond -Steve Dougherty -Steve Durrheimer -Steve Francia -Steve Koch -Steven Burgess -Steven Erenst -Steven Hartland -Steven Iveson -Steven Merrill -Steven Richards -Steven Taylor -Stéphane Este-Gracias -Stig Larsson -Su Wang -Subhajit Ghosh -Sujith Haridasan -Sun Gengze <690388648@qq.com> -Sun Jianbo -Sune Keller -Sunny Gogoi -Suryakumar Sudar -Sven Dowideit -Swapnil Daingade -Sylvain Baubeau -Sylvain Bellemare -Sébastien -Sébastien HOUZÉ -Sébastien Luttringer -Sébastien Stormacq -Sören Tempel -Tabakhase -Tadej Janež -Takuto Sato -tang0th -Tangi Colin -Tatsuki Sugiura -Tatsushi Inagaki -Taylan Isikdemir -Taylor Jones -Ted M. Young -Tehmasp Chaudhri -Tejaswini Duggaraju -Tejesh Mehta -Terry Chu -terryding77 <550147740@qq.com> -Thatcher Peskens -theadactyl -Thell 'Bo' Fowler -Thermionix -Thiago Alves Silva -Thijs Terlouw -Thomas Bikeev -Thomas Frössman -Thomas Gazagnaire -Thomas Graf -Thomas Grainger -Thomas Hansen -Thomas Ledos -Thomas Leonard -Thomas Léveil -Thomas Orozco -Thomas Riccardi -Thomas Schroeter -Thomas Sjögren -Thomas Swift -Thomas Tanaka -Thomas Texier -Ti Zhou -Tiago Seabra -Tianon Gravi -Tianyi Wang -Tibor Vass -Tiffany Jernigan -Tiffany Low -Till Claassen -Till Wegmüller -Tim -Tim Bart -Tim Bosse -Tim Dettrick -Tim Düsterhus -Tim Hockin -Tim Potter -Tim Ruffles -Tim Smith -Tim Terhorst -Tim Wagner -Tim Wang -Tim Waugh -Tim Wraight -Tim Zju <21651152@zju.edu.cn> -timchenxiaoyu <837829664@qq.com> -timfeirg -Timo Rothenpieler -Timothy Hobbs -tjwebb123 -tobe -Tobias Bieniek -Tobias Bradtke -Tobias Gesellchen -Tobias Klauser -Tobias Munk -Tobias Pfandzelter -Tobias Schmidt -Tobias Schwab -Todd Crane -Todd Lunter -Todd Whiteman -Toli Kuznets -Tom Barlow -Tom Booth -Tom Denham -Tom Fotherby -Tom Howe -Tom Hulihan -Tom Maaswinkel -Tom Parker -Tom Sweeney -Tom Wilkie -Tom X. Tobin -Tom Zhao -Tomas Janousek -Tomas Kral -Tomas Tomecek -Tomasz Kopczynski -Tomasz Lipinski -Tomasz Nurkiewicz -Tomek Mańko -Tommaso Visconti -Tomoya Tabuchi -Tomáš Hrčka -tonic -Tonny Xu -Tony Abboud -Tony Daws -Tony Miller -toogley -Torstein Husebø -Toshiaki Makita -Tõnis Tiigi -Trace Andreason -tracylihui <793912329@qq.com> -Trapier Marshall -Travis Cline -Travis Thieman -Trent Ogren -Trevor -Trevor Pounds -Trevor Sullivan -Trishna Guha -Tristan Carel -Troy Denton -Tudor Brindus -Ty Alexander -Tycho Andersen -Tyler Brock -Tyler Brown -Tzu-Jung Lee -uhayate -Ulysse Carion -Umesh Yadav -Utz Bacher -vagrant -Vaidas Jablonskis -Valentin Kulesh -vanderliang -Velko Ivanov -Veres Lajos -Victor Algaze -Victor Coisne -Victor Costan -Victor I. Wood -Victor Lyuboslavsky -Victor Marmol -Victor Palma -Victor Vieux -Victoria Bialas -Vijaya Kumar K -Vikas Choudhary -Vikram bir Singh -Viktor Stanchev -Viktor Vojnovski -VinayRaghavanKS -Vincent Batts -Vincent Bernat -Vincent Boulineau -Vincent Demeester -Vincent Giersch -Vincent Mayers -Vincent Woo -Vinod Kulkarni -Vishal Doshi -Vishnu Kannan -Vitaly Ostrosablin -Vitor Monteiro -Vivek Agarwal -Vivek Dasgupta -Vivek Goyal -Vladimir Bulyga -Vladimir Kirillov -Vladimir Pouzanov -Vladimir Rutsky -Vladimir Varankin -VladimirAus -Vladislav Kolesnikov -Vlastimil Zeman -Vojtech Vitek (V-Teq) -Walter Leibbrandt -Walter Stanish -Wang Chao -Wang Guoliang -Wang Jie -Wang Long -Wang Ping -Wang Xing -Wang Yuexiao -Wang Yumu <37442693@qq.com> -wanghuaiqing -Ward Vandewege -WarheadsSE -Wassim Dhif -Wataru Ishida -Wayne Chang -Wayne Song -Weerasak Chongnguluam -Wei Fu -Wei Wu -Wei-Ting Kuo -weipeng -weiyan -Weiyang Zhu -Wen Cheng Ma -Wendel Fleming -Wenjun Tang -Wenkai Yin -wenlxie -Wenxuan Zhao -Wenyu You <21551128@zju.edu.cn> -Wenzhi Liang -Wes Morgan -Wewang Xiaorenfine -Wiktor Kwapisiewicz -Will Dietz -Will Rouesnel -Will Weaver -willhf -William Delanoue -William Henry -William Hubbs -William Martin -William Riancho -William Thurston -Wilson Júnior -Wing-Kam Wong -WiseTrem -Wolfgang Nagele -Wolfgang Powisch -Wonjun Kim -WuLonghui -xamyzhao -Xia Wu -Xian Chaobo -Xianglin Gao -Xianjie -Xianlu Bird -Xiao YongBiao -Xiao Zhang -XiaoBing Jiang -Xiaodong Liu -Xiaodong Zhang -Xiaohua Ding -Xiaoxi He -Xiaoxu Chen -Xiaoyu Zhang -xichengliudui <1693291525@qq.com> -xiekeyang -Ximo Guanter Gonzálbez -xin.li -Xinbo Weng -Xinfeng Liu -Xinzi Zhou -Xiuming Chen -Xuecong Liao -xuzhaokui -Yadnyawalkya Tale -Yahya -yalpul -YAMADA Tsuyoshi -Yamasaki Masahide -Yamazaki Masashi -Yan Feng -Yan Zhu -Yang Bai -Yang Li -Yang Pengfei -yangchenliang -Yann Autissier -Yanqiang Miao -Yao Zaiyong -Yash Murty -Yassine Tijani -Yasunori Mahata -Yazhong Liu -Yestin Sun -Yi EungJun -Yibai Zhang -Yihang Ho -Ying Li -Yohei Ueda -Yong Tang -Yongxin Li -Yongzhi Pan -Yosef Fertel -You-Sheng Yang (楊有勝) -youcai -Youcef YEKHLEF -Youfu Zhang -Yu Changchun -Yu Chengxia -Yu Peng -Yu-Ju Hong -Yuan Sun -Yuanhong Peng -Yue Zhang -Yufei Xiong -Yuhao Fang -Yuichiro Kaneko -YujiOshima -Yunxiang Huang -Yurii Rashkovskii -Yusuf Tarık Günaydın -Yves Blusseau <90z7oey02@sneakemail.com> -Yves Junqueira -Zac Dover -Zach Borboa -Zach Gershman -Zachary Jaffee -Zain Memon -Zaiste! -Zane DeGraffenried -Zefan Li -Zen Lin(Zhinan Lin) -Zhang Kun -Zhang Wei -Zhang Wentao -ZhangHang -zhangxianwei -Zhenan Ye <21551168@zju.edu.cn> -zhenghenghuo -Zhenhai Gao -Zhenkun Bi -ZhiPeng Lu -zhipengzuo -Zhou Hao -Zhoulin Xie -Zhu Guihua -Zhu Kunjia -Zhuoyun Wei -Ziheng Liu -Zilin Du -zimbatm -Ziming Dong -ZJUshuaizhou <21551191@zju.edu.cn> -zmarouf -Zoltan Tombol -Zou Yu -zqh -Zuhayr Elahi -Zunayed Ali -Álvaro Lázaro -Átila Camurça Alves -尹吉峰 -屈骏 -徐俊杰 -慕陶 -搏通 -黄艳红00139573 -정재영 diff --git a/vendor/github.com/docker/docker/LICENSE b/vendor/github.com/docker/docker/LICENSE deleted file mode 100644 index 6d8d58fb6..000000000 --- a/vendor/github.com/docker/docker/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2013-2018 Docker, Inc. - - 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 - - https://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. diff --git a/vendor/github.com/docker/docker/NOTICE b/vendor/github.com/docker/docker/NOTICE deleted file mode 100644 index 58b19b6d1..000000000 --- a/vendor/github.com/docker/docker/NOTICE +++ /dev/null @@ -1,19 +0,0 @@ -Docker -Copyright 2012-2017 Docker, Inc. - -This product includes software developed at Docker, Inc. (https://www.docker.com). - -This product contains software (https://github.com/creack/pty) developed -by Keith Rarick, licensed under the MIT License. - -The following is courtesy of our legal counsel: - - -Use and transfer of Docker may be subject to certain restrictions by the -United States and other governments. -It is your responsibility to ensure that your use and/or transfer does not -violate applicable laws. - -For more information, please see https://www.bis.doc.gov - -See also https://www.apache.org/dev/crypto.html and/or seek legal counsel. diff --git a/vendor/github.com/docker/docker/pkg/homedir/homedir_linux.go b/vendor/github.com/docker/docker/pkg/homedir/homedir_linux.go deleted file mode 100644 index ded1c7c8c..000000000 --- a/vendor/github.com/docker/docker/pkg/homedir/homedir_linux.go +++ /dev/null @@ -1,105 +0,0 @@ -package homedir // import "github.com/docker/docker/pkg/homedir" - -import ( - "errors" - "os" - "path/filepath" - "strings" -) - -// GetRuntimeDir returns XDG_RUNTIME_DIR. -// XDG_RUNTIME_DIR is typically configured via pam_systemd. -// GetRuntimeDir returns non-nil error if XDG_RUNTIME_DIR is not set. -// -// See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html -func GetRuntimeDir() (string, error) { - if xdgRuntimeDir := os.Getenv("XDG_RUNTIME_DIR"); xdgRuntimeDir != "" { - return xdgRuntimeDir, nil - } - return "", errors.New("could not get XDG_RUNTIME_DIR") -} - -// StickRuntimeDirContents sets the sticky bit on files that are under -// XDG_RUNTIME_DIR, so that the files won't be periodically removed by the system. -// -// StickyRuntimeDir returns slice of sticked files. -// StickyRuntimeDir returns nil error if XDG_RUNTIME_DIR is not set. -// -// See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html -func StickRuntimeDirContents(files []string) ([]string, error) { - runtimeDir, err := GetRuntimeDir() - if err != nil { - // ignore error if runtimeDir is empty - return nil, nil - } - runtimeDir, err = filepath.Abs(runtimeDir) - if err != nil { - return nil, err - } - var sticked []string - for _, f := range files { - f, err = filepath.Abs(f) - if err != nil { - return sticked, err - } - if strings.HasPrefix(f, runtimeDir+"/") { - if err = stick(f); err != nil { - return sticked, err - } - sticked = append(sticked, f) - } - } - return sticked, nil -} - -func stick(f string) error { - st, err := os.Stat(f) - if err != nil { - return err - } - m := st.Mode() - m |= os.ModeSticky - return os.Chmod(f, m) -} - -// GetDataHome returns XDG_DATA_HOME. -// GetDataHome returns $HOME/.local/share and nil error if XDG_DATA_HOME is not set. -// If HOME and XDG_DATA_HOME are not set, getpwent(3) is consulted to determine the users home directory. -// -// See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html -func GetDataHome() (string, error) { - if xdgDataHome := os.Getenv("XDG_DATA_HOME"); xdgDataHome != "" { - return xdgDataHome, nil - } - home := Get() - if home == "" { - return "", errors.New("could not get either XDG_DATA_HOME or HOME") - } - return filepath.Join(home, ".local", "share"), nil -} - -// GetConfigHome returns XDG_CONFIG_HOME. -// GetConfigHome returns $HOME/.config and nil error if XDG_CONFIG_HOME is not set. -// If HOME and XDG_CONFIG_HOME are not set, getpwent(3) is consulted to determine the users home directory. -// -// See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html -func GetConfigHome() (string, error) { - if xdgConfigHome := os.Getenv("XDG_CONFIG_HOME"); xdgConfigHome != "" { - return xdgConfigHome, nil - } - home := Get() - if home == "" { - return "", errors.New("could not get either XDG_CONFIG_HOME or HOME") - } - return filepath.Join(home, ".config"), nil -} - -// GetLibHome returns $HOME/.local/lib -// If HOME is not set, getpwent(3) is consulted to determine the users home directory. -func GetLibHome() (string, error) { - home := Get() - if home == "" { - return "", errors.New("could not get HOME") - } - return filepath.Join(home, ".local/lib"), nil -} diff --git a/vendor/github.com/docker/docker/pkg/homedir/homedir_others.go b/vendor/github.com/docker/docker/pkg/homedir/homedir_others.go deleted file mode 100644 index 11f1bec98..000000000 --- a/vendor/github.com/docker/docker/pkg/homedir/homedir_others.go +++ /dev/null @@ -1,33 +0,0 @@ -//go:build !linux -// +build !linux - -package homedir // import "github.com/docker/docker/pkg/homedir" - -import ( - "errors" -) - -// GetRuntimeDir is unsupported on non-linux system. -func GetRuntimeDir() (string, error) { - return "", errors.New("homedir.GetRuntimeDir() is not supported on this system") -} - -// StickRuntimeDirContents is unsupported on non-linux system. -func StickRuntimeDirContents(files []string) ([]string, error) { - return nil, errors.New("homedir.StickRuntimeDirContents() is not supported on this system") -} - -// GetDataHome is unsupported on non-linux system. -func GetDataHome() (string, error) { - return "", errors.New("homedir.GetDataHome() is not supported on this system") -} - -// GetConfigHome is unsupported on non-linux system. -func GetConfigHome() (string, error) { - return "", errors.New("homedir.GetConfigHome() is not supported on this system") -} - -// GetLibHome is unsupported on non-linux system. -func GetLibHome() (string, error) { - return "", errors.New("homedir.GetLibHome() is not supported on this system") -} diff --git a/vendor/github.com/docker/docker/pkg/homedir/homedir_unix.go b/vendor/github.com/docker/docker/pkg/homedir/homedir_unix.go deleted file mode 100644 index d1732dee5..000000000 --- a/vendor/github.com/docker/docker/pkg/homedir/homedir_unix.go +++ /dev/null @@ -1,39 +0,0 @@ -//go:build !windows -// +build !windows - -package homedir // import "github.com/docker/docker/pkg/homedir" - -import ( - "os" - "os/user" -) - -// Key returns the env var name for the user's home dir based on -// the platform being run on -func Key() string { - return "HOME" -} - -// Get returns the home directory of the current user with the help of -// environment variables depending on the target operating system. -// Returned path should be used with "path/filepath" to form new paths. -// -// If linking statically with cgo enabled against glibc, ensure the -// osusergo build tag is used. -// -// If needing to do nss lookups, do not disable cgo or set osusergo. -func Get() string { - home := os.Getenv(Key()) - if home == "" { - if u, err := user.Current(); err == nil { - return u.HomeDir - } - } - return home -} - -// GetShortcutString returns the string that is shortcut to user's home directory -// in the native shell of the platform running on. -func GetShortcutString() string { - return "~" -} diff --git a/vendor/github.com/docker/docker/pkg/homedir/homedir_windows.go b/vendor/github.com/docker/docker/pkg/homedir/homedir_windows.go deleted file mode 100644 index 2f81813b2..000000000 --- a/vendor/github.com/docker/docker/pkg/homedir/homedir_windows.go +++ /dev/null @@ -1,24 +0,0 @@ -package homedir // import "github.com/docker/docker/pkg/homedir" - -import ( - "os" -) - -// Key returns the env var name for the user's home dir based on -// the platform being run on -func Key() string { - return "USERPROFILE" -} - -// Get returns the home directory of the current user with the help of -// environment variables depending on the target operating system. -// Returned path should be used with "path/filepath" to form new paths. -func Get() string { - return os.Getenv(Key()) -} - -// GetShortcutString returns the string that is shortcut to user's home directory -// in the native shell of the platform running on. -func GetShortcutString() string { - return "%USERPROFILE%" // be careful while using in format functions -} diff --git a/vendor/github.com/google/go-containerregistry/LICENSE b/vendor/github.com/google/go-containerregistry/LICENSE deleted file mode 100644 index 7a4a3ea24..000000000 --- a/vendor/github.com/google/go-containerregistry/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - 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 "[]" - 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 - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. \ No newline at end of file diff --git a/vendor/github.com/google/go-containerregistry/internal/and/and_closer.go b/vendor/github.com/google/go-containerregistry/internal/and/and_closer.go deleted file mode 100644 index 14a05eaa1..000000000 --- a/vendor/github.com/google/go-containerregistry/internal/and/and_closer.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2020 Google LLC 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 and provides helpers for adding Close to io.{Reader|Writer}. -package and - -import ( - "io" -) - -// ReadCloser implements io.ReadCloser by reading from a particular io.Reader -// and then calling the provided "Close()" method. -type ReadCloser struct { - io.Reader - CloseFunc func() error -} - -var _ io.ReadCloser = (*ReadCloser)(nil) - -// Close implements io.ReadCloser -func (rac *ReadCloser) Close() error { - return rac.CloseFunc() -} - -// WriteCloser implements io.WriteCloser by reading from a particular io.Writer -// and then calling the provided "Close()" method. -type WriteCloser struct { - io.Writer - CloseFunc func() error -} - -var _ io.WriteCloser = (*WriteCloser)(nil) - -// Close implements io.WriteCloser -func (wac *WriteCloser) Close() error { - return wac.CloseFunc() -} diff --git a/vendor/github.com/google/go-containerregistry/internal/compression/compression.go b/vendor/github.com/google/go-containerregistry/internal/compression/compression.go deleted file mode 100644 index 012487150..000000000 --- a/vendor/github.com/google/go-containerregistry/internal/compression/compression.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2022 Google LLC 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 compression abstracts over gzip and zstd. -package compression - -import ( - "bufio" - "bytes" - "io" - - "github.com/google/go-containerregistry/internal/gzip" - "github.com/google/go-containerregistry/internal/zstd" - "github.com/google/go-containerregistry/pkg/compression" -) - -// Opener represents e.g. opening a file. -type Opener = func() (io.ReadCloser, error) - -// GetCompression detects whether an Opener is compressed and which algorithm is used. -func GetCompression(opener Opener) (compression.Compression, error) { - rc, err := opener() - if err != nil { - return compression.None, err - } - defer rc.Close() - - cp, _, err := PeekCompression(rc) - if err != nil { - return compression.None, err - } - - return cp, nil -} - -// PeekCompression detects whether the input stream is compressed and which algorithm is used. -// -// If r implements Peek, we will use that directly, otherwise a small number -// of bytes are buffered to Peek at the gzip/zstd header, and the returned -// PeekReader can be used as a replacement for the consumed input io.Reader. -func PeekCompression(r io.Reader) (compression.Compression, PeekReader, error) { - pr := intoPeekReader(r) - - if isGZip, _, err := checkHeader(pr, gzip.MagicHeader); err != nil { - return compression.None, pr, err - } else if isGZip { - return compression.GZip, pr, nil - } - - if isZStd, _, err := checkHeader(pr, zstd.MagicHeader); err != nil { - return compression.None, pr, err - } else if isZStd { - return compression.ZStd, pr, nil - } - - return compression.None, pr, nil -} - -// PeekReader is an io.Reader that also implements Peek a la bufio.Reader. -type PeekReader interface { - io.Reader - Peek(n int) ([]byte, error) -} - -// IntoPeekReader creates a PeekReader from an io.Reader. -// If the reader already has a Peek method, it will just return the passed reader. -func intoPeekReader(r io.Reader) PeekReader { - if p, ok := r.(PeekReader); ok { - return p - } - - return bufio.NewReader(r) -} - -// CheckHeader checks whether the first bytes from a PeekReader match an expected header -func checkHeader(pr PeekReader, expectedHeader []byte) (bool, PeekReader, error) { - header, err := pr.Peek(len(expectedHeader)) - if err != nil { - // https://github.com/google/go-containerregistry/issues/367 - if err == io.EOF { - return false, pr, nil - } - return false, pr, err - } - return bytes.Equal(header, expectedHeader), pr, nil -} diff --git a/vendor/github.com/google/go-containerregistry/internal/estargz/estargz.go b/vendor/github.com/google/go-containerregistry/internal/estargz/estargz.go deleted file mode 100644 index 69021bcee..000000000 --- a/vendor/github.com/google/go-containerregistry/internal/estargz/estargz.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2020 Google LLC 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 estargz adapts the containerd estargz package to our abstractions. -package estargz - -import ( - "bytes" - "io" - - "github.com/containerd/stargz-snapshotter/estargz" - v1 "github.com/google/go-containerregistry/pkg/v1" -) - -// Assert that what we're returning is an io.ReadCloser -var _ io.ReadCloser = (*estargz.Blob)(nil) - -// ReadCloser reads uncompressed tarball input from the io.ReadCloser and -// returns: -// - An io.ReadCloser from which compressed data may be read, and -// - A v1.Hash with the hash of the estargz table of contents, or -// - An error if the estargz processing encountered a problem. -// -// Refer to estargz for the options: -// https://pkg.go.dev/github.com/containerd/stargz-snapshotter/estargz@v0.4.1#Option -func ReadCloser(r io.ReadCloser, opts ...estargz.Option) (*estargz.Blob, v1.Hash, error) { - defer r.Close() - - // TODO(#876): Avoid buffering into memory. - bs, err := io.ReadAll(r) - if err != nil { - return nil, v1.Hash{}, err - } - br := bytes.NewReader(bs) - - rc, err := estargz.Build(io.NewSectionReader(br, 0, int64(len(bs))), opts...) - if err != nil { - return nil, v1.Hash{}, err - } - - h, err := v1.NewHash(rc.TOCDigest().String()) - return rc, h, err -} diff --git a/vendor/github.com/google/go-containerregistry/internal/gzip/zip.go b/vendor/github.com/google/go-containerregistry/internal/gzip/zip.go deleted file mode 100644 index 018c0f8c0..000000000 --- a/vendor/github.com/google/go-containerregistry/internal/gzip/zip.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2020 Google LLC 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 gzip provides helper functions for interacting with gzipped streams. -package gzip - -import ( - "bufio" - "bytes" - "compress/gzip" - "io" - - "github.com/google/go-containerregistry/internal/and" -) - -// MagicHeader is the start of gzip files. -var MagicHeader = []byte{'\x1f', '\x8b'} - -// ReadCloser reads uncompressed input data from the io.ReadCloser and -// returns an io.ReadCloser from which compressed data may be read. -// This uses gzip.BestSpeed for the compression level. -func ReadCloser(r io.ReadCloser) io.ReadCloser { - return ReadCloserLevel(r, gzip.BestSpeed) -} - -// ReadCloserLevel reads uncompressed input data from the io.ReadCloser and -// returns an io.ReadCloser from which compressed data may be read. -// Refer to compress/gzip for the level: -// https://golang.org/pkg/compress/gzip/#pkg-constants -func ReadCloserLevel(r io.ReadCloser, level int) io.ReadCloser { - pr, pw := io.Pipe() - - // For highly compressible layers, gzip.Writer will output a very small - // number of bytes per Write(). This is normally fine, but when pushing - // to a registry, we want to ensure that we're taking full advantage of - // the available bandwidth instead of sending tons of tiny writes over - // the wire. - // 64K ought to be small enough for anybody. - bw := bufio.NewWriterSize(pw, 2<<16) - - // Returns err so we can pw.CloseWithError(err) - go func() error { - // TODO(go1.14): Just defer {pw,gw,r}.Close like you'd expect. - // Context: https://golang.org/issue/24283 - gw, err := gzip.NewWriterLevel(bw, level) - if err != nil { - return pw.CloseWithError(err) - } - - if _, err := io.Copy(gw, r); err != nil { - defer r.Close() - defer gw.Close() - return pw.CloseWithError(err) - } - - // Close gzip writer to Flush it and write gzip trailers. - if err := gw.Close(); err != nil { - return pw.CloseWithError(err) - } - - // Flush bufio writer to ensure we write out everything. - if err := bw.Flush(); err != nil { - return pw.CloseWithError(err) - } - - // We don't really care if these fail. - defer pw.Close() - defer r.Close() - - return nil - }() - - return pr -} - -// UnzipReadCloser reads compressed input data from the io.ReadCloser and -// returns an io.ReadCloser from which uncompressed data may be read. -func UnzipReadCloser(r io.ReadCloser) (io.ReadCloser, error) { - gr, err := gzip.NewReader(r) - if err != nil { - return nil, err - } - return &and.ReadCloser{ - Reader: gr, - CloseFunc: func() error { - // If the unzip fails, then this seems to return the same - // error as the read. We don't want this to interfere with - // us closing the main ReadCloser, since this could leave - // an open file descriptor (fails on Windows). - gr.Close() - return r.Close() - }, - }, nil -} - -// Is detects whether the input stream is compressed. -func Is(r io.Reader) (bool, error) { - magicHeader := make([]byte, 2) - n, err := r.Read(magicHeader) - if n == 0 && err == io.EOF { - return false, nil - } - if err != nil { - return false, err - } - return bytes.Equal(magicHeader, MagicHeader), nil -} diff --git a/vendor/github.com/google/go-containerregistry/internal/redact/redact.go b/vendor/github.com/google/go-containerregistry/internal/redact/redact.go deleted file mode 100644 index b2e3f186c..000000000 --- a/vendor/github.com/google/go-containerregistry/internal/redact/redact.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2020 Google LLC 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 redact contains a simple context signal for redacting requests. -package redact - -import ( - "context" - "errors" - "net/url" -) - -type contextKey string - -var redactKey = contextKey("redact") - -// NewContext creates a new ctx with the reason for redaction. -func NewContext(ctx context.Context, reason string) context.Context { - return context.WithValue(ctx, redactKey, reason) -} - -// FromContext returns the redaction reason, if any. -func FromContext(ctx context.Context) (bool, string) { - reason, ok := ctx.Value(redactKey).(string) - return ok, reason -} - -// Error redacts potentially sensitive query parameter values in the URL from the error's message. -// -// If the error is a *url.Error, this returns a *url.Error with the URL redacted. -// Any other error type, or nil, is returned unchanged. -func Error(err error) error { - // If the error is a url.Error, we can redact the URL. - // Otherwise (including if err is nil), we can't redact. - var uerr *url.Error - if ok := errors.As(err, &uerr); !ok { - return err - } - u, perr := url.Parse(uerr.URL) - if perr != nil { - return err // If the URL can't be parsed, just return the original error. - } - uerr.URL = URL(u).String() // Update the URL to the redacted URL. - return uerr -} - -// The set of query string keys that we expect to send as part of the registry -// protocol. Anything else is potentially dangerous to leak, as it's probably -// from a redirect. These redirects often included tokens or signed URLs. -var paramAllowlist = map[string]struct{}{ - // Token exchange - "scope": {}, - "service": {}, - // Cross-repo mounting - "mount": {}, - "from": {}, - // Layer PUT - "digest": {}, - // Listing tags and catalog - "n": {}, - "last": {}, -} - -// URL redacts potentially sensitive query parameter values from the URL's query string. -func URL(u *url.URL) *url.URL { - qs := u.Query() - for k, v := range qs { - for i := range v { - if _, ok := paramAllowlist[k]; !ok { - // key is not in the Allowlist - v[i] = "REDACTED" - } - } - } - r := *u - r.RawQuery = qs.Encode() - return &r -} diff --git a/vendor/github.com/google/go-containerregistry/internal/retry/retry.go b/vendor/github.com/google/go-containerregistry/internal/retry/retry.go deleted file mode 100644 index c9e356450..000000000 --- a/vendor/github.com/google/go-containerregistry/internal/retry/retry.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2019 Google LLC 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 retry provides methods for retrying operations. It is a thin wrapper -// around k8s.io/apimachinery/pkg/util/wait to make certain operations easier. -package retry - -import ( - "context" - "errors" - "fmt" - - "github.com/google/go-containerregistry/internal/retry/wait" -) - -// Backoff is an alias of our own wait.Backoff to avoid name conflicts with -// the kubernetes wait package. Typing retry.Backoff is aesier than fixing -// the wrong import every time you use wait.Backoff. -type Backoff = wait.Backoff - -// This is implemented by several errors in the net package as well as our -// transport.Error. -type temporary interface { - Temporary() bool -} - -// IsTemporary returns true if err implements Temporary() and it returns true. -func IsTemporary(err error) bool { - if errors.Is(err, context.DeadlineExceeded) { - return false - } - if te, ok := err.(temporary); ok && te.Temporary() { - return true - } - return false -} - -// IsNotNil returns true if err is not nil. -func IsNotNil(err error) bool { - return err != nil -} - -// Predicate determines whether an error should be retried. -type Predicate func(error) (retry bool) - -// Retry retries a given function, f, until a predicate is satisfied, using -// exponential backoff. If the predicate is never satisfied, it will return the -// last error returned by f. -func Retry(f func() error, p Predicate, backoff wait.Backoff) (err error) { - if f == nil { - return fmt.Errorf("nil f passed to retry") - } - if p == nil { - return fmt.Errorf("nil p passed to retry") - } - - condition := func() (bool, error) { - err = f() - if p(err) { - return false, nil - } - return true, err - } - - wait.ExponentialBackoff(backoff, condition) - return -} - -type contextKey string - -var key = contextKey("never") - -// Never returns a context that signals something should not be retried. -// This is a hack and can be used to communicate across package boundaries -// to avoid retry amplification. -func Never(ctx context.Context) context.Context { - return context.WithValue(ctx, key, true) -} - -// Ever returns true if the context was wrapped by Never. -func Ever(ctx context.Context) bool { - return ctx.Value(key) == nil -} diff --git a/vendor/github.com/google/go-containerregistry/internal/retry/wait/kubernetes_apimachinery_wait.go b/vendor/github.com/google/go-containerregistry/internal/retry/wait/kubernetes_apimachinery_wait.go deleted file mode 100644 index ab06e5f10..000000000 --- a/vendor/github.com/google/go-containerregistry/internal/retry/wait/kubernetes_apimachinery_wait.go +++ /dev/null @@ -1,123 +0,0 @@ -/* -Copyright 2014 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 wait is a subset of k8s.io/apimachinery to avoid conflicts -// in dependencies (specifically, logging). -package wait - -import ( - "errors" - "math/rand" - "time" -) - -// Jitter returns a time.Duration between duration and duration + maxFactor * -// duration. -// -// This allows clients to avoid converging on periodic behavior. If maxFactor -// is 0.0, a suggested default value will be chosen. -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)) - return wait -} - -// ErrWaitTimeout is returned when the condition exited without success. -var ErrWaitTimeout = errors.New("timed out waiting for the condition") - -// ConditionFunc returns true if the condition is satisfied, or an error -// if the loop should be aborted. -type ConditionFunc func() (done bool, err error) - -// Backoff holds parameters applied to a Backoff function. -type Backoff struct { - // The initial duration. - Duration time.Duration - // Duration is multiplied by factor each iteration, if factor is not zero - // and the limits imposed by Steps and Cap have not been reached. - // Should not be negative. - // The jitter does not contribute to the updates to the duration parameter. - Factor float64 - // The sleep at each iteration is the duration plus an additional - // amount chosen uniformly at random from the interval between - // zero and `jitter*duration`. - Jitter float64 - // The remaining number of iterations in which the duration - // parameter may change (but progress can be stopped earlier by - // hitting the cap). If not positive, the duration is not - // changed. Used for exponential backoff in combination with - // Factor and Cap. - Steps int - // A limit on revised values of the duration parameter. If a - // multiplication by the factor parameter would make the duration - // exceed the cap then the duration is set to the cap and the - // steps parameter is set to zero. - Cap time.Duration -} - -// Step (1) returns an amount of time to sleep determined by the -// original Duration and Jitter and (2) mutates the provided Backoff -// to update its Steps and Duration. -func (b *Backoff) Step() time.Duration { - if b.Steps < 1 { - if b.Jitter > 0 { - return Jitter(b.Duration, b.Jitter) - } - return b.Duration - } - b.Steps-- - - duration := b.Duration - - // calculate the next step - if b.Factor != 0 { - b.Duration = time.Duration(float64(b.Duration) * b.Factor) - if b.Cap > 0 && b.Duration > b.Cap { - b.Duration = b.Cap - b.Steps = 0 - } - } - - if b.Jitter > 0 { - duration = Jitter(duration, b.Jitter) - } - return duration -} - -// ExponentialBackoff repeats a condition check with exponential backoff. -// -// It repeatedly checks the condition and then sleeps, using `backoff.Step()` -// to determine the length of the sleep and adjust Duration and Steps. -// Stops and returns as soon as: -// 1. the condition check returns true or an error, -// 2. `backoff.Steps` checks of the condition have been done, or -// 3. a sleep truncated by the cap on duration has been completed. -// In case (1) the returned error is what the condition function returned. -// In all other cases, ErrWaitTimeout is returned. -func ExponentialBackoff(backoff Backoff, condition ConditionFunc) error { - for backoff.Steps > 0 { - if ok, err := condition(); err != nil || ok { - return err - } - if backoff.Steps == 1 { - break - } - time.Sleep(backoff.Step()) - } - return ErrWaitTimeout -} diff --git a/vendor/github.com/google/go-containerregistry/internal/verify/verify.go b/vendor/github.com/google/go-containerregistry/internal/verify/verify.go deleted file mode 100644 index 463f7e4b3..000000000 --- a/vendor/github.com/google/go-containerregistry/internal/verify/verify.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2020 Google LLC 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 verify provides a ReadCloser that verifies content matches the -// expected hash values. -package verify - -import ( - "bytes" - "encoding/hex" - "errors" - "fmt" - "hash" - "io" - - "github.com/google/go-containerregistry/internal/and" - v1 "github.com/google/go-containerregistry/pkg/v1" -) - -// SizeUnknown is a sentinel value to indicate that the expected size is not known. -const SizeUnknown = -1 - -type verifyReader struct { - inner io.Reader - hasher hash.Hash - expected v1.Hash - gotSize, wantSize int64 -} - -// Error provides information about the failed hash verification. -type Error struct { - got string - want v1.Hash - gotSize int64 -} - -func (v Error) Error() string { - return fmt.Sprintf("error verifying %s checksum after reading %d bytes; got %q, want %q", - v.want.Algorithm, v.gotSize, v.got, v.want) -} - -// Read implements io.Reader -func (vc *verifyReader) Read(b []byte) (int, error) { - n, err := vc.inner.Read(b) - vc.gotSize += int64(n) - if err == io.EOF { - if vc.wantSize != SizeUnknown && vc.gotSize != vc.wantSize { - return n, fmt.Errorf("error verifying size; got %d, want %d", vc.gotSize, vc.wantSize) - } - got := hex.EncodeToString(vc.hasher.Sum(nil)) - if want := vc.expected.Hex; got != want { - return n, Error{ - got: vc.expected.Algorithm + ":" + got, - want: vc.expected, - gotSize: vc.gotSize, - } - } - } - return n, err -} - -// ReadCloser wraps the given io.ReadCloser to verify that its contents match -// the provided v1.Hash before io.EOF is returned. -// -// The reader will only be read up to size bytes, to prevent resource -// exhaustion. If EOF is returned before size bytes are read, an error is -// returned. -// -// A size of SizeUnknown (-1) indicates disables size verification when the size -// is unknown ahead of time. -func ReadCloser(r io.ReadCloser, size int64, h v1.Hash) (io.ReadCloser, error) { - w, err := v1.Hasher(h.Algorithm) - if err != nil { - return nil, err - } - r2 := io.TeeReader(r, w) // pass all writes to the hasher. - if size != SizeUnknown { - r2 = io.LimitReader(r2, size) // if we know the size, limit to that size. - } - return &and.ReadCloser{ - Reader: &verifyReader{ - inner: r2, - hasher: w, - expected: h, - wantSize: size, - }, - CloseFunc: r.Close, - }, nil -} - -// Descriptor verifies that the embedded Data field matches the Size and Digest -// fields of the given v1.Descriptor, returning an error if the Data field is -// missing or if it contains incorrect data. -func Descriptor(d v1.Descriptor) error { - if d.Data == nil { - return errors.New("error verifying descriptor; Data == nil") - } - - h, sz, err := v1.SHA256(bytes.NewReader(d.Data)) - if err != nil { - return err - } - if h != d.Digest { - return fmt.Errorf("error verifying Digest; got %q, want %q", h, d.Digest) - } - if sz != d.Size { - return fmt.Errorf("error verifying Size; got %d, want %d", sz, d.Size) - } - - return nil -} diff --git a/vendor/github.com/google/go-containerregistry/internal/windows/windows.go b/vendor/github.com/google/go-containerregistry/internal/windows/windows.go deleted file mode 100644 index 62d04cfb3..000000000 --- a/vendor/github.com/google/go-containerregistry/internal/windows/windows.go +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2021 Google LLC 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 windows - -import ( - "archive/tar" - "bytes" - "errors" - "fmt" - "io" - "path" - "strings" - - "github.com/google/go-containerregistry/internal/gzip" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/tarball" -) - -// userOwnerAndGroupSID is a magic value needed to make the binary executable -// in a Windows container. -// -// owner: BUILTIN/Users group: BUILTIN/Users ($sddlValue="O:BUG:BU") -const userOwnerAndGroupSID = "AQAAgBQAAAAkAAAAAAAAAAAAAAABAgAAAAAABSAAAAAhAgAAAQIAAAAAAAUgAAAAIQIAAA==" - -// Windows returns a Layer that is converted to be pullable on Windows. -func Windows(layer v1.Layer) (v1.Layer, error) { - // TODO: do this lazily. - - layerReader, err := layer.Uncompressed() - if err != nil { - return nil, fmt.Errorf("getting layer: %w", err) - } - defer layerReader.Close() - tarReader := tar.NewReader(layerReader) - w := new(bytes.Buffer) - tarWriter := tar.NewWriter(w) - defer tarWriter.Close() - - for _, dir := range []string{"Files", "Hives"} { - if err := tarWriter.WriteHeader(&tar.Header{ - Name: dir, - Typeflag: tar.TypeDir, - // Use a fixed Mode, so that this isn't sensitive to the directory and umask - // under which it was created. Additionally, windows can only set 0222, - // 0444, or 0666, none of which are executable. - Mode: 0555, - Format: tar.FormatPAX, - }); err != nil { - return nil, fmt.Errorf("writing %s directory: %w", dir, err) - } - } - - for { - header, err := tarReader.Next() - if errors.Is(err, io.EOF) { - break - } - if err != nil { - return nil, fmt.Errorf("reading layer: %w", err) - } - - if strings.HasPrefix(header.Name, "Files/") { - return nil, fmt.Errorf("file path %q already suitable for Windows", header.Name) - } - - header.Name = path.Join("Files", header.Name) - header.Format = tar.FormatPAX - - // TODO: this seems to make the file executable on Windows; - // only do this if the file should be executable. - if header.PAXRecords == nil { - header.PAXRecords = map[string]string{} - } - header.PAXRecords["MSWINDOWS.rawsd"] = userOwnerAndGroupSID - - if err := tarWriter.WriteHeader(header); err != nil { - return nil, fmt.Errorf("writing tar header: %w", err) - } - - if header.Typeflag == tar.TypeReg { - if _, err = io.Copy(tarWriter, tarReader); err != nil { - return nil, fmt.Errorf("writing layer file: %w", err) - } - } - } - - if err := tarWriter.Close(); err != nil { - return nil, err - } - - b := w.Bytes() - // gzip the contents, then create the layer - opener := func() (io.ReadCloser, error) { - return gzip.ReadCloser(io.NopCloser(bytes.NewReader(b))), nil - } - layer, err = tarball.LayerFromOpener(opener) - if err != nil { - return nil, fmt.Errorf("creating layer: %w", err) - } - - return layer, nil -} diff --git a/vendor/github.com/google/go-containerregistry/internal/zstd/zstd.go b/vendor/github.com/google/go-containerregistry/internal/zstd/zstd.go deleted file mode 100644 index cccf54a30..000000000 --- a/vendor/github.com/google/go-containerregistry/internal/zstd/zstd.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2022 Google LLC 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 zstd provides helper functions for interacting with zstd streams. -package zstd - -import ( - "bufio" - "bytes" - "io" - - "github.com/google/go-containerregistry/internal/and" - "github.com/klauspost/compress/zstd" -) - -// MagicHeader is the start of zstd files. -var MagicHeader = []byte{'\x28', '\xb5', '\x2f', '\xfd'} - -// ReadCloser reads uncompressed input data from the io.ReadCloser and -// returns an io.ReadCloser from which compressed data may be read. -// This uses zstd level 1 for the compression. -func ReadCloser(r io.ReadCloser) io.ReadCloser { - return ReadCloserLevel(r, 1) -} - -// ReadCloserLevel reads uncompressed input data from the io.ReadCloser and -// returns an io.ReadCloser from which compressed data may be read. -func ReadCloserLevel(r io.ReadCloser, level int) io.ReadCloser { - pr, pw := io.Pipe() - - // For highly compressible layers, zstd.Writer will output a very small - // number of bytes per Write(). This is normally fine, but when pushing - // to a registry, we want to ensure that we're taking full advantage of - // the available bandwidth instead of sending tons of tiny writes over - // the wire. - // 64K ought to be small enough for anybody. - bw := bufio.NewWriterSize(pw, 2<<16) - - // Returns err so we can pw.CloseWithError(err) - go func() error { - // TODO(go1.14): Just defer {pw,zw,r}.Close like you'd expect. - // Context: https://golang.org/issue/24283 - zw, err := zstd.NewWriter(bw, zstd.WithEncoderLevel(zstd.EncoderLevelFromZstd(level))) - if err != nil { - return pw.CloseWithError(err) - } - - if _, err := io.Copy(zw, r); err != nil { - defer r.Close() - defer zw.Close() - return pw.CloseWithError(err) - } - - // Close zstd writer to Flush it and write zstd trailers. - if err := zw.Close(); err != nil { - return pw.CloseWithError(err) - } - - // Flush bufio writer to ensure we write out everything. - if err := bw.Flush(); err != nil { - return pw.CloseWithError(err) - } - - // We don't really care if these fail. - defer pw.Close() - defer r.Close() - - return nil - }() - - return pr -} - -// UnzipReadCloser reads compressed input data from the io.ReadCloser and -// returns an io.ReadCloser from which uncompressed data may be read. -func UnzipReadCloser(r io.ReadCloser) (io.ReadCloser, error) { - gr, err := zstd.NewReader(r) - if err != nil { - return nil, err - } - return &and.ReadCloser{ - Reader: gr, - CloseFunc: func() error { - // If the unzip fails, then this seems to return the same - // error as the read. We don't want this to interfere with - // us closing the main ReadCloser, since this could leave - // an open file descriptor (fails on Windows). - gr.Close() - return r.Close() - }, - }, nil -} - -// Is detects whether the input stream is compressed. -func Is(r io.Reader) (bool, error) { - magicHeader := make([]byte, 4) - n, err := r.Read(magicHeader) - if n == 0 && err == io.EOF { - return false, nil - } - if err != nil { - return false, err - } - return bytes.Equal(magicHeader, MagicHeader), nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/authn/README.md b/vendor/github.com/google/go-containerregistry/pkg/authn/README.md deleted file mode 100644 index 042bddec0..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/authn/README.md +++ /dev/null @@ -1,322 +0,0 @@ -# `authn` - -[![GoDoc](https://godoc.org/github.com/google/go-containerregistry/pkg/authn?status.svg)](https://godoc.org/github.com/google/go-containerregistry/pkg/authn) - -This README outlines how we acquire and use credentials when interacting with a registry. - -As much as possible, we attempt to emulate `docker`'s authentication behavior and configuration so that this library "just works" if you've already configured credentials that work with `docker`; however, when things don't work, a basic understanding of what's going on can help with debugging. - -The official documentation for how authentication with `docker` works is (reasonably) scattered across several different sites and GitHub repositories, so we've tried to summarize the relevant bits here. - -## tl;dr for consumers of this package - -By default, [`pkg/v1/remote`](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/remote) uses [`Anonymous`](https://godoc.org/github.com/google/go-containerregistry/pkg/authn#Anonymous) credentials (i.e. _none_), which for most registries will only allow read access to public images. - -To use the credentials found in your Docker config file, you can use the [`DefaultKeychain`](https://godoc.org/github.com/google/go-containerregistry/pkg/authn#DefaultKeychain), e.g.: - -```go -package main - -import ( - "fmt" - - "github.com/google/go-containerregistry/pkg/authn" - "github.com/google/go-containerregistry/pkg/name" - "github.com/google/go-containerregistry/pkg/v1/remote" -) - -func main() { - ref, err := name.ParseReference("registry.example.com/private/repo") - if err != nil { - panic(err) - } - - // Fetch the manifest using default credentials. - img, err := remote.Get(ref, remote.WithAuthFromKeychain(authn.DefaultKeychain)) - if err != nil { - panic(err) - } - - // Prints the digest of registry.example.com/private/repo - fmt.Println(img.Digest) -} -``` - -The `DefaultKeychain` will use credentials as described in your Docker config file -- usually `~/.docker/config.json`, or `%USERPROFILE%\.docker\config.json` on Windows -- or the location described by the `DOCKER_CONFIG` environment variable, if set. - -If those are not found, `DefaultKeychain` will look for credentials configured using [Podman's expectation](https://docs.podman.io/en/latest/markdown/podman-login.1.html) that these are found in `${XDG_RUNTIME_DIR}/containers/auth.json`. - -[See below](#docker-config-auth) for more information about what is configured in this file. - -## Emulating Cloud Provider Credential Helpers - -[`pkg/v1/google.Keychain`](https://pkg.go.dev/github.com/google/go-containerregistry/pkg/v1/google#Keychain) provides a `Keychain` implementation that emulates [`docker-credential-gcr`](https://github.com/GoogleCloudPlatform/docker-credential-gcr) to find credentials in the environment. -See [`google.NewEnvAuthenticator`](https://pkg.go.dev/github.com/google/go-containerregistry/pkg/v1/google#NewEnvAuthenticator) and [`google.NewGcloudAuthenticator`](https://pkg.go.dev/github.com/google/go-containerregistry/pkg/v1/google#NewGcloudAuthenticator) for more information. - -To emulate other credential helpers without requiring them to be available as executables, [`NewKeychainFromHelper`](https://pkg.go.dev/github.com/google/go-containerregistry/pkg/authn#NewKeychainFromHelper) provides an adapter that takes a Go implementation satisfying a subset of the [`credentials.Helper`](https://pkg.go.dev/github.com/docker/docker-credential-helpers/credentials#Helper) interface, and makes it available as a `Keychain`. - -This means that you can emulate, for example, [Amazon ECR's `docker-credential-ecr-login` credential helper](https://github.com/awslabs/amazon-ecr-credential-helper) using the same implementation: - -```go -import ( - ecr "github.com/awslabs/amazon-ecr-credential-helper/ecr-login" - "github.com/awslabs/amazon-ecr-credential-helper/ecr-login/api" - - "github.com/google/go-containerregistry/pkg/authn" - "github.com/google/go-containerregistry/pkg/v1/remote" -) - -func main() { - // ... - ecrHelper := ecr.ECRHelper{ClientFactory: api.DefaultClientFactory{}} - img, err := remote.Get(ref, remote.WithAuthFromKeychain(authn.NewKeychainFromHelper(ecrHelper))) - if err != nil { - panic(err) - } - // ... -} -``` - -Likewise, you can emulate [Azure's ACR `docker-credential-acr-env` credential helper](https://github.com/chrismellard/docker-credential-acr-env): - -```go -import ( - "github.com/chrismellard/docker-credential-acr-env/pkg/credhelper" - - "github.com/google/go-containerregistry/pkg/authn" - "github.com/google/go-containerregistry/pkg/v1/remote" -) - -func main() { - // ... - acrHelper := credhelper.NewACRCredentialsHelper() - img, err := remote.Get(ref, remote.WithAuthFromKeychain(authn.NewKeychainFromHelper(acrHelper))) - if err != nil { - panic(err) - } - // ... -} -``` - - - -## Using Multiple `Keychain`s - -[`NewMultiKeychain`](https://pkg.go.dev/github.com/google/go-containerregistry/pkg/authn#NewMultiKeychain) allows you to specify multiple `Keychain` implementations, which will be checked in order when credentials are needed. - -For example: - -```go -kc := authn.NewMultiKeychain( - authn.DefaultKeychain, - google.Keychain, - authn.NewKeychainFromHelper(ecr.ECRHelper{ClientFactory: api.DefaultClientFactory{}}), - authn.NewKeychainFromHelper(acr.ACRCredHelper{}), -) -``` - -This multi-keychain will: - -- first check for credentials found in the Docker config file, as describe above, then -- check for GCP credentials available in the environment, as described above, then -- check for ECR credentials by emulating the ECR credential helper, then -- check for ACR credentials by emulating the ACR credential helper. - -If any keychain implementation is able to provide credentials for the request, they will be used, and further keychain implementations will not be consulted. - -If no implementations are able to provide credentials, `Anonymous` credentials will be used. - -## Docker Config Auth - -What follows attempts to gather useful information about Docker's config.json and make it available in one place. - -If you have questions, please [file an issue](https://github.com/google/go-containerregistry/issues/new). - -### Plaintext - -The config file is where your credentials are stored when you invoke `docker login`, e.g. the contents may look something like this: - -```json -{ - "auths": { - "registry.example.com": { - "auth": "QXp1cmVEaWFtb25kOmh1bnRlcjI=" - } - } -} -``` - -The `auths` map has an entry per registry, and the `auth` field contains your username and password encoded as [HTTP 'Basic' Auth](https://tools.ietf.org/html/rfc7617). - -**NOTE**: This means that your credentials are stored _in plaintext_: - -```bash -$ echo "QXp1cmVEaWFtb25kOmh1bnRlcjI=" | base64 -d -AzureDiamond:hunter2 -``` - -For what it's worth, this config file is equivalent to: - -```json -{ - "auths": { - "registry.example.com": { - "username": "AzureDiamond", - "password": "hunter2" - } - } -} -``` - -... which is useful to know if e.g. your CI system provides you a registry username and password via environment variables and you want to populate this file manually without invoking `docker login`. - -### Helpers - -If you log in like this, `docker` will warn you that you should use a [credential helper](https://docs.docker.com/engine/reference/commandline/login/#credentials-store), and you should! - -To configure a global credential helper: -```json -{ - "credsStore": "osxkeychain" -} -``` - -To configure a per-registry credential helper: -```json -{ - "credHelpers": { - "gcr.io": "gcr" - } -} -``` - -We use [`github.com/docker/cli/cli/config.Load`](https://godoc.org/github.com/docker/cli/cli/config#Load) to parse the config file and invoke any necessary credential helpers. This handles the logic of taking a [`ConfigFile`](https://github.com/docker/cli/blob/ba63a92655c0bea4857b8d6cc4991498858b3c60/cli/config/configfile/file.go#L25-L54) + registry domain and producing an [`AuthConfig`](https://github.com/docker/cli/blob/ba63a92655c0bea4857b8d6cc4991498858b3c60/cli/config/types/authconfig.go#L3-L22), which determines how we authenticate to the registry. - -## Credential Helpers - -The [credential helper protocol](https://github.com/docker/docker-credential-helpers) allows you to configure a binary that supplies credentials for the registry, rather than hard-coding them in the config file. - -The protocol has several verbs, but the one we most care about is `get`. - -For example, using the following config file: -```json -{ - "credHelpers": { - "gcr.io": "gcr", - "eu.gcr.io": "gcr" - } -} -``` - -To acquire credentials for `gcr.io`, we look in the `credHelpers` map to find -the credential helper for `gcr.io` is `gcr`. By appending that value to -`docker-credential-`, we can get the name of the binary we need to use. - -For this example, that's `docker-credential-gcr`, which must be on our `$PATH`. -We'll then invoke that binary to get credentials: - -```bash -$ echo "gcr.io" | docker-credential-gcr get -{"Username":"_token","Secret":""} -``` - -You can configure the same credential helper for multiple registries, which is -why we need to pass the domain in via STDIN, e.g. if we were trying to access -`eu.gcr.io`, we'd do this instead: - -```bash -$ echo "eu.gcr.io" | docker-credential-gcr get -{"Username":"_token","Secret":""} -``` - -### Debugging credential helpers - -If a credential helper is configured but doesn't seem to be working, it can be -challenging to debug. Implementing a fake credential helper lets you poke around -to make it easier to see where the failure is happening. - -This "implements" a credential helper with hard-coded values: -``` -#!/usr/bin/env bash -echo '{"Username":"","Secret":"hunter2"}' -``` - - -This implements a credential helper that prints the output of -`docker-credential-gcr` to both stderr and whatever called it, which allows you -to snoop on another credential helper: -``` -#!/usr/bin/env bash -docker-credential-gcr $@ | tee >(cat 1>&2) -``` - -Put those files somewhere on your path, naming them e.g. -`docker-credential-hardcoded` and `docker-credential-tee`, then modify the -config file to use them: - -```json -{ - "credHelpers": { - "gcr.io": "tee", - "eu.gcr.io": "hardcoded" - } -} -``` - -The `docker-credential-tee` trick works with both `crane` and `docker`: - -```bash -$ crane manifest gcr.io/google-containers/pause > /dev/null -{"ServerURL":"","Username":"_dcgcr_1_5_0_token","Secret":""} - -$ docker pull gcr.io/google-containers/pause -Using default tag: latest -{"ServerURL":"","Username":"_dcgcr_1_5_0_token","Secret":""} -latest: Pulling from google-containers/pause -a3ed95caeb02: Pull complete -4964c72cd024: Pull complete -Digest: sha256:a78c2d6208eff9b672de43f880093100050983047b7b0afe0217d3656e1b0d5f -Status: Downloaded newer image for gcr.io/google-containers/pause:latest -gcr.io/google-containers/pause:latest -``` - -## The Registry - -There are two methods for authenticating against a registry: -[token](https://docs.docker.com/registry/spec/auth/token/) and -[oauth2](https://docs.docker.com/registry/spec/auth/oauth/). - -Both methods are used to acquire an opaque `Bearer` token (or -[RegistryToken](https://github.com/docker/cli/blob/ba63a92655c0bea4857b8d6cc4991498858b3c60/cli/config/types/authconfig.go#L21)) -to use in the `Authorization` header. The registry will return a `401 -Unauthorized` during the [version -check](https://github.com/opencontainers/distribution-spec/blob/2c3975d1f03b67c9a0203199038adea0413f0573/spec.md#api-version-check) -(or during normal operations) with -[Www-Authenticate](https://tools.ietf.org/html/rfc7235#section-4.1) challenge -indicating how to proceed. - -### Token - -If we get back an `AuthConfig` containing a [`Username/Password`](https://github.com/docker/cli/blob/ba63a92655c0bea4857b8d6cc4991498858b3c60/cli/config/types/authconfig.go#L5-L6) -or -[`Auth`](https://github.com/docker/cli/blob/ba63a92655c0bea4857b8d6cc4991498858b3c60/cli/config/types/authconfig.go#L7), -we'll use the token method for authentication: - -![basic](../../images/credhelper-basic.svg) - -### OAuth 2 - -If we get back an `AuthConfig` containing an [`IdentityToken`](https://github.com/docker/cli/blob/ba63a92655c0bea4857b8d6cc4991498858b3c60/cli/config/types/authconfig.go#L18) -we'll use the oauth2 method for authentication: - -![oauth](../../images/credhelper-oauth.svg) - -This happens when a credential helper returns a response with the -[`Username`](https://github.com/docker/docker-credential-helpers/blob/f78081d1f7fef6ad74ad6b79368de6348386e591/credentials/credentials.go#L16) -set to `` (no, that's not a placeholder, the literal string `""`). -It is unclear why: [moby/moby#36926](https://github.com/moby/moby/issues/36926). - -We only support the oauth2 `grant_type` for `refresh_token` ([#629](https://github.com/google/go-containerregistry/issues/629)), -since it's impossible to determine from the registry response whether we should -use oauth, and the token method for authentication is widely implemented by -registries. diff --git a/vendor/github.com/google/go-containerregistry/pkg/authn/anon.go b/vendor/github.com/google/go-containerregistry/pkg/authn/anon.go deleted file mode 100644 index 83214957d..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/authn/anon.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2018 Google LLC 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 authn - -// anonymous implements Authenticator for anonymous authentication. -type anonymous struct{} - -// Authorization implements Authenticator. -func (a *anonymous) Authorization() (*AuthConfig, error) { - return &AuthConfig{}, nil -} - -// Anonymous is a singleton Authenticator for providing anonymous auth. -var Anonymous Authenticator = &anonymous{} diff --git a/vendor/github.com/google/go-containerregistry/pkg/authn/auth.go b/vendor/github.com/google/go-containerregistry/pkg/authn/auth.go deleted file mode 100644 index 0111f1ae7..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/authn/auth.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2018 Google LLC 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 authn - -// auth is an Authenticator that simply returns the wrapped AuthConfig. -type auth struct { - config AuthConfig -} - -// FromConfig returns an Authenticator that just returns the given AuthConfig. -func FromConfig(cfg AuthConfig) Authenticator { - return &auth{cfg} -} - -// Authorization implements Authenticator. -func (a *auth) Authorization() (*AuthConfig, error) { - return &a.config, nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/authn/authn.go b/vendor/github.com/google/go-containerregistry/pkg/authn/authn.go deleted file mode 100644 index 172d218e4..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/authn/authn.go +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2018 Google LLC 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 authn - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "strings" -) - -// Authenticator is used to authenticate Docker transports. -type Authenticator interface { - // Authorization returns the value to use in an http transport's Authorization header. - Authorization() (*AuthConfig, error) -} - -// AuthConfig contains authorization information for connecting to a Registry -// Inlined what we use from github.com/docker/cli/cli/config/types -type AuthConfig struct { - Username string `json:"username,omitempty"` - Password string `json:"password,omitempty"` - Auth string `json:"auth,omitempty"` - - // IdentityToken is used to authenticate the user and get - // an access token for the registry. - IdentityToken string `json:"identitytoken,omitempty"` - - // RegistryToken is a bearer token to be sent to a registry - RegistryToken string `json:"registrytoken,omitempty"` -} - -// This is effectively a copy of the type AuthConfig. This simplifies -// JSON unmarshalling since AuthConfig methods are not inherited -type authConfig AuthConfig - -// UnmarshalJSON implements json.Unmarshaler -func (a *AuthConfig) UnmarshalJSON(data []byte) error { - var shadow authConfig - err := json.Unmarshal(data, &shadow) - if err != nil { - return err - } - - *a = (AuthConfig)(shadow) - - if len(shadow.Auth) != 0 { - var derr error - a.Username, a.Password, derr = decodeDockerConfigFieldAuth(shadow.Auth) - if derr != nil { - err = fmt.Errorf("unable to decode auth field: %w", derr) - } - } else if len(a.Username) != 0 && len(a.Password) != 0 { - a.Auth = encodeDockerConfigFieldAuth(shadow.Username, shadow.Password) - } - - return err -} - -// MarshalJSON implements json.Marshaler -func (a AuthConfig) MarshalJSON() ([]byte, error) { - shadow := (authConfig)(a) - shadow.Auth = encodeDockerConfigFieldAuth(shadow.Username, shadow.Password) - return json.Marshal(shadow) -} - -// decodeDockerConfigFieldAuth deserializes the "auth" field from dockercfg into a -// username and a password. The format of the auth field is base64(:). -// -// From https://github.com/kubernetes/kubernetes/blob/75e49ec824b183288e1dbaccfd7dbe77d89db381/pkg/credentialprovider/config.go -// Copyright 2014 The Kubernetes Authors. -// SPDX-License-Identifier: Apache-2.0 -func decodeDockerConfigFieldAuth(field string) (username, password string, err error) { - var decoded []byte - // StdEncoding can only decode padded string - // RawStdEncoding can only decode unpadded string - if strings.HasSuffix(strings.TrimSpace(field), "=") { - // decode padded data - decoded, err = base64.StdEncoding.DecodeString(field) - } else { - // decode unpadded data - decoded, err = base64.RawStdEncoding.DecodeString(field) - } - - if err != nil { - return - } - - parts := strings.SplitN(string(decoded), ":", 2) - if len(parts) != 2 { - err = fmt.Errorf("must be formatted as base64(username:password)") - return - } - - username = parts[0] - password = parts[1] - - return -} - -func encodeDockerConfigFieldAuth(username, password string) string { - return base64.StdEncoding.EncodeToString([]byte(username + ":" + password)) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/authn/basic.go b/vendor/github.com/google/go-containerregistry/pkg/authn/basic.go deleted file mode 100644 index 500cb6616..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/authn/basic.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2018 Google LLC 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 authn - -// Basic implements Authenticator for basic authentication. -type Basic struct { - Username string - Password string -} - -// Authorization implements Authenticator. -func (b *Basic) Authorization() (*AuthConfig, error) { - return &AuthConfig{ - Username: b.Username, - Password: b.Password, - }, nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/authn/bearer.go b/vendor/github.com/google/go-containerregistry/pkg/authn/bearer.go deleted file mode 100644 index 4cf86df92..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/authn/bearer.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2018 Google LLC 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 authn - -// Bearer implements Authenticator for bearer authentication. -type Bearer struct { - Token string `json:"token"` -} - -// Authorization implements Authenticator. -func (b *Bearer) Authorization() (*AuthConfig, error) { - return &AuthConfig{ - RegistryToken: b.Token, - }, nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/authn/doc.go b/vendor/github.com/google/go-containerregistry/pkg/authn/doc.go deleted file mode 100644 index c2a5fc026..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/authn/doc.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2018 Google LLC 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 authn defines different methods of authentication for -// talking to a container registry. -package authn diff --git a/vendor/github.com/google/go-containerregistry/pkg/authn/keychain.go b/vendor/github.com/google/go-containerregistry/pkg/authn/keychain.go deleted file mode 100644 index 99e0b81c8..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/authn/keychain.go +++ /dev/null @@ -1,249 +0,0 @@ -// Copyright 2018 Google LLC 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 authn - -import ( - "os" - "path/filepath" - "sync" - "time" - - "github.com/docker/cli/cli/config" - "github.com/docker/cli/cli/config/configfile" - "github.com/docker/cli/cli/config/types" - "github.com/google/go-containerregistry/pkg/name" - "github.com/mitchellh/go-homedir" -) - -// Resource represents a registry or repository that can be authenticated against. -type Resource interface { - // String returns the full string representation of the target, e.g. - // gcr.io/my-project or just gcr.io. - String() string - - // RegistryStr returns just the registry portion of the target, e.g. for - // gcr.io/my-project, this should just return gcr.io. This is needed to - // pull out an appropriate hostname. - RegistryStr() string -} - -// Keychain is an interface for resolving an image reference to a credential. -type Keychain interface { - // Resolve looks up the most appropriate credential for the specified target. - Resolve(Resource) (Authenticator, error) -} - -// defaultKeychain implements Keychain with the semantics of the standard Docker -// credential keychain. -type defaultKeychain struct { - mu sync.Mutex -} - -var ( - // DefaultKeychain implements Keychain by interpreting the docker config file. - DefaultKeychain = &defaultKeychain{} -) - -const ( - // DefaultAuthKey is the key used for dockerhub in config files, which - // is hardcoded for historical reasons. - DefaultAuthKey = "https://" + name.DefaultRegistry + "/v1/" -) - -// Resolve implements Keychain. -func (dk *defaultKeychain) Resolve(target Resource) (Authenticator, error) { - dk.mu.Lock() - defer dk.mu.Unlock() - - // Podman users may have their container registry auth configured in a - // different location, that Docker packages aren't aware of. - // If the Docker config file isn't found, we'll fallback to look where - // Podman configures it, and parse that as a Docker auth config instead. - - // First, check $HOME/.docker/config.json - foundDockerConfig := false - home, err := homedir.Dir() - if err == nil { - foundDockerConfig = fileExists(filepath.Join(home, ".docker/config.json")) - } - // If $HOME/.docker/config.json isn't found, check $DOCKER_CONFIG (if set) - if !foundDockerConfig && os.Getenv("DOCKER_CONFIG") != "" { - foundDockerConfig = fileExists(filepath.Join(os.Getenv("DOCKER_CONFIG"), "config.json")) - } - // If either of those locations are found, load it using Docker's - // config.Load, which may fail if the config can't be parsed. - // - // If neither was found, look for Podman's auth at - // $XDG_RUNTIME_DIR/containers/auth.json and attempt to load it as a - // Docker config. - // - // If neither are found, fallback to Anonymous. - var cf *configfile.ConfigFile - if foundDockerConfig { - cf, err = config.Load(os.Getenv("DOCKER_CONFIG")) - if err != nil { - return nil, err - } - } else { - f, err := os.Open(filepath.Join(os.Getenv("XDG_RUNTIME_DIR"), "containers/auth.json")) - if err != nil { - return Anonymous, nil - } - defer f.Close() - cf, err = config.LoadFromReader(f) - if err != nil { - return nil, err - } - } - - // See: - // https://github.com/google/ko/issues/90 - // https://github.com/moby/moby/blob/fc01c2b481097a6057bec3cd1ab2d7b4488c50c4/registry/config.go#L397-L404 - var cfg, empty types.AuthConfig - for _, key := range []string{ - target.String(), - target.RegistryStr(), - } { - if key == name.DefaultRegistry { - key = DefaultAuthKey - } - - cfg, err = cf.GetAuthConfig(key) - if err != nil { - return nil, err - } - // cf.GetAuthConfig automatically sets the ServerAddress attribute. Since - // we don't make use of it, clear the value for a proper "is-empty" test. - // See: https://github.com/google/go-containerregistry/issues/1510 - cfg.ServerAddress = "" - if cfg != empty { - break - } - } - if cfg == empty { - return Anonymous, nil - } - - return FromConfig(AuthConfig{ - Username: cfg.Username, - Password: cfg.Password, - Auth: cfg.Auth, - IdentityToken: cfg.IdentityToken, - RegistryToken: cfg.RegistryToken, - }), nil -} - -// fileExists returns true if the given path exists and is not a directory. -func fileExists(path string) bool { - fi, err := os.Stat(path) - return err == nil && !fi.IsDir() -} - -// Helper is a subset of the Docker credential helper credentials.Helper -// interface used by NewKeychainFromHelper. -// -// See: -// https://pkg.go.dev/github.com/docker/docker-credential-helpers/credentials#Helper -type Helper interface { - Get(serverURL string) (string, string, error) -} - -// NewKeychainFromHelper returns a Keychain based on a Docker credential helper -// implementation that can Get username and password credentials for a given -// server URL. -func NewKeychainFromHelper(h Helper) Keychain { return wrapper{h} } - -type wrapper struct{ h Helper } - -func (w wrapper) Resolve(r Resource) (Authenticator, error) { - u, p, err := w.h.Get(r.RegistryStr()) - if err != nil { - return Anonymous, nil - } - // If the secret being stored is an identity token, the Username should be set to - // ref: https://docs.docker.com/engine/reference/commandline/login/#credential-helper-protocol - if u == "" { - return FromConfig(AuthConfig{Username: u, IdentityToken: p}), nil - } - return FromConfig(AuthConfig{Username: u, Password: p}), nil -} - -func RefreshingKeychain(inner Keychain, duration time.Duration) Keychain { - return &refreshingKeychain{ - keychain: inner, - duration: duration, - } -} - -type refreshingKeychain struct { - keychain Keychain - duration time.Duration - clock func() time.Time -} - -func (r *refreshingKeychain) Resolve(target Resource) (Authenticator, error) { - last := time.Now() - auth, err := r.keychain.Resolve(target) - if err != nil || auth == Anonymous { - return auth, err - } - return &refreshing{ - target: target, - keychain: r.keychain, - last: last, - cached: auth, - duration: r.duration, - clock: r.clock, - }, nil -} - -type refreshing struct { - sync.Mutex - target Resource - keychain Keychain - - duration time.Duration - - last time.Time - cached Authenticator - - // for testing - clock func() time.Time -} - -func (r *refreshing) Authorization() (*AuthConfig, error) { - r.Lock() - defer r.Unlock() - if r.cached == nil || r.expired() { - r.last = r.now() - auth, err := r.keychain.Resolve(r.target) - if err != nil { - return nil, err - } - r.cached = auth - } - return r.cached.Authorization() -} - -func (r *refreshing) now() time.Time { - if r.clock == nil { - return time.Now() - } - return r.clock() -} - -func (r *refreshing) expired() bool { - return r.now().Sub(r.last) > r.duration -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/authn/multikeychain.go b/vendor/github.com/google/go-containerregistry/pkg/authn/multikeychain.go deleted file mode 100644 index 3b1804f5d..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/authn/multikeychain.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2018 Google LLC 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 authn - -type multiKeychain struct { - keychains []Keychain -} - -// Assert that our multi-keychain implements Keychain. -var _ (Keychain) = (*multiKeychain)(nil) - -// NewMultiKeychain composes a list of keychains into one new keychain. -func NewMultiKeychain(kcs ...Keychain) Keychain { - return &multiKeychain{keychains: kcs} -} - -// Resolve implements Keychain. -func (mk *multiKeychain) Resolve(target Resource) (Authenticator, error) { - for _, kc := range mk.keychains { - auth, err := kc.Resolve(target) - if err != nil { - return nil, err - } - if auth != Anonymous { - return auth, nil - } - } - return Anonymous, nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/compression/compression.go b/vendor/github.com/google/go-containerregistry/pkg/compression/compression.go deleted file mode 100644 index 6686c2d8d..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/compression/compression.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2022 Google LLC 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 compression abstracts over gzip and zstd. -package compression - -// Compression is an enumeration of the supported compression algorithms -type Compression string - -// The collection of known MediaType values. -const ( - None Compression = "none" - GZip Compression = "gzip" - ZStd Compression = "zstd" -) diff --git a/vendor/github.com/google/go-containerregistry/pkg/crane/append.go b/vendor/github.com/google/go-containerregistry/pkg/crane/append.go deleted file mode 100644 index f1c2ef69a..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/crane/append.go +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2018 Google LLC 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 crane - -import ( - "fmt" - "os" - - "github.com/google/go-containerregistry/internal/windows" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/mutate" - "github.com/google/go-containerregistry/pkg/v1/stream" - "github.com/google/go-containerregistry/pkg/v1/tarball" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -func isWindows(img v1.Image) (bool, error) { - cfg, err := img.ConfigFile() - if err != nil { - return false, err - } - return cfg != nil && cfg.OS == "windows", nil -} - -// Append reads a layer from path and appends it the the v1.Image base. -// -// If the base image is a Windows base image (i.e., its config.OS is -// "windows"), the contents of the tarballs will be modified to be suitable for -// a Windows container image.`, -func Append(base v1.Image, paths ...string) (v1.Image, error) { - if base == nil { - return nil, fmt.Errorf("invalid argument: base") - } - - win, err := isWindows(base) - if err != nil { - return nil, fmt.Errorf("getting base image: %w", err) - } - - baseMediaType, err := base.MediaType() - - if err != nil { - return nil, fmt.Errorf("getting base image media type: %w", err) - } - - layerType := types.DockerLayer - - if baseMediaType == types.OCIManifestSchema1 { - layerType = types.OCILayer - } - - layers := make([]v1.Layer, 0, len(paths)) - for _, path := range paths { - layer, err := getLayer(path, layerType) - if err != nil { - return nil, fmt.Errorf("reading layer %q: %w", path, err) - } - - if win { - layer, err = windows.Windows(layer) - if err != nil { - return nil, fmt.Errorf("converting %q for Windows: %w", path, err) - } - } - - layers = append(layers, layer) - } - - return mutate.AppendLayers(base, layers...) -} - -func getLayer(path string, layerType types.MediaType) (v1.Layer, error) { - f, err := streamFile(path) - if err != nil { - return nil, err - } - if f != nil { - return stream.NewLayer(f, stream.WithMediaType(layerType)), nil - } - - return tarball.LayerFromFile(path, tarball.WithMediaType(layerType)) -} - -// If we're dealing with a named pipe, trying to open it multiple times will -// fail, so we need to do a streaming upload. -// -// returns nil, nil for non-streaming files -func streamFile(path string) (*os.File, error) { - if path == "-" { - return os.Stdin, nil - } - fi, err := os.Stat(path) - if err != nil { - return nil, err - } - - if !fi.Mode().IsRegular() { - return os.Open(path) - } - - return nil, nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/crane/catalog.go b/vendor/github.com/google/go-containerregistry/pkg/crane/catalog.go deleted file mode 100644 index f30800cca..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/crane/catalog.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2019 Google LLC 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 crane - -import ( - "context" - - "github.com/google/go-containerregistry/pkg/name" - "github.com/google/go-containerregistry/pkg/v1/remote" -) - -// Catalog returns the repositories in a registry's catalog. -func Catalog(src string, opt ...Option) (res []string, err error) { - o := makeOptions(opt...) - reg, err := name.NewRegistry(src, o.Name...) - if err != nil { - return nil, err - } - - // This context gets overridden by remote.WithContext, which is set by - // crane.WithContext. - return remote.Catalog(context.Background(), reg, o.Remote...) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/crane/config.go b/vendor/github.com/google/go-containerregistry/pkg/crane/config.go deleted file mode 100644 index 3e55cc93a..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/crane/config.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2018 Google LLC 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 crane - -// Config returns the config file for the remote image ref. -func Config(ref string, opt ...Option) ([]byte, error) { - i, _, err := getImage(ref, opt...) - if err != nil { - return nil, err - } - return i.RawConfigFile() -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/crane/copy.go b/vendor/github.com/google/go-containerregistry/pkg/crane/copy.go deleted file mode 100644 index bbdf5481f..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/crane/copy.go +++ /dev/null @@ -1,181 +0,0 @@ -// Copyright 2018 Google LLC 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 crane - -import ( - "errors" - "fmt" - "net/http" - - "github.com/google/go-containerregistry/pkg/logs" - "github.com/google/go-containerregistry/pkg/name" - "github.com/google/go-containerregistry/pkg/v1/remote" - "github.com/google/go-containerregistry/pkg/v1/remote/transport" - "golang.org/x/sync/errgroup" -) - -// Copy copies a remote image or index from src to dst. -func Copy(src, dst string, opt ...Option) error { - o := makeOptions(opt...) - srcRef, err := name.ParseReference(src, o.Name...) - if err != nil { - return fmt.Errorf("parsing reference %q: %w", src, err) - } - - dstRef, err := name.ParseReference(dst, o.Name...) - if err != nil { - return fmt.Errorf("parsing reference for %q: %w", dst, err) - } - - puller, err := remote.NewPuller(o.Remote...) - if err != nil { - return err - } - - if tag, ok := dstRef.(name.Tag); ok { - if o.noclobber { - logs.Progress.Printf("Checking existing tag %v", tag) - head, err := puller.Head(o.ctx, tag) - var terr *transport.Error - if errors.As(err, &terr) { - if terr.StatusCode != http.StatusNotFound && terr.StatusCode != http.StatusForbidden { - return err - } - } else if err != nil { - return err - } - - if head != nil { - return fmt.Errorf("refusing to clobber existing tag %s@%s", tag, head.Digest) - } - } - } - - pusher, err := remote.NewPusher(o.Remote...) - if err != nil { - return err - } - - logs.Progress.Printf("Copying from %v to %v", srcRef, dstRef) - desc, err := puller.Get(o.ctx, srcRef) - if err != nil { - return fmt.Errorf("fetching %q: %w", src, err) - } - - if o.Platform == nil { - return pusher.Push(o.ctx, dstRef, desc) - } - - // If platform is explicitly set, don't copy the whole index, just the appropriate image. - img, err := desc.Image() - if err != nil { - return err - } - return pusher.Push(o.ctx, dstRef, img) -} - -// CopyRepository copies every tag from src to dst. -func CopyRepository(src, dst string, opt ...Option) error { - o := makeOptions(opt...) - - srcRepo, err := name.NewRepository(src, o.Name...) - if err != nil { - return err - } - - dstRepo, err := name.NewRepository(dst, o.Name...) - if err != nil { - return fmt.Errorf("parsing reference for %q: %w", dst, err) - } - - puller, err := remote.NewPuller(o.Remote...) - if err != nil { - return err - } - - ignoredTags := map[string]struct{}{} - if o.noclobber { - // TODO: It would be good to propagate noclobber down into remote so we can use Etags. - have, err := puller.List(o.ctx, dstRepo) - if err != nil { - var terr *transport.Error - if errors.As(err, &terr) { - // Some registries create repository on first push, so listing tags will fail. - // If we see 404 or 403, assume we failed because the repository hasn't been created yet. - if !(terr.StatusCode == http.StatusNotFound || terr.StatusCode == http.StatusForbidden) { - return err - } - } else { - return err - } - } - for _, tag := range have { - ignoredTags[tag] = struct{}{} - } - } - - pusher, err := remote.NewPusher(o.Remote...) - if err != nil { - return err - } - - lister, err := puller.Lister(o.ctx, srcRepo) - if err != nil { - return err - } - - g, ctx := errgroup.WithContext(o.ctx) - g.SetLimit(o.jobs) - - for lister.HasNext() { - tags, err := lister.Next(ctx) - if err != nil { - return err - } - - for _, tag := range tags.Tags { - tag := tag - - if o.noclobber { - if _, ok := ignoredTags[tag]; ok { - logs.Progress.Printf("Skipping %s due to no-clobber", tag) - continue - } - } - - g.Go(func() error { - srcTag, err := name.ParseReference(src+":"+tag, o.Name...) - if err != nil { - return fmt.Errorf("failed to parse tag: %w", err) - } - dstTag, err := name.ParseReference(dst+":"+tag, o.Name...) - if err != nil { - return fmt.Errorf("failed to parse tag: %w", err) - } - - logs.Progress.Printf("Fetching %s", srcTag) - desc, err := puller.Get(ctx, srcTag) - if err != nil { - return err - } - - logs.Progress.Printf("Pushing %s", dstTag) - return pusher.Push(ctx, dstTag, desc) - }) - } - } - - return g.Wait() -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/crane/delete.go b/vendor/github.com/google/go-containerregistry/pkg/crane/delete.go deleted file mode 100644 index 58a8be1f0..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/crane/delete.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2018 Google LLC 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 crane - -import ( - "fmt" - - "github.com/google/go-containerregistry/pkg/name" - "github.com/google/go-containerregistry/pkg/v1/remote" -) - -// Delete deletes the remote reference at src. -func Delete(src string, opt ...Option) error { - o := makeOptions(opt...) - ref, err := name.ParseReference(src, o.Name...) - if err != nil { - return fmt.Errorf("parsing reference %q: %w", src, err) - } - - return remote.Delete(ref, o.Remote...) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/crane/digest.go b/vendor/github.com/google/go-containerregistry/pkg/crane/digest.go deleted file mode 100644 index 868a57010..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/crane/digest.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2018 Google LLC 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 crane - -import "github.com/google/go-containerregistry/pkg/logs" - -// Digest returns the sha256 hash of the remote image at ref. -func Digest(ref string, opt ...Option) (string, error) { - o := makeOptions(opt...) - if o.Platform != nil { - desc, err := getManifest(ref, opt...) - if err != nil { - return "", err - } - if !desc.MediaType.IsIndex() { - return desc.Digest.String(), nil - } - - // TODO: does not work for indexes which contain schema v1 manifests - img, err := desc.Image() - if err != nil { - return "", err - } - digest, err := img.Digest() - if err != nil { - return "", err - } - return digest.String(), nil - } - desc, err := Head(ref, opt...) - if err != nil { - logs.Warn.Printf("HEAD request failed, falling back on GET: %v", err) - rdesc, err := getManifest(ref, opt...) - if err != nil { - return "", err - } - return rdesc.Digest.String(), nil - } - return desc.Digest.String(), nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/crane/doc.go b/vendor/github.com/google/go-containerregistry/pkg/crane/doc.go deleted file mode 100644 index 7602d7953..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/crane/doc.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2019 Google LLC 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 crane holds libraries used to implement the crane CLI. -package crane diff --git a/vendor/github.com/google/go-containerregistry/pkg/crane/export.go b/vendor/github.com/google/go-containerregistry/pkg/crane/export.go deleted file mode 100644 index b5e1296d2..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/crane/export.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2018 Google LLC 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 crane - -import ( - "io" - - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/mutate" -) - -// Export writes the filesystem contents (as a tarball) of img to w. -// If img has a single layer, just write the (uncompressed) contents to w so -// that this "just works" for images that just wrap a single blob. -func Export(img v1.Image, w io.Writer) error { - layers, err := img.Layers() - if err != nil { - return err - } - if len(layers) == 1 { - // If it's a single layer... - l := layers[0] - mt, err := l.MediaType() - if err != nil { - return err - } - - if !mt.IsLayer() { - // ...and isn't an OCI mediaType, we don't have to flatten it. - // This lets export work for single layer, non-tarball images. - rc, err := l.Uncompressed() - if err != nil { - return err - } - _, err = io.Copy(w, rc) - return err - } - } - fs := mutate.Extract(img) - _, err = io.Copy(w, fs) - return err -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/crane/filemap.go b/vendor/github.com/google/go-containerregistry/pkg/crane/filemap.go deleted file mode 100644 index 36dfc2a64..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/crane/filemap.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2018 Google LLC 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 crane - -import ( - "archive/tar" - "bytes" - "io" - "sort" - - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/empty" - "github.com/google/go-containerregistry/pkg/v1/mutate" - "github.com/google/go-containerregistry/pkg/v1/tarball" -) - -// Layer creates a layer from a single file map. These layers are reproducible and consistent. -// A filemap is a path -> file content map representing a file system. -func Layer(filemap map[string][]byte) (v1.Layer, error) { - b := &bytes.Buffer{} - w := tar.NewWriter(b) - - fn := []string{} - for f := range filemap { - fn = append(fn, f) - } - sort.Strings(fn) - - for _, f := range fn { - c := filemap[f] - if err := w.WriteHeader(&tar.Header{ - Name: f, - Size: int64(len(c)), - }); err != nil { - return nil, err - } - if _, err := w.Write(c); err != nil { - return nil, err - } - } - if err := w.Close(); err != nil { - return nil, err - } - - // Return a new copy of the buffer each time it's opened. - return tarball.LayerFromOpener(func() (io.ReadCloser, error) { - return io.NopCloser(bytes.NewBuffer(b.Bytes())), nil - }) -} - -// Image creates a image with the given filemaps as its contents. These images are reproducible and consistent. -// A filemap is a path -> file content map representing a file system. -func Image(filemap map[string][]byte) (v1.Image, error) { - y, err := Layer(filemap) - if err != nil { - return nil, err - } - - return mutate.AppendLayers(empty.Image, y) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/crane/get.go b/vendor/github.com/google/go-containerregistry/pkg/crane/get.go deleted file mode 100644 index 98a2e8933..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/crane/get.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2018 Google LLC 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 crane - -import ( - "fmt" - - "github.com/google/go-containerregistry/pkg/name" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/remote" -) - -func getImage(r string, opt ...Option) (v1.Image, name.Reference, error) { - o := makeOptions(opt...) - ref, err := name.ParseReference(r, o.Name...) - if err != nil { - return nil, nil, fmt.Errorf("parsing reference %q: %w", r, err) - } - img, err := remote.Image(ref, o.Remote...) - if err != nil { - return nil, nil, fmt.Errorf("reading image %q: %w", ref, err) - } - return img, ref, nil -} - -func getManifest(r string, opt ...Option) (*remote.Descriptor, error) { - o := makeOptions(opt...) - ref, err := name.ParseReference(r, o.Name...) - if err != nil { - return nil, fmt.Errorf("parsing reference %q: %w", r, err) - } - return remote.Get(ref, o.Remote...) -} - -// Get calls remote.Get and returns an uninterpreted response. -func Get(r string, opt ...Option) (*remote.Descriptor, error) { - return getManifest(r, opt...) -} - -// Head performs a HEAD request for a manifest and returns a content descriptor -// based on the registry's response. -func Head(r string, opt ...Option) (*v1.Descriptor, error) { - o := makeOptions(opt...) - ref, err := name.ParseReference(r, o.Name...) - if err != nil { - return nil, err - } - return remote.Head(ref, o.Remote...) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/crane/list.go b/vendor/github.com/google/go-containerregistry/pkg/crane/list.go deleted file mode 100644 index 38352153b..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/crane/list.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2018 Google LLC 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 crane - -import ( - "fmt" - - "github.com/google/go-containerregistry/pkg/name" - "github.com/google/go-containerregistry/pkg/v1/remote" -) - -// ListTags returns the tags in repository src. -func ListTags(src string, opt ...Option) ([]string, error) { - o := makeOptions(opt...) - repo, err := name.NewRepository(src, o.Name...) - if err != nil { - return nil, fmt.Errorf("parsing repo %q: %w", src, err) - } - - return remote.List(repo, o.Remote...) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/crane/manifest.go b/vendor/github.com/google/go-containerregistry/pkg/crane/manifest.go deleted file mode 100644 index a54926aef..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/crane/manifest.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2018 Google LLC 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 crane - -// Manifest returns the manifest for the remote image or index ref. -func Manifest(ref string, opt ...Option) ([]byte, error) { - desc, err := getManifest(ref, opt...) - if err != nil { - return nil, err - } - o := makeOptions(opt...) - if o.Platform != nil { - img, err := desc.Image() - if err != nil { - return nil, err - } - return img.RawManifest() - } - return desc.Manifest, nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/crane/options.go b/vendor/github.com/google/go-containerregistry/pkg/crane/options.go deleted file mode 100644 index d9d441761..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/crane/options.go +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright 2019 Google LLC 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 crane - -import ( - "context" - "crypto/tls" - "net/http" - - "github.com/google/go-containerregistry/pkg/authn" - "github.com/google/go-containerregistry/pkg/name" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/remote" -) - -// Options hold the options that crane uses when calling other packages. -type Options struct { - Name []name.Option - Remote []remote.Option - Platform *v1.Platform - Keychain authn.Keychain - Transport http.RoundTripper - - auth authn.Authenticator - insecure bool - jobs int - noclobber bool - ctx context.Context -} - -// GetOptions exposes the underlying []remote.Option, []name.Option, and -// platform, based on the passed Option. Generally, you shouldn't need to use -// this unless you've painted yourself into a dependency corner as we have -// with the crane and gcrane cli packages. -func GetOptions(opts ...Option) Options { - return makeOptions(opts...) -} - -func makeOptions(opts ...Option) Options { - opt := Options{ - Remote: []remote.Option{ - remote.WithAuthFromKeychain(authn.DefaultKeychain), - }, - Keychain: authn.DefaultKeychain, - jobs: 4, - ctx: context.Background(), - } - - for _, o := range opts { - o(&opt) - } - - // Allow for untrusted certificates if the user - // passed Insecure but no custom transport. - if opt.insecure && opt.Transport == nil { - transport := remote.DefaultTransport.(*http.Transport).Clone() - transport.TLSClientConfig = &tls.Config{ - InsecureSkipVerify: true, //nolint: gosec - } - - WithTransport(transport)(&opt) - } else if opt.Transport == nil { - opt.Transport = remote.DefaultTransport - } - - return opt -} - -// Option is a functional option for crane. -type Option func(*Options) - -// WithTransport is a functional option for overriding the default transport -// for remote operations. Setting a transport will override the Insecure option's -// configuration allowing for image registries to use untrusted certificates. -func WithTransport(t http.RoundTripper) Option { - return func(o *Options) { - o.Remote = append(o.Remote, remote.WithTransport(t)) - o.Transport = t - } -} - -// Insecure is an Option that allows image references to be fetched without TLS. -// This will also allow for untrusted (e.g. self-signed) certificates in cases where -// the default transport is used (i.e. when WithTransport is not used). -func Insecure(o *Options) { - o.Name = append(o.Name, name.Insecure) - o.insecure = true -} - -// WithPlatform is an Option to specify the platform. -func WithPlatform(platform *v1.Platform) Option { - return func(o *Options) { - if platform != nil { - o.Remote = append(o.Remote, remote.WithPlatform(*platform)) - } - o.Platform = platform - } -} - -// WithAuthFromKeychain is a functional option for overriding the default -// authenticator for remote operations, using an authn.Keychain to find -// credentials. -// -// By default, crane will use authn.DefaultKeychain. -func WithAuthFromKeychain(keys authn.Keychain) Option { - return func(o *Options) { - // Replace the default keychain at position 0. - o.Remote[0] = remote.WithAuthFromKeychain(keys) - o.Keychain = keys - } -} - -// WithAuth is a functional option for overriding the default authenticator -// for remote operations. -// -// By default, crane will use authn.DefaultKeychain. -func WithAuth(auth authn.Authenticator) Option { - return func(o *Options) { - // Replace the default keychain at position 0. - o.Remote[0] = remote.WithAuth(auth) - o.auth = auth - } -} - -// WithUserAgent adds the given string to the User-Agent header for any HTTP -// requests. -func WithUserAgent(ua string) Option { - return func(o *Options) { - o.Remote = append(o.Remote, remote.WithUserAgent(ua)) - } -} - -// WithNondistributable is an option that allows pushing non-distributable -// layers. -func WithNondistributable() Option { - return func(o *Options) { - o.Remote = append(o.Remote, remote.WithNondistributable) - } -} - -// WithContext is a functional option for setting the context. -func WithContext(ctx context.Context) Option { - return func(o *Options) { - o.ctx = ctx - o.Remote = append(o.Remote, remote.WithContext(ctx)) - } -} - -// WithJobs sets the number of concurrent jobs to run. -// -// The default number of jobs is GOMAXPROCS. -func WithJobs(jobs int) Option { - return func(o *Options) { - if jobs > 0 { - o.jobs = jobs - } - o.Remote = append(o.Remote, remote.WithJobs(o.jobs)) - } -} - -// WithNoClobber modifies behavior to avoid overwriting existing tags, if possible. -func WithNoClobber(noclobber bool) Option { - return func(o *Options) { - o.noclobber = noclobber - } -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/crane/pull.go b/vendor/github.com/google/go-containerregistry/pkg/crane/pull.go deleted file mode 100644 index 7e6e5b7b6..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/crane/pull.go +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2018 Google LLC 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 crane - -import ( - "fmt" - "os" - - legacy "github.com/google/go-containerregistry/pkg/legacy/tarball" - "github.com/google/go-containerregistry/pkg/name" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/empty" - "github.com/google/go-containerregistry/pkg/v1/layout" - "github.com/google/go-containerregistry/pkg/v1/remote" - "github.com/google/go-containerregistry/pkg/v1/tarball" -) - -// Tag applied to images that were pulled by digest. This denotes that the -// image was (probably) never tagged with this, but lets us avoid applying the -// ":latest" tag which might be misleading. -const iWasADigestTag = "i-was-a-digest" - -// Pull returns a v1.Image of the remote image src. -func Pull(src string, opt ...Option) (v1.Image, error) { - o := makeOptions(opt...) - ref, err := name.ParseReference(src, o.Name...) - if err != nil { - return nil, fmt.Errorf("parsing reference %q: %w", src, err) - } - - return remote.Image(ref, o.Remote...) -} - -// Save writes the v1.Image img as a tarball at path with tag src. -func Save(img v1.Image, src, path string) error { - imgMap := map[string]v1.Image{src: img} - return MultiSave(imgMap, path) -} - -// MultiSave writes collection of v1.Image img with tag as a tarball. -func MultiSave(imgMap map[string]v1.Image, path string, opt ...Option) error { - o := makeOptions(opt...) - tagToImage := map[name.Tag]v1.Image{} - - for src, img := range imgMap { - ref, err := name.ParseReference(src, o.Name...) - if err != nil { - return fmt.Errorf("parsing ref %q: %w", src, err) - } - - // WriteToFile wants a tag to write to the tarball, but we might have - // been given a digest. - // If the original ref was a tag, use that. Otherwise, if it was a - // digest, tag the image with :i-was-a-digest instead. - tag, ok := ref.(name.Tag) - if !ok { - d, ok := ref.(name.Digest) - if !ok { - return fmt.Errorf("ref wasn't a tag or digest") - } - tag = d.Repository.Tag(iWasADigestTag) - } - tagToImage[tag] = img - } - // no progress channel (for now) - return tarball.MultiWriteToFile(path, tagToImage) -} - -// PullLayer returns the given layer from a registry. -func PullLayer(ref string, opt ...Option) (v1.Layer, error) { - o := makeOptions(opt...) - digest, err := name.NewDigest(ref, o.Name...) - if err != nil { - return nil, err - } - - return remote.Layer(digest, o.Remote...) -} - -// SaveLegacy writes the v1.Image img as a legacy tarball at path with tag src. -func SaveLegacy(img v1.Image, src, path string) error { - imgMap := map[string]v1.Image{src: img} - return MultiSave(imgMap, path) -} - -// MultiSaveLegacy writes collection of v1.Image img with tag as a legacy tarball. -func MultiSaveLegacy(imgMap map[string]v1.Image, path string) error { - refToImage := map[name.Reference]v1.Image{} - - for src, img := range imgMap { - ref, err := name.ParseReference(src) - if err != nil { - return fmt.Errorf("parsing ref %q: %w", src, err) - } - refToImage[ref] = img - } - - w, err := os.Create(path) - if err != nil { - return err - } - defer w.Close() - - return legacy.MultiWrite(refToImage, w) -} - -// SaveOCI writes the v1.Image img as an OCI Image Layout at path. If a layout -// already exists at that path, it will add the image to the index. -func SaveOCI(img v1.Image, path string) error { - imgMap := map[string]v1.Image{"": img} - return MultiSaveOCI(imgMap, path) -} - -// MultiSaveOCI writes collection of v1.Image img as an OCI Image Layout at path. If a layout -// already exists at that path, it will add the image to the index. -func MultiSaveOCI(imgMap map[string]v1.Image, path string) error { - p, err := layout.FromPath(path) - if err != nil { - p, err = layout.Write(path, empty.Index) - if err != nil { - return err - } - } - for _, img := range imgMap { - if err = p.AppendImage(img); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/crane/push.go b/vendor/github.com/google/go-containerregistry/pkg/crane/push.go deleted file mode 100644 index 90a058502..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/crane/push.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2018 Google LLC 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 crane - -import ( - "fmt" - - "github.com/google/go-containerregistry/pkg/name" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/remote" - "github.com/google/go-containerregistry/pkg/v1/tarball" -) - -// Load reads the tarball at path as a v1.Image. -func Load(path string, opt ...Option) (v1.Image, error) { - return LoadTag(path, "", opt...) -} - -// LoadTag reads a tag from the tarball at path as a v1.Image. -// If tag is "", will attempt to read the tarball as a single image. -func LoadTag(path, tag string, opt ...Option) (v1.Image, error) { - if tag == "" { - return tarball.ImageFromPath(path, nil) - } - - o := makeOptions(opt...) - t, err := name.NewTag(tag, o.Name...) - if err != nil { - return nil, fmt.Errorf("parsing tag %q: %w", tag, err) - } - return tarball.ImageFromPath(path, &t) -} - -// Push pushes the v1.Image img to a registry as dst. -func Push(img v1.Image, dst string, opt ...Option) error { - o := makeOptions(opt...) - tag, err := name.ParseReference(dst, o.Name...) - if err != nil { - return fmt.Errorf("parsing reference %q: %w", dst, err) - } - return remote.Write(tag, img, o.Remote...) -} - -// Upload pushes the v1.Layer to a given repo. -func Upload(layer v1.Layer, repo string, opt ...Option) error { - o := makeOptions(opt...) - ref, err := name.NewRepository(repo, o.Name...) - if err != nil { - return fmt.Errorf("parsing repo %q: %w", repo, err) - } - - return remote.WriteLayer(ref, layer, o.Remote...) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/crane/tag.go b/vendor/github.com/google/go-containerregistry/pkg/crane/tag.go deleted file mode 100644 index 13bc39587..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/crane/tag.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2019 Google LLC 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 crane - -import ( - "fmt" - - "github.com/google/go-containerregistry/pkg/name" - "github.com/google/go-containerregistry/pkg/v1/remote" -) - -// Tag adds tag to the remote img. -func Tag(img, tag string, opt ...Option) error { - o := makeOptions(opt...) - ref, err := name.ParseReference(img, o.Name...) - if err != nil { - return fmt.Errorf("parsing reference %q: %w", img, err) - } - desc, err := remote.Get(ref, o.Remote...) - if err != nil { - return fmt.Errorf("fetching %q: %w", img, err) - } - - dst := ref.Context().Tag(tag) - - return remote.Tag(dst, desc, o.Remote...) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/legacy/config.go b/vendor/github.com/google/go-containerregistry/pkg/legacy/config.go deleted file mode 100644 index 3364bec61..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/legacy/config.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2019 Google LLC 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 legacy - -import ( - v1 "github.com/google/go-containerregistry/pkg/v1" -) - -// LayerConfigFile is the configuration file that holds the metadata describing -// a v1 layer. See: -// https://github.com/moby/moby/blob/master/image/spec/v1.md -type LayerConfigFile struct { - v1.ConfigFile - - ContainerConfig v1.Config `json:"container_config,omitempty"` - - ID string `json:"id,omitempty"` - Parent string `json:"parent,omitempty"` - Throwaway bool `json:"throwaway,omitempty"` - Comment string `json:"comment,omitempty"` -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/legacy/doc.go b/vendor/github.com/google/go-containerregistry/pkg/legacy/doc.go deleted file mode 100644 index 1d1668887..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/legacy/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2019 Google LLC 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 legacy provides functionality to work with docker images in the v1 -// format. -// See: https://github.com/moby/moby/blob/master/image/spec/v1.md -package legacy diff --git a/vendor/github.com/google/go-containerregistry/pkg/legacy/tarball/README.md b/vendor/github.com/google/go-containerregistry/pkg/legacy/tarball/README.md deleted file mode 100644 index 90b88c757..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/legacy/tarball/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# `legacy/tarball` - -[![GoDoc](https://godoc.org/github.com/google/go-containerregistry/pkg/legacy/tarball?status.svg)](https://godoc.org/github.com/google/go-containerregistry/pkg/legacy/tarball) - -This package implements support for writing legacy tarballs, as described -[here](https://github.com/moby/moby/blob/749d90e10f989802638ae542daf54257f3bf71f2/image/spec/v1.2.md#combined-image-json--filesystem-changeset-format). diff --git a/vendor/github.com/google/go-containerregistry/pkg/legacy/tarball/doc.go b/vendor/github.com/google/go-containerregistry/pkg/legacy/tarball/doc.go deleted file mode 100644 index 62684d6e7..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/legacy/tarball/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2019 Google LLC 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 tarball provides facilities for writing v1 docker images -// (https://github.com/moby/moby/blob/master/image/spec/v1.md) from/to a tarball -// on-disk. -package tarball diff --git a/vendor/github.com/google/go-containerregistry/pkg/legacy/tarball/write.go b/vendor/github.com/google/go-containerregistry/pkg/legacy/tarball/write.go deleted file mode 100644 index 627bfbfdb..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/legacy/tarball/write.go +++ /dev/null @@ -1,371 +0,0 @@ -// Copyright 2019 Google LLC 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 tarball - -import ( - "archive/tar" - "bytes" - "encoding/json" - "fmt" - "io" - "sort" - "strings" - - "github.com/google/go-containerregistry/pkg/legacy" - "github.com/google/go-containerregistry/pkg/name" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/partial" - "github.com/google/go-containerregistry/pkg/v1/tarball" -) - -// repositoriesTarDescriptor represents the repositories file inside a `docker save` tarball. -type repositoriesTarDescriptor map[string]map[string]string - -// v1Layer represents a layer with metadata needed by the v1 image spec https://github.com/moby/moby/blob/master/image/spec/v1.md. -type v1Layer struct { - // config is the layer metadata. - config *legacy.LayerConfigFile - // layer is the v1.Layer object this v1Layer represents. - layer v1.Layer -} - -// json returns the raw bytes of the json metadata of the given v1Layer. -func (l *v1Layer) json() ([]byte, error) { - return json.Marshal(l.config) -} - -// version returns the raw bytes of the "VERSION" file of the given v1Layer. -func (l *v1Layer) version() []byte { - return []byte("1.0") -} - -// v1LayerID computes the v1 image format layer id for the given v1.Layer with the given v1 parent ID and raw image config. -func v1LayerID(layer v1.Layer, parentID string, rawConfig []byte) (string, error) { - d, err := layer.Digest() - if err != nil { - return "", fmt.Errorf("unable to get layer digest to generate v1 layer ID: %w", err) - } - s := fmt.Sprintf("%s %s", d.Hex, parentID) - if len(rawConfig) != 0 { - s = fmt.Sprintf("%s %s", s, string(rawConfig)) - } - - h, _, _ := v1.SHA256(strings.NewReader(s)) - return h.Hex, nil -} - -// newTopV1Layer creates a new v1Layer for a layer other than the top layer in a v1 image tarball. -func newV1Layer(layer v1.Layer, parent *v1Layer, history v1.History) (*v1Layer, error) { - parentID := "" - if parent != nil { - parentID = parent.config.ID - } - id, err := v1LayerID(layer, parentID, nil) - if err != nil { - return nil, fmt.Errorf("unable to generate v1 layer ID: %w", err) - } - result := &v1Layer{ - layer: layer, - config: &legacy.LayerConfigFile{ - ConfigFile: v1.ConfigFile{ - Created: history.Created, - Author: history.Author, - }, - ContainerConfig: v1.Config{ - Cmd: []string{history.CreatedBy}, - }, - ID: id, - Parent: parentID, - Throwaway: history.EmptyLayer, - Comment: history.Comment, - }, - } - return result, nil -} - -// newTopV1Layer creates a new v1Layer for the top layer in a v1 image tarball. -func newTopV1Layer(layer v1.Layer, parent *v1Layer, history v1.History, imgConfig *v1.ConfigFile, rawConfig []byte) (*v1Layer, error) { - result, err := newV1Layer(layer, parent, history) - if err != nil { - return nil, err - } - id, err := v1LayerID(layer, result.config.Parent, rawConfig) - if err != nil { - return nil, fmt.Errorf("unable to generate v1 layer ID for top layer: %w", err) - } - result.config.ID = id - result.config.Architecture = imgConfig.Architecture - result.config.Container = imgConfig.Container - result.config.DockerVersion = imgConfig.DockerVersion - result.config.OS = imgConfig.OS - result.config.Config = imgConfig.Config - result.config.Created = imgConfig.Created - return result, nil -} - -// splitTag splits the given tagged image name /: -// into / and . -func splitTag(name string) (string, string) { - // Split on ":" - parts := strings.Split(name, ":") - // Verify that we aren't confusing a tag for a hostname w/ port for the purposes of weak validation. - if len(parts) > 1 && !strings.Contains(parts[len(parts)-1], "/") { - base := strings.Join(parts[:len(parts)-1], ":") - tag := parts[len(parts)-1] - return base, tag - } - return name, "" -} - -// addTags adds the given image tags to the given "repositories" file descriptor in a v1 image tarball. -func addTags(repos repositoriesTarDescriptor, tags []string, topLayerID string) { - for _, t := range tags { - base, tag := splitTag(t) - tagToID, ok := repos[base] - if !ok { - tagToID = make(map[string]string) - repos[base] = tagToID - } - tagToID[tag] = topLayerID - } -} - -// updateLayerSources updates the given layer digest to descriptor map with the descriptor of the given layer in the given image if it's an undistributable layer. -func updateLayerSources(layerSources map[v1.Hash]v1.Descriptor, layer v1.Layer, img v1.Image) error { - d, err := layer.Digest() - if err != nil { - return err - } - // Add to LayerSources if it's a foreign layer. - desc, err := partial.BlobDescriptor(img, d) - if err != nil { - return err - } - if !desc.MediaType.IsDistributable() { - diffid, err := partial.BlobToDiffID(img, d) - if err != nil { - return err - } - layerSources[diffid] = *desc - } - return nil -} - -// Write is a wrapper to write a single image in V1 format and tag to a tarball. -func Write(ref name.Reference, img v1.Image, w io.Writer) error { - return MultiWrite(map[name.Reference]v1.Image{ref: img}, w) -} - -// filterEmpty filters out the history corresponding to empty layers from the -// given history. -func filterEmpty(h []v1.History) []v1.History { - result := []v1.History{} - for _, i := range h { - if i.EmptyLayer { - continue - } - result = append(result, i) - } - return result -} - -// MultiWrite writes the contents of each image to the provided reader, in the V1 image tarball format. -// The contents are written in the following format: -// One manifest.json file at the top level containing information about several images. -// One repositories file mapping from the image / to to the id of the top most layer. -// For every layer, a directory named with the layer ID is created with the following contents: -// -// layer.tar - The uncompressed layer tarball. -// .json- Layer metadata json. -// VERSION- Schema version string. Always set to "1.0". -// -// One file for the config blob, named after its SHA. -func MultiWrite(refToImage map[name.Reference]v1.Image, w io.Writer) error { - tf := tar.NewWriter(w) - defer tf.Close() - - sortedImages, imageToTags := dedupRefToImage(refToImage) - var m tarball.Manifest - repos := make(repositoriesTarDescriptor) - - seenLayerIDs := make(map[string]struct{}) - for _, img := range sortedImages { - tags := imageToTags[img] - - // Write the config. - cfgName, err := img.ConfigName() - if err != nil { - return err - } - cfgFileName := fmt.Sprintf("%s.json", cfgName.Hex) - cfgBlob, err := img.RawConfigFile() - if err != nil { - return err - } - if err := writeTarEntry(tf, cfgFileName, bytes.NewReader(cfgBlob), int64(len(cfgBlob))); err != nil { - return err - } - cfg, err := img.ConfigFile() - if err != nil { - return err - } - - // Store foreign layer info. - layerSources := make(map[v1.Hash]v1.Descriptor) - - // Write the layers. - layers, err := img.Layers() - if err != nil { - return err - } - history := filterEmpty(cfg.History) - // Create a blank config history if the config didn't have a history. - if len(history) == 0 && len(layers) != 0 { - history = make([]v1.History, len(layers)) - } else if len(layers) != len(history) { - return fmt.Errorf("image config had layer history which did not match the number of layers, got len(history)=%d, len(layers)=%d, want len(history)=len(layers)", len(history), len(layers)) - } - layerFiles := make([]string, len(layers)) - var prev *v1Layer - for i, l := range layers { - if err := updateLayerSources(layerSources, l, img); err != nil { - return fmt.Errorf("unable to update image metadata to include undistributable layer source information: %w", err) - } - var cur *v1Layer - if i < (len(layers) - 1) { - cur, err = newV1Layer(l, prev, history[i]) - } else { - cur, err = newTopV1Layer(l, prev, history[i], cfg, cfgBlob) - } - if err != nil { - return err - } - layerFiles[i] = fmt.Sprintf("%s/layer.tar", cur.config.ID) - if _, ok := seenLayerIDs[cur.config.ID]; ok { - prev = cur - continue - } - seenLayerIDs[cur.config.ID] = struct{}{} - - // If the v1.Layer implements UncompressedSize efficiently, use that - // for the tar header. Otherwise, this iterates over Uncompressed(). - // NOTE: If using a streaming layer, this may consume the layer. - size, err := partial.UncompressedSize(l) - if err != nil { - return err - } - u, err := l.Uncompressed() - if err != nil { - return err - } - defer u.Close() - if err := writeTarEntry(tf, layerFiles[i], u, size); err != nil { - return err - } - - j, err := cur.json() - if err != nil { - return err - } - if err := writeTarEntry(tf, fmt.Sprintf("%s/json", cur.config.ID), bytes.NewReader(j), int64(len(j))); err != nil { - return err - } - v := cur.version() - if err := writeTarEntry(tf, fmt.Sprintf("%s/VERSION", cur.config.ID), bytes.NewReader(v), int64(len(v))); err != nil { - return err - } - prev = cur - } - - // Generate the tar descriptor and write it. - m = append(m, tarball.Descriptor{ - Config: cfgFileName, - RepoTags: tags, - Layers: layerFiles, - LayerSources: layerSources, - }) - // prev should be the top layer here. Use it to add the image tags - // to the tarball repositories file. - addTags(repos, tags, prev.config.ID) - } - - mBytes, err := json.Marshal(m) - if err != nil { - return err - } - - if err := writeTarEntry(tf, "manifest.json", bytes.NewReader(mBytes), int64(len(mBytes))); err != nil { - return err - } - reposBytes, err := json.Marshal(&repos) - if err != nil { - return err - } - return writeTarEntry(tf, "repositories", bytes.NewReader(reposBytes), int64(len(reposBytes))) -} - -func dedupRefToImage(refToImage map[name.Reference]v1.Image) ([]v1.Image, map[v1.Image][]string) { - imageToTags := make(map[v1.Image][]string) - - for ref, img := range refToImage { - if tag, ok := ref.(name.Tag); ok { - if tags, ok := imageToTags[img]; ok && tags != nil { - imageToTags[img] = append(tags, tag.String()) - } else { - imageToTags[img] = []string{tag.String()} - } - } else { - if _, ok := imageToTags[img]; !ok { - imageToTags[img] = nil - } - } - } - - // Force specific order on tags - imgs := []v1.Image{} - for img, tags := range imageToTags { - sort.Strings(tags) - imgs = append(imgs, img) - } - - sort.Slice(imgs, func(i, j int) bool { - cfI, err := imgs[i].ConfigName() - if err != nil { - return false - } - cfJ, err := imgs[j].ConfigName() - if err != nil { - return false - } - return cfI.Hex < cfJ.Hex - }) - - return imgs, imageToTags -} - -// Writes a file to the provided writer with a corresponding tar header -func writeTarEntry(tf *tar.Writer, path string, r io.Reader, size int64) error { - hdr := &tar.Header{ - Mode: 0644, - Typeflag: tar.TypeReg, - Size: size, - Name: path, - } - if err := tf.WriteHeader(hdr); err != nil { - return err - } - _, err := io.Copy(tf, r) - return err -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/logs/logs.go b/vendor/github.com/google/go-containerregistry/pkg/logs/logs.go deleted file mode 100644 index a5d25b188..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/logs/logs.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2018 Google LLC 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 logs exposes the loggers used by this library. -package logs - -import ( - "io" - "log" -) - -var ( - // Warn is used to log non-fatal errors. - Warn = log.New(io.Discard, "", log.LstdFlags) - - // Progress is used to log notable, successful events. - Progress = log.New(io.Discard, "", log.LstdFlags) - - // Debug is used to log information that is useful for debugging. - Debug = log.New(io.Discard, "", log.LstdFlags) -) - -// Enabled checks to see if the logger's writer is set to something other -// than io.Discard. This allows callers to avoid expensive operations -// that will end up in /dev/null anyway. -func Enabled(l *log.Logger) bool { - return l.Writer() != io.Discard -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/README.md b/vendor/github.com/google/go-containerregistry/pkg/name/README.md deleted file mode 100644 index 4889b8446..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/name/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# `name` - -[![GoDoc](https://godoc.org/github.com/google/go-containerregistry/pkg/name?status.svg)](https://godoc.org/github.com/google/go-containerregistry/pkg/name) diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/check.go b/vendor/github.com/google/go-containerregistry/pkg/name/check.go deleted file mode 100644 index e9a240a3e..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/name/check.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2018 Google LLC 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 name - -import ( - "strings" - "unicode/utf8" -) - -// stripRunesFn returns a function which returns -1 (i.e. a value which -// signals deletion in strings.Map) for runes in 'runes', and the rune otherwise. -func stripRunesFn(runes string) func(rune) rune { - return func(r rune) rune { - if strings.ContainsRune(runes, r) { - return -1 - } - return r - } -} - -// checkElement checks a given named element matches character and length restrictions. -// Returns true if the given element adheres to the given restrictions, false otherwise. -func checkElement(name, element, allowedRunes string, minRunes, maxRunes int) error { - numRunes := utf8.RuneCountInString(element) - if (numRunes < minRunes) || (maxRunes < numRunes) { - return newErrBadName("%s must be between %d and %d characters in length: %s", name, minRunes, maxRunes, element) - } else if len(strings.Map(stripRunesFn(allowedRunes), element)) != 0 { - return newErrBadName("%s can only contain the characters `%s`: %s", name, allowedRunes, element) - } - return nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/digest.go b/vendor/github.com/google/go-containerregistry/pkg/name/digest.go deleted file mode 100644 index c049c1ef4..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/name/digest.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2018 Google LLC 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 name - -import ( - // nolint: depguard - _ "crypto/sha256" // Recommended by go-digest. - "strings" - - "github.com/opencontainers/go-digest" -) - -const digestDelim = "@" - -// Digest stores a digest name in a structured form. -type Digest struct { - Repository - digest string - original string -} - -// Ensure Digest implements Reference -var _ Reference = (*Digest)(nil) - -// Context implements Reference. -func (d Digest) Context() Repository { - return d.Repository -} - -// Identifier implements Reference. -func (d Digest) Identifier() string { - return d.DigestStr() -} - -// DigestStr returns the digest component of the Digest. -func (d Digest) DigestStr() string { - return d.digest -} - -// Name returns the name from which the Digest was derived. -func (d Digest) Name() string { - return d.Repository.Name() + digestDelim + d.DigestStr() -} - -// String returns the original input string. -func (d Digest) String() string { - return d.original -} - -// NewDigest returns a new Digest representing the given name. -func NewDigest(name string, opts ...Option) (Digest, error) { - // Split on "@" - parts := strings.Split(name, digestDelim) - if len(parts) != 2 { - return Digest{}, newErrBadName("a digest must contain exactly one '@' separator (e.g. registry/repository@digest) saw: %s", name) - } - base := parts[0] - dig := parts[1] - prefix := digest.Canonical.String() + ":" - if !strings.HasPrefix(dig, prefix) { - return Digest{}, newErrBadName("unsupported digest algorithm: %s", dig) - } - hex := strings.TrimPrefix(dig, prefix) - if err := digest.Canonical.Validate(hex); err != nil { - return Digest{}, err - } - - tag, err := NewTag(base, opts...) - if err == nil { - base = tag.Repository.Name() - } - - repo, err := NewRepository(base, opts...) - if err != nil { - return Digest{}, err - } - return Digest{ - Repository: repo, - digest: dig, - original: name, - }, nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/doc.go b/vendor/github.com/google/go-containerregistry/pkg/name/doc.go deleted file mode 100644 index b294794dc..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/name/doc.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2018 Google LLC 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 name defines structured types for representing image references. -// -// What's in a name? For image references, not nearly enough! -// -// Image references look a lot like URLs, but they differ in that they don't -// contain the scheme (http or https), they can end with a :tag or a @digest -// (the latter being validated), and they perform defaulting for missing -// components. -// -// Since image references don't contain the scheme, we do our best to infer -// if we use http or https from the given hostname. We allow http fallback for -// any host that looks like localhost (localhost, 127.0.0.1, ::1), ends in -// ".local", or is in the "private" address space per RFC 1918. For everything -// else, we assume https only. To override this heuristic, use the Insecure -// option. -// -// Image references with a digest signal to us that we should verify the content -// of the image matches the digest. E.g. when pulling a Digest reference, we'll -// calculate the sha256 of the manifest returned by the registry and error out -// if it doesn't match what we asked for. -// -// For defaulting, we interpret "ubuntu" as -// "index.docker.io/library/ubuntu:latest" because we add the missing repo -// "library", the missing registry "index.docker.io", and the missing tag -// "latest". To disable this defaulting, use the StrictValidation option. This -// is useful e.g. to only allow image references that explicitly set a tag or -// digest, so that you don't accidentally pull "latest". -package name diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/errors.go b/vendor/github.com/google/go-containerregistry/pkg/name/errors.go deleted file mode 100644 index bf004ffcf..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/name/errors.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2018 Google LLC 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 name - -import ( - "errors" - "fmt" -) - -// ErrBadName is an error for when a bad docker name is supplied. -type ErrBadName struct { - info string -} - -func (e *ErrBadName) Error() string { - return e.info -} - -// Is reports whether target is an error of type ErrBadName -func (e *ErrBadName) Is(target error) bool { - var berr *ErrBadName - return errors.As(target, &berr) -} - -// newErrBadName returns a ErrBadName which returns the given formatted string from Error(). -func newErrBadName(fmtStr string, args ...any) *ErrBadName { - return &ErrBadName{fmt.Sprintf(fmtStr, args...)} -} - -// IsErrBadName returns true if the given error is an ErrBadName. -// -// Deprecated: Use errors.Is. -func IsErrBadName(err error) bool { - var berr *ErrBadName - return errors.As(err, &berr) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/options.go b/vendor/github.com/google/go-containerregistry/pkg/name/options.go deleted file mode 100644 index d14fedcda..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/name/options.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2018 Google LLC 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 name - -const ( - // DefaultRegistry is the registry name that will be used if no registry - // provided and the default is not overridden. - DefaultRegistry = "index.docker.io" - defaultRegistryAlias = "docker.io" - - // DefaultTag is the tag name that will be used if no tag provided and the - // default is not overridden. - DefaultTag = "latest" -) - -type options struct { - strict bool // weak by default - insecure bool // secure by default - defaultRegistry string - defaultTag string -} - -func makeOptions(opts ...Option) options { - opt := options{ - defaultRegistry: DefaultRegistry, - defaultTag: DefaultTag, - } - for _, o := range opts { - o(&opt) - } - return opt -} - -// Option is a functional option for name parsing. -type Option func(*options) - -// StrictValidation is an Option that requires image references to be fully -// specified; i.e. no defaulting for registry (dockerhub), repo (library), -// or tag (latest). -func StrictValidation(opts *options) { - opts.strict = true -} - -// WeakValidation is an Option that sets defaults when parsing names, see -// StrictValidation. -func WeakValidation(opts *options) { - opts.strict = false -} - -// Insecure is an Option that allows image references to be fetched without TLS. -func Insecure(opts *options) { - opts.insecure = true -} - -// OptionFn is a function that returns an option. -type OptionFn func() Option - -// WithDefaultRegistry sets the default registry that will be used if one is not -// provided. -func WithDefaultRegistry(r string) Option { - return func(opts *options) { - opts.defaultRegistry = r - } -} - -// WithDefaultTag sets the default tag that will be used if one is not provided. -func WithDefaultTag(t string) Option { - return func(opts *options) { - opts.defaultTag = t - } -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/ref.go b/vendor/github.com/google/go-containerregistry/pkg/name/ref.go deleted file mode 100644 index 912ab3301..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/name/ref.go +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright 2018 Google LLC 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 name - -import ( - "fmt" -) - -// Reference defines the interface that consumers use when they can -// take either a tag or a digest. -type Reference interface { - fmt.Stringer - - // Context accesses the Repository context of the reference. - Context() Repository - - // Identifier accesses the type-specific portion of the reference. - Identifier() string - - // Name is the fully-qualified reference name. - Name() string - - // Scope is the scope needed to access this reference. - Scope(string) string -} - -// ParseReference parses the string as a reference, either by tag or digest. -func ParseReference(s string, opts ...Option) (Reference, error) { - if t, err := NewTag(s, opts...); err == nil { - return t, nil - } - if d, err := NewDigest(s, opts...); err == nil { - return d, nil - } - return nil, newErrBadName("could not parse reference: " + s) -} - -type stringConst string - -// MustParseReference behaves like ParseReference, but panics instead of -// returning an error. It's intended for use in tests, or when a value is -// expected to be valid at code authoring time. -// -// To discourage its use in scenarios where the value is not known at code -// authoring time, it must be passed a string constant: -// -// const str = "valid/string" -// MustParseReference(str) -// MustParseReference("another/valid/string") -// MustParseReference(str + "/and/more") -// -// These will not compile: -// -// var str = "valid/string" -// MustParseReference(str) -// MustParseReference(strings.Join([]string{"valid", "string"}, "/")) -func MustParseReference(s stringConst, opts ...Option) Reference { - ref, err := ParseReference(string(s), opts...) - if err != nil { - panic(err) - } - return ref -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/registry.go b/vendor/github.com/google/go-containerregistry/pkg/name/registry.go deleted file mode 100644 index 5b0d01769..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/name/registry.go +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2018 Google LLC 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 name - -import ( - "net" - "net/url" - "path" - "regexp" - "strings" -) - -// Detect more complex forms of local references. -var reLocal = regexp.MustCompile(`.*\.local(?:host)?(?::\d{1,5})?$`) - -// Detect the loopback IP (127.0.0.1) -var reLoopback = regexp.MustCompile(regexp.QuoteMeta("127.0.0.1")) - -// Detect the loopback IPV6 (::1) -var reipv6Loopback = regexp.MustCompile(regexp.QuoteMeta("::1")) - -// Registry stores a docker registry name in a structured form. -type Registry struct { - insecure bool - registry string -} - -// RegistryStr returns the registry component of the Registry. -func (r Registry) RegistryStr() string { - return r.registry -} - -// Name returns the name from which the Registry was derived. -func (r Registry) Name() string { - return r.RegistryStr() -} - -func (r Registry) String() string { - return r.Name() -} - -// Repo returns a Repository in the Registry with the given name. -func (r Registry) Repo(repo ...string) Repository { - return Repository{Registry: r, repository: path.Join(repo...)} -} - -// Scope returns the scope required to access the registry. -func (r Registry) Scope(string) string { - // The only resource under 'registry' is 'catalog'. http://goo.gl/N9cN9Z - return "registry:catalog:*" -} - -func (r Registry) isRFC1918() bool { - ipStr := strings.Split(r.Name(), ":")[0] - ip := net.ParseIP(ipStr) - if ip == nil { - return false - } - for _, cidr := range []string{"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"} { - _, block, _ := net.ParseCIDR(cidr) - if block.Contains(ip) { - return true - } - } - return false -} - -// Scheme returns https scheme for all the endpoints except localhost or when explicitly defined. -func (r Registry) Scheme() string { - if r.insecure { - return "http" - } - if r.isRFC1918() { - return "http" - } - if strings.HasPrefix(r.Name(), "localhost:") { - return "http" - } - if reLocal.MatchString(r.Name()) { - return "http" - } - if reLoopback.MatchString(r.Name()) { - return "http" - } - if reipv6Loopback.MatchString(r.Name()) { - return "http" - } - return "https" -} - -func checkRegistry(name string) error { - // Per RFC 3986, registries (authorities) are required to be prefixed with "//" - // url.Host == hostname[:port] == authority - if url, err := url.Parse("//" + name); err != nil || url.Host != name { - return newErrBadName("registries must be valid RFC 3986 URI authorities: %s", name) - } - return nil -} - -// NewRegistry returns a Registry based on the given name. -// Strict validation requires explicit, valid RFC 3986 URI authorities to be given. -func NewRegistry(name string, opts ...Option) (Registry, error) { - opt := makeOptions(opts...) - if opt.strict && len(name) == 0 { - return Registry{}, newErrBadName("strict validation requires the registry to be explicitly defined") - } - - if err := checkRegistry(name); err != nil { - return Registry{}, err - } - - if name == "" { - name = opt.defaultRegistry - } - // Rewrite "docker.io" to "index.docker.io". - // See: https://github.com/google/go-containerregistry/issues/68 - if name == defaultRegistryAlias { - name = DefaultRegistry - } - - return Registry{registry: name, insecure: opt.insecure}, nil -} - -// NewInsecureRegistry returns an Insecure Registry based on the given name. -// -// Deprecated: Use the Insecure Option with NewRegistry instead. -func NewInsecureRegistry(name string, opts ...Option) (Registry, error) { - opts = append(opts, Insecure) - return NewRegistry(name, opts...) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/repository.go b/vendor/github.com/google/go-containerregistry/pkg/name/repository.go deleted file mode 100644 index 9250e3625..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/name/repository.go +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2018 Google LLC 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 name - -import ( - "fmt" - "strings" -) - -const ( - defaultNamespace = "library" - repositoryChars = "abcdefghijklmnopqrstuvwxyz0123456789_-./" - regRepoDelimiter = "/" -) - -// Repository stores a docker repository name in a structured form. -type Repository struct { - Registry - repository string -} - -// See https://docs.docker.com/docker-hub/official_repos -func hasImplicitNamespace(repo string, reg Registry) bool { - return !strings.ContainsRune(repo, '/') && reg.RegistryStr() == DefaultRegistry -} - -// RepositoryStr returns the repository component of the Repository. -func (r Repository) RepositoryStr() string { - if hasImplicitNamespace(r.repository, r.Registry) { - return fmt.Sprintf("%s/%s", defaultNamespace, r.repository) - } - return r.repository -} - -// Name returns the name from which the Repository was derived. -func (r Repository) Name() string { - regName := r.Registry.Name() - if regName != "" { - return regName + regRepoDelimiter + r.RepositoryStr() - } - // TODO: As far as I can tell, this is unreachable. - return r.RepositoryStr() -} - -func (r Repository) String() string { - return r.Name() -} - -// Scope returns the scope required to perform the given action on the registry. -// TODO(jonjohnsonjr): consider moving scopes to a separate package. -func (r Repository) Scope(action string) string { - return fmt.Sprintf("repository:%s:%s", r.RepositoryStr(), action) -} - -func checkRepository(repository string) error { - return checkElement("repository", repository, repositoryChars, 2, 255) -} - -// NewRepository returns a new Repository representing the given name, according to the given strictness. -func NewRepository(name string, opts ...Option) (Repository, error) { - opt := makeOptions(opts...) - if len(name) == 0 { - return Repository{}, newErrBadName("a repository name must be specified") - } - - var registry string - repo := name - parts := strings.SplitN(name, regRepoDelimiter, 2) - if len(parts) == 2 && (strings.ContainsRune(parts[0], '.') || strings.ContainsRune(parts[0], ':')) { - // The first part of the repository is treated as the registry domain - // iff it contains a '.' or ':' character, otherwise it is all repository - // and the domain defaults to Docker Hub. - registry = parts[0] - repo = parts[1] - } - - if err := checkRepository(repo); err != nil { - return Repository{}, err - } - - reg, err := NewRegistry(registry, opts...) - if err != nil { - return Repository{}, err - } - if hasImplicitNamespace(repo, reg) && opt.strict { - return Repository{}, newErrBadName("strict validation requires the full repository path (missing 'library')") - } - return Repository{reg, repo}, nil -} - -// Tag returns a Tag in this Repository. -func (r Repository) Tag(identifier string) Tag { - t := Tag{ - tag: identifier, - Repository: r, - } - t.original = t.Name() - return t -} - -// Digest returns a Digest in this Repository. -func (r Repository) Digest(identifier string) Digest { - d := Digest{ - digest: identifier, - Repository: r, - } - d.original = d.Name() - return d -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/name/tag.go b/vendor/github.com/google/go-containerregistry/pkg/name/tag.go deleted file mode 100644 index 66bd1bec3..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/name/tag.go +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2018 Google LLC 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 name - -import ( - "strings" -) - -const ( - // TODO(dekkagaijin): use the docker/distribution regexes for validation. - tagChars = "abcdefghijklmnopqrstuvwxyz0123456789_-.ABCDEFGHIJKLMNOPQRSTUVWXYZ" - tagDelim = ":" -) - -// Tag stores a docker tag name in a structured form. -type Tag struct { - Repository - tag string - original string -} - -// Ensure Tag implements Reference -var _ Reference = (*Tag)(nil) - -// Context implements Reference. -func (t Tag) Context() Repository { - return t.Repository -} - -// Identifier implements Reference. -func (t Tag) Identifier() string { - return t.TagStr() -} - -// TagStr returns the tag component of the Tag. -func (t Tag) TagStr() string { - return t.tag -} - -// Name returns the name from which the Tag was derived. -func (t Tag) Name() string { - return t.Repository.Name() + tagDelim + t.TagStr() -} - -// String returns the original input string. -func (t Tag) String() string { - return t.original -} - -// Scope returns the scope required to perform the given action on the tag. -func (t Tag) Scope(action string) string { - return t.Repository.Scope(action) -} - -func checkTag(name string) error { - return checkElement("tag", name, tagChars, 1, 128) -} - -// NewTag returns a new Tag representing the given name, according to the given strictness. -func NewTag(name string, opts ...Option) (Tag, error) { - opt := makeOptions(opts...) - base := name - tag := "" - - // Split on ":" - parts := strings.Split(name, tagDelim) - // Verify that we aren't confusing a tag for a hostname w/ port for the purposes of weak validation. - if len(parts) > 1 && !strings.Contains(parts[len(parts)-1], regRepoDelimiter) { - base = strings.Join(parts[:len(parts)-1], tagDelim) - tag = parts[len(parts)-1] - } - - // We don't require a tag, but if we get one check it's valid, - // even when not being strict. - // If we are being strict, we want to validate the tag regardless in case - // it's empty. - if tag != "" || opt.strict { - if err := checkTag(tag); err != nil { - return Tag{}, err - } - } - - if tag == "" { - tag = opt.defaultTag - } - - repo, err := NewRepository(base, opts...) - if err != nil { - return Tag{}, err - } - return Tag{ - Repository: repo, - tag: tag, - original: name, - }, nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/config.go b/vendor/github.com/google/go-containerregistry/pkg/v1/config.go deleted file mode 100644 index 960c93b5f..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/config.go +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright 2018 Google LLC 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 v1 - -import ( - "encoding/json" - "io" - "time" -) - -// ConfigFile is the configuration file that holds the metadata describing -// how to launch a container. See: -// https://github.com/opencontainers/image-spec/blob/master/config.md -// -// docker_version and os.version are not part of the spec but included -// for backwards compatibility. -type ConfigFile struct { - Architecture string `json:"architecture"` - Author string `json:"author,omitempty"` - Container string `json:"container,omitempty"` - Created Time `json:"created,omitempty"` - DockerVersion string `json:"docker_version,omitempty"` - History []History `json:"history,omitempty"` - OS string `json:"os"` - RootFS RootFS `json:"rootfs"` - Config Config `json:"config"` - OSVersion string `json:"os.version,omitempty"` - Variant string `json:"variant,omitempty"` - OSFeatures []string `json:"os.features,omitempty"` -} - -// Platform attempts to generates a Platform from the ConfigFile fields. -func (cf *ConfigFile) Platform() *Platform { - if cf.OS == "" && cf.Architecture == "" && cf.OSVersion == "" && cf.Variant == "" && len(cf.OSFeatures) == 0 { - return nil - } - return &Platform{ - OS: cf.OS, - Architecture: cf.Architecture, - OSVersion: cf.OSVersion, - Variant: cf.Variant, - OSFeatures: cf.OSFeatures, - } -} - -// History is one entry of a list recording how this container image was built. -type History struct { - Author string `json:"author,omitempty"` - Created Time `json:"created,omitempty"` - CreatedBy string `json:"created_by,omitempty"` - Comment string `json:"comment,omitempty"` - EmptyLayer bool `json:"empty_layer,omitempty"` -} - -// Time is a wrapper around time.Time to help with deep copying -type Time struct { - time.Time -} - -// DeepCopyInto creates a deep-copy of the Time value. The underlying time.Time -// type is effectively immutable in the time API, so it is safe to -// copy-by-assign, despite the presence of (unexported) Pointer fields. -func (t *Time) DeepCopyInto(out *Time) { - *out = *t -} - -// RootFS holds the ordered list of file system deltas that comprise the -// container image's root filesystem. -type RootFS struct { - Type string `json:"type"` - DiffIDs []Hash `json:"diff_ids"` -} - -// HealthConfig holds configuration settings for the HEALTHCHECK feature. -type HealthConfig struct { - // Test is the test to perform to check that the container is healthy. - // An empty slice means to inherit the default. - // The options are: - // {} : inherit healthcheck - // {"NONE"} : disable healthcheck - // {"CMD", args...} : exec arguments directly - // {"CMD-SHELL", command} : run command with system's default shell - Test []string `json:",omitempty"` - - // Zero means to inherit. Durations are expressed as integer nanoseconds. - Interval time.Duration `json:",omitempty"` // Interval is the time to wait between checks. - Timeout time.Duration `json:",omitempty"` // Timeout is the time to wait before considering the check to have hung. - StartPeriod time.Duration `json:",omitempty"` // The start period for the container to initialize before the retries starts to count down. - - // Retries is the number of consecutive failures needed to consider a container as unhealthy. - // Zero means inherit. - Retries int `json:",omitempty"` -} - -// Config is a submessage of the config file described as: -// -// The execution parameters which SHOULD be used as a base when running -// a container using the image. -// -// The names of the fields in this message are chosen to reflect the JSON -// payload of the Config as defined here: -// https://git.io/vrAET -// and -// https://github.com/opencontainers/image-spec/blob/master/config.md -type Config struct { - AttachStderr bool `json:"AttachStderr,omitempty"` - AttachStdin bool `json:"AttachStdin,omitempty"` - AttachStdout bool `json:"AttachStdout,omitempty"` - Cmd []string `json:"Cmd,omitempty"` - Healthcheck *HealthConfig `json:"Healthcheck,omitempty"` - Domainname string `json:"Domainname,omitempty"` - Entrypoint []string `json:"Entrypoint,omitempty"` - Env []string `json:"Env,omitempty"` - Hostname string `json:"Hostname,omitempty"` - Image string `json:"Image,omitempty"` - Labels map[string]string `json:"Labels,omitempty"` - OnBuild []string `json:"OnBuild,omitempty"` - OpenStdin bool `json:"OpenStdin,omitempty"` - StdinOnce bool `json:"StdinOnce,omitempty"` - Tty bool `json:"Tty,omitempty"` - User string `json:"User,omitempty"` - Volumes map[string]struct{} `json:"Volumes,omitempty"` - WorkingDir string `json:"WorkingDir,omitempty"` - ExposedPorts map[string]struct{} `json:"ExposedPorts,omitempty"` - ArgsEscaped bool `json:"ArgsEscaped,omitempty"` - NetworkDisabled bool `json:"NetworkDisabled,omitempty"` - MacAddress string `json:"MacAddress,omitempty"` - StopSignal string `json:"StopSignal,omitempty"` - Shell []string `json:"Shell,omitempty"` -} - -// ParseConfigFile parses the io.Reader's contents into a ConfigFile. -func ParseConfigFile(r io.Reader) (*ConfigFile, error) { - cf := ConfigFile{} - if err := json.NewDecoder(r).Decode(&cf); err != nil { - return nil, err - } - return &cf, nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/doc.go b/vendor/github.com/google/go-containerregistry/pkg/v1/doc.go deleted file mode 100644 index 7a84736be..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2018 Google LLC 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. - -// +k8s:deepcopy-gen=package - -// Package v1 defines structured types for OCI v1 images -package v1 diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/empty/README.md b/vendor/github.com/google/go-containerregistry/pkg/v1/empty/README.md deleted file mode 100644 index 8663a830f..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/empty/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# `empty` - -[![GoDoc](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/empty?status.svg)](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/empty) - -The empty packages provides an empty base for constructing a `v1.Image` or `v1.ImageIndex`. -This is especially useful when paired with the [`mutate`](/pkg/v1/mutate) package, -see [`mutate.Append`](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/mutate#Append) -and [`mutate.AppendManifests`](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/mutate#AppendManifests). diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/empty/doc.go b/vendor/github.com/google/go-containerregistry/pkg/v1/empty/doc.go deleted file mode 100644 index 1a521e9a7..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/empty/doc.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2018 Google LLC 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 empty provides an implementation of v1.Image equivalent to "FROM scratch". -package empty diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/empty/image.go b/vendor/github.com/google/go-containerregistry/pkg/v1/empty/image.go deleted file mode 100644 index c58a06ce0..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/empty/image.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2018 Google LLC 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 empty - -import ( - "fmt" - - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/partial" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -// Image is a singleton empty image, think: FROM scratch. -var Image, _ = partial.UncompressedToImage(emptyImage{}) - -type emptyImage struct{} - -// MediaType implements partial.UncompressedImageCore. -func (i emptyImage) MediaType() (types.MediaType, error) { - return types.DockerManifestSchema2, nil -} - -// RawConfigFile implements partial.UncompressedImageCore. -func (i emptyImage) RawConfigFile() ([]byte, error) { - return partial.RawConfigFile(i) -} - -// ConfigFile implements v1.Image. -func (i emptyImage) ConfigFile() (*v1.ConfigFile, error) { - return &v1.ConfigFile{ - RootFS: v1.RootFS{ - // Some clients check this. - Type: "layers", - }, - }, nil -} - -func (i emptyImage) LayerByDiffID(h v1.Hash) (partial.UncompressedLayer, error) { - return nil, fmt.Errorf("LayerByDiffID(%s): empty image", h) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/empty/index.go b/vendor/github.com/google/go-containerregistry/pkg/v1/empty/index.go deleted file mode 100644 index 18b414891..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/empty/index.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2018 Google LLC 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 empty - -import ( - "encoding/json" - "errors" - - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/partial" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -// Index is a singleton empty index, think: FROM scratch. -var Index = emptyIndex{} - -type emptyIndex struct{} - -func (i emptyIndex) MediaType() (types.MediaType, error) { - return types.OCIImageIndex, nil -} - -func (i emptyIndex) Digest() (v1.Hash, error) { - return partial.Digest(i) -} - -func (i emptyIndex) Size() (int64, error) { - return partial.Size(i) -} - -func (i emptyIndex) IndexManifest() (*v1.IndexManifest, error) { - return base(), nil -} - -func (i emptyIndex) RawManifest() ([]byte, error) { - return json.Marshal(base()) -} - -func (i emptyIndex) Image(v1.Hash) (v1.Image, error) { - return nil, errors.New("empty index") -} - -func (i emptyIndex) ImageIndex(v1.Hash) (v1.ImageIndex, error) { - return nil, errors.New("empty index") -} - -func base() *v1.IndexManifest { - return &v1.IndexManifest{ - SchemaVersion: 2, - MediaType: types.OCIImageIndex, - Manifests: []v1.Descriptor{}, - } -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/hash.go b/vendor/github.com/google/go-containerregistry/pkg/v1/hash.go deleted file mode 100644 index f78a5fa89..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/hash.go +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2018 Google LLC 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 v1 - -import ( - "crypto" - "encoding/hex" - "encoding/json" - "fmt" - "hash" - "io" - "strconv" - "strings" -) - -// Hash is an unqualified digest of some content, e.g. sha256:deadbeef -type Hash struct { - // Algorithm holds the algorithm used to compute the hash. - Algorithm string - - // Hex holds the hex portion of the content hash. - Hex string -} - -// String reverses NewHash returning the string-form of the hash. -func (h Hash) String() string { - return fmt.Sprintf("%s:%s", h.Algorithm, h.Hex) -} - -// NewHash validates the input string is a hash and returns a strongly type Hash object. -func NewHash(s string) (Hash, error) { - h := Hash{} - if err := h.parse(s); err != nil { - return Hash{}, err - } - return h, nil -} - -// MarshalJSON implements json.Marshaler -func (h Hash) MarshalJSON() ([]byte, error) { - return json.Marshal(h.String()) -} - -// UnmarshalJSON implements json.Unmarshaler -func (h *Hash) UnmarshalJSON(data []byte) error { - s, err := strconv.Unquote(string(data)) - if err != nil { - return err - } - return h.parse(s) -} - -// MarshalText implements encoding.TextMarshaler. This is required to use -// v1.Hash as a key in a map when marshalling JSON. -func (h Hash) MarshalText() (text []byte, err error) { - return []byte(h.String()), nil -} - -// UnmarshalText implements encoding.TextUnmarshaler. This is required to use -// v1.Hash as a key in a map when unmarshalling JSON. -func (h *Hash) UnmarshalText(text []byte) error { - return h.parse(string(text)) -} - -// Hasher returns a hash.Hash for the named algorithm (e.g. "sha256") -func Hasher(name string) (hash.Hash, error) { - switch name { - case "sha256": - return crypto.SHA256.New(), nil - default: - return nil, fmt.Errorf("unsupported hash: %q", name) - } -} - -func (h *Hash) parse(unquoted string) error { - parts := strings.Split(unquoted, ":") - if len(parts) != 2 { - return fmt.Errorf("cannot parse hash: %q", unquoted) - } - - rest := strings.TrimLeft(parts[1], "0123456789abcdef") - if len(rest) != 0 { - return fmt.Errorf("found non-hex character in hash: %c", rest[0]) - } - - hasher, err := Hasher(parts[0]) - if err != nil { - return err - } - // Compare the hex to the expected size (2 hex characters per byte) - if len(parts[1]) != hasher.Size()*2 { - return fmt.Errorf("wrong number of hex digits for %s: %s", parts[0], parts[1]) - } - - h.Algorithm = parts[0] - h.Hex = parts[1] - return nil -} - -// SHA256 computes the Hash of the provided io.Reader's content. -func SHA256(r io.Reader) (Hash, int64, error) { - hasher := crypto.SHA256.New() - n, err := io.Copy(hasher, r) - if err != nil { - return Hash{}, 0, err - } - return Hash{ - Algorithm: "sha256", - Hex: hex.EncodeToString(hasher.Sum(make([]byte, 0, hasher.Size()))), - }, n, nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/image.go b/vendor/github.com/google/go-containerregistry/pkg/v1/image.go deleted file mode 100644 index 8de9e4764..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/image.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2018 Google LLC 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 v1 - -import ( - "github.com/google/go-containerregistry/pkg/v1/types" -) - -// Image defines the interface for interacting with an OCI v1 image. -type Image interface { - // Layers returns the ordered collection of filesystem layers that comprise this image. - // The order of the list is oldest/base layer first, and most-recent/top layer last. - Layers() ([]Layer, error) - - // MediaType of this image's manifest. - MediaType() (types.MediaType, error) - - // Size returns the size of the manifest. - Size() (int64, error) - - // ConfigName returns the hash of the image's config file, also known as - // the Image ID. - ConfigName() (Hash, error) - - // ConfigFile returns this image's config file. - ConfigFile() (*ConfigFile, error) - - // RawConfigFile returns the serialized bytes of ConfigFile(). - RawConfigFile() ([]byte, error) - - // Digest returns the sha256 of this image's manifest. - Digest() (Hash, error) - - // Manifest returns this image's Manifest object. - Manifest() (*Manifest, error) - - // RawManifest returns the serialized bytes of Manifest() - RawManifest() ([]byte, error) - - // LayerByDigest returns a Layer for interacting with a particular layer of - // the image, looking it up by "digest" (the compressed hash). - LayerByDigest(Hash) (Layer, error) - - // LayerByDiffID is an analog to LayerByDigest, looking up by "diff id" - // (the uncompressed hash). - LayerByDiffID(Hash) (Layer, error) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/index.go b/vendor/github.com/google/go-containerregistry/pkg/v1/index.go deleted file mode 100644 index 8e7bc8ebb..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/index.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2018 Google LLC 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 v1 - -import ( - "github.com/google/go-containerregistry/pkg/v1/types" -) - -// ImageIndex defines the interface for interacting with an OCI image index. -type ImageIndex interface { - // MediaType of this image's manifest. - MediaType() (types.MediaType, error) - - // Digest returns the sha256 of this index's manifest. - Digest() (Hash, error) - - // Size returns the size of the manifest. - Size() (int64, error) - - // IndexManifest returns this image index's manifest object. - IndexManifest() (*IndexManifest, error) - - // RawManifest returns the serialized bytes of IndexManifest(). - RawManifest() ([]byte, error) - - // Image returns a v1.Image that this ImageIndex references. - Image(Hash) (Image, error) - - // ImageIndex returns a v1.ImageIndex that this ImageIndex references. - ImageIndex(Hash) (ImageIndex, error) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/layer.go b/vendor/github.com/google/go-containerregistry/pkg/v1/layer.go deleted file mode 100644 index 57447d263..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/layer.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2018 Google LLC 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 v1 - -import ( - "io" - - "github.com/google/go-containerregistry/pkg/v1/types" -) - -// Layer is an interface for accessing the properties of a particular layer of a v1.Image -type Layer interface { - // Digest returns the Hash of the compressed layer. - Digest() (Hash, error) - - // DiffID returns the Hash of the uncompressed layer. - DiffID() (Hash, error) - - // Compressed returns an io.ReadCloser for the compressed layer contents. - Compressed() (io.ReadCloser, error) - - // Uncompressed returns an io.ReadCloser for the uncompressed layer contents. - Uncompressed() (io.ReadCloser, error) - - // Size returns the compressed size of the Layer. - Size() (int64, error) - - // MediaType returns the media type of the Layer. - MediaType() (types.MediaType, error) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/layout/README.md b/vendor/github.com/google/go-containerregistry/pkg/v1/layout/README.md deleted file mode 100644 index 54bee6d9f..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/layout/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# `layout` - -[![GoDoc](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/layout?status.svg)](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/layout) - -The `layout` package implements support for interacting with an [OCI Image Layout](https://github.com/opencontainers/image-spec/blob/master/image-layout.md). diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/layout/blob.go b/vendor/github.com/google/go-containerregistry/pkg/v1/layout/blob.go deleted file mode 100644 index 2e5f4358d..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/layout/blob.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2018 Google LLC 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 layout - -import ( - "io" - "os" - - v1 "github.com/google/go-containerregistry/pkg/v1" -) - -// Blob returns a blob with the given hash from the Path. -func (l Path) Blob(h v1.Hash) (io.ReadCloser, error) { - return os.Open(l.blobPath(h)) -} - -// Bytes is a convenience function to return a blob from the Path as -// a byte slice. -func (l Path) Bytes(h v1.Hash) ([]byte, error) { - return os.ReadFile(l.blobPath(h)) -} - -func (l Path) blobPath(h v1.Hash) string { - return l.path("blobs", h.Algorithm, h.Hex) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/layout/doc.go b/vendor/github.com/google/go-containerregistry/pkg/v1/layout/doc.go deleted file mode 100644 index d80d27363..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/layout/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2018 Google LLC 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 layout provides facilities for reading/writing artifacts from/to -// an OCI image layout on disk, see: -// -// https://github.com/opencontainers/image-spec/blob/master/image-layout.md -package layout diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/layout/gc.go b/vendor/github.com/google/go-containerregistry/pkg/v1/layout/gc.go deleted file mode 100644 index 5fdb2c05d..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/layout/gc.go +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2018 Google LLC 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. - -// This is an EXPERIMENTAL package, and may change in arbitrary ways without notice. -package layout - -import ( - "fmt" - "io/fs" - "path/filepath" - "strings" - - v1 "github.com/google/go-containerregistry/pkg/v1" -) - -// GarbageCollect removes unreferenced blobs from the oci-layout -// -// This is an experimental api, and not subject to any stability guarantees -// We may abandon it at any time, without prior notice. -// Deprecated: Use it at your own risk! -func (l Path) GarbageCollect() ([]v1.Hash, error) { - idx, err := l.ImageIndex() - if err != nil { - return nil, err - } - blobsToKeep := map[string]bool{} - if err := l.garbageCollectImageIndex(idx, blobsToKeep); err != nil { - return nil, err - } - blobsDir := l.path("blobs") - removedBlobs := []v1.Hash{} - - err = filepath.WalkDir(blobsDir, func(path string, d fs.DirEntry, err error) error { - if err != nil { - return err - } - - if d.IsDir() { - return nil - } - - rel, err := filepath.Rel(blobsDir, path) - if err != nil { - return err - } - hashString := strings.Replace(rel, "/", ":", 1) - if present := blobsToKeep[hashString]; !present { - h, err := v1.NewHash(hashString) - if err != nil { - return err - } - removedBlobs = append(removedBlobs, h) - } - return nil - }) - - if err != nil { - return nil, err - } - - return removedBlobs, nil -} - -func (l Path) garbageCollectImageIndex(index v1.ImageIndex, blobsToKeep map[string]bool) error { - idxm, err := index.IndexManifest() - if err != nil { - return err - } - - h, err := index.Digest() - if err != nil { - return err - } - - blobsToKeep[h.String()] = true - - for _, descriptor := range idxm.Manifests { - if descriptor.MediaType.IsImage() { - img, err := index.Image(descriptor.Digest) - if err != nil { - return err - } - if err := l.garbageCollectImage(img, blobsToKeep); err != nil { - return err - } - } else if descriptor.MediaType.IsIndex() { - idx, err := index.ImageIndex(descriptor.Digest) - if err != nil { - return err - } - if err := l.garbageCollectImageIndex(idx, blobsToKeep); err != nil { - return err - } - } else { - return fmt.Errorf("gc: unknown media type: %s", descriptor.MediaType) - } - } - return nil -} - -func (l Path) garbageCollectImage(image v1.Image, blobsToKeep map[string]bool) error { - h, err := image.Digest() - if err != nil { - return err - } - blobsToKeep[h.String()] = true - - h, err = image.ConfigName() - if err != nil { - return err - } - blobsToKeep[h.String()] = true - - ls, err := image.Layers() - if err != nil { - return err - } - for _, l := range ls { - h, err := l.Digest() - if err != nil { - return err - } - blobsToKeep[h.String()] = true - } - return nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/layout/image.go b/vendor/github.com/google/go-containerregistry/pkg/v1/layout/image.go deleted file mode 100644 index c9ae9665c..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/layout/image.go +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright 2018 Google LLC 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 layout - -import ( - "fmt" - "io" - "os" - "sync" - - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/partial" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -type layoutImage struct { - path Path - desc v1.Descriptor - manifestLock sync.Mutex // Protects rawManifest - rawManifest []byte -} - -var _ partial.CompressedImageCore = (*layoutImage)(nil) - -// Image reads a v1.Image with digest h from the Path. -func (l Path) Image(h v1.Hash) (v1.Image, error) { - ii, err := l.ImageIndex() - if err != nil { - return nil, err - } - - return ii.Image(h) -} - -func (li *layoutImage) MediaType() (types.MediaType, error) { - return li.desc.MediaType, nil -} - -// Implements WithManifest for partial.Blobset. -func (li *layoutImage) Manifest() (*v1.Manifest, error) { - return partial.Manifest(li) -} - -func (li *layoutImage) RawManifest() ([]byte, error) { - li.manifestLock.Lock() - defer li.manifestLock.Unlock() - if li.rawManifest != nil { - return li.rawManifest, nil - } - - b, err := li.path.Bytes(li.desc.Digest) - if err != nil { - return nil, err - } - - li.rawManifest = b - return li.rawManifest, nil -} - -func (li *layoutImage) RawConfigFile() ([]byte, error) { - manifest, err := li.Manifest() - if err != nil { - return nil, err - } - - return li.path.Bytes(manifest.Config.Digest) -} - -func (li *layoutImage) LayerByDigest(h v1.Hash) (partial.CompressedLayer, error) { - manifest, err := li.Manifest() - if err != nil { - return nil, err - } - - if h == manifest.Config.Digest { - return &compressedBlob{ - path: li.path, - desc: manifest.Config, - }, nil - } - - for _, desc := range manifest.Layers { - if h == desc.Digest { - return &compressedBlob{ - path: li.path, - desc: desc, - }, nil - } - } - - return nil, fmt.Errorf("could not find layer in image: %s", h) -} - -type compressedBlob struct { - path Path - desc v1.Descriptor -} - -func (b *compressedBlob) Digest() (v1.Hash, error) { - return b.desc.Digest, nil -} - -func (b *compressedBlob) Compressed() (io.ReadCloser, error) { - return b.path.Blob(b.desc.Digest) -} - -func (b *compressedBlob) Size() (int64, error) { - return b.desc.Size, nil -} - -func (b *compressedBlob) MediaType() (types.MediaType, error) { - return b.desc.MediaType, nil -} - -// Descriptor implements partial.withDescriptor. -func (b *compressedBlob) Descriptor() (*v1.Descriptor, error) { - return &b.desc, nil -} - -// See partial.Exists. -func (b *compressedBlob) Exists() (bool, error) { - _, err := os.Stat(b.path.blobPath(b.desc.Digest)) - if os.IsNotExist(err) { - return false, nil - } - return err == nil, err -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/layout/index.go b/vendor/github.com/google/go-containerregistry/pkg/v1/layout/index.go deleted file mode 100644 index 7404f186b..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/layout/index.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2018 Google LLC 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 layout - -import ( - "encoding/json" - "errors" - "fmt" - "io" - "os" - - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/partial" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -var _ v1.ImageIndex = (*layoutIndex)(nil) - -type layoutIndex struct { - mediaType types.MediaType - path Path - rawIndex []byte -} - -// ImageIndexFromPath is a convenience function which constructs a Path and returns its v1.ImageIndex. -func ImageIndexFromPath(path string) (v1.ImageIndex, error) { - lp, err := FromPath(path) - if err != nil { - return nil, err - } - return lp.ImageIndex() -} - -// ImageIndex returns a v1.ImageIndex for the Path. -func (l Path) ImageIndex() (v1.ImageIndex, error) { - rawIndex, err := os.ReadFile(l.path("index.json")) - if err != nil { - return nil, err - } - - idx := &layoutIndex{ - mediaType: types.OCIImageIndex, - path: l, - rawIndex: rawIndex, - } - - return idx, nil -} - -func (i *layoutIndex) MediaType() (types.MediaType, error) { - return i.mediaType, nil -} - -func (i *layoutIndex) Digest() (v1.Hash, error) { - return partial.Digest(i) -} - -func (i *layoutIndex) Size() (int64, error) { - return partial.Size(i) -} - -func (i *layoutIndex) IndexManifest() (*v1.IndexManifest, error) { - var index v1.IndexManifest - err := json.Unmarshal(i.rawIndex, &index) - return &index, err -} - -func (i *layoutIndex) RawManifest() ([]byte, error) { - return i.rawIndex, nil -} - -func (i *layoutIndex) Image(h v1.Hash) (v1.Image, error) { - // Look up the digest in our manifest first to return a better error. - desc, err := i.findDescriptor(h) - if err != nil { - return nil, err - } - - if !isExpectedMediaType(desc.MediaType, types.OCIManifestSchema1, types.DockerManifestSchema2) { - return nil, fmt.Errorf("unexpected media type for %v: %s", h, desc.MediaType) - } - - img := &layoutImage{ - path: i.path, - desc: *desc, - } - return partial.CompressedToImage(img) -} - -func (i *layoutIndex) ImageIndex(h v1.Hash) (v1.ImageIndex, error) { - // Look up the digest in our manifest first to return a better error. - desc, err := i.findDescriptor(h) - if err != nil { - return nil, err - } - - if !isExpectedMediaType(desc.MediaType, types.OCIImageIndex, types.DockerManifestList) { - return nil, fmt.Errorf("unexpected media type for %v: %s", h, desc.MediaType) - } - - rawIndex, err := i.path.Bytes(h) - if err != nil { - return nil, err - } - - return &layoutIndex{ - mediaType: desc.MediaType, - path: i.path, - rawIndex: rawIndex, - }, nil -} - -func (i *layoutIndex) Blob(h v1.Hash) (io.ReadCloser, error) { - return i.path.Blob(h) -} - -func (i *layoutIndex) findDescriptor(h v1.Hash) (*v1.Descriptor, error) { - im, err := i.IndexManifest() - if err != nil { - return nil, err - } - - if h == (v1.Hash{}) { - if len(im.Manifests) != 1 { - return nil, errors.New("oci layout must contain only a single image to be used with layout.Image") - } - return &(im.Manifests)[0], nil - } - - for _, desc := range im.Manifests { - if desc.Digest == h { - return &desc, nil - } - } - - return nil, fmt.Errorf("could not find descriptor in index: %s", h) -} - -// TODO: Pull this out into methods on types.MediaType? e.g. instead, have: -// * mt.IsIndex() -// * mt.IsImage() -func isExpectedMediaType(mt types.MediaType, expected ...types.MediaType) bool { - for _, allowed := range expected { - if mt == allowed { - return true - } - } - return false -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/layout/layoutpath.go b/vendor/github.com/google/go-containerregistry/pkg/v1/layout/layoutpath.go deleted file mode 100644 index a031ff5ae..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/layout/layoutpath.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2019 The original author or 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 layout - -import "path/filepath" - -// Path represents an OCI image layout rooted in a file system path -type Path string - -func (l Path) path(elem ...string) string { - complete := []string{string(l)} - return filepath.Join(append(complete, elem...)...) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/layout/options.go b/vendor/github.com/google/go-containerregistry/pkg/v1/layout/options.go deleted file mode 100644 index a26f9f371..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/layout/options.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2019 Google LLC 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 layout - -import v1 "github.com/google/go-containerregistry/pkg/v1" - -// Option is a functional option for Layout. -type Option func(*options) - -type options struct { - descOpts []descriptorOption -} - -func makeOptions(opts ...Option) *options { - o := &options{ - descOpts: []descriptorOption{}, - } - for _, apply := range opts { - apply(o) - } - return o -} - -type descriptorOption func(*v1.Descriptor) - -// WithAnnotations adds annotations to the artifact descriptor. -func WithAnnotations(annotations map[string]string) Option { - return func(o *options) { - o.descOpts = append(o.descOpts, func(desc *v1.Descriptor) { - if desc.Annotations == nil { - desc.Annotations = make(map[string]string) - } - for k, v := range annotations { - desc.Annotations[k] = v - } - }) - } -} - -// WithURLs adds urls to the artifact descriptor. -func WithURLs(urls []string) Option { - return func(o *options) { - o.descOpts = append(o.descOpts, func(desc *v1.Descriptor) { - if desc.URLs == nil { - desc.URLs = []string{} - } - desc.URLs = append(desc.URLs, urls...) - }) - } -} - -// WithPlatform sets the platform of the artifact descriptor. -func WithPlatform(platform v1.Platform) Option { - return func(o *options) { - o.descOpts = append(o.descOpts, func(desc *v1.Descriptor) { - desc.Platform = &platform - }) - } -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/layout/read.go b/vendor/github.com/google/go-containerregistry/pkg/v1/layout/read.go deleted file mode 100644 index 796abc7dd..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/layout/read.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2019 The original author or 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 layout - -import ( - "os" - "path/filepath" -) - -// FromPath reads an OCI image layout at path and constructs a layout.Path. -func FromPath(path string) (Path, error) { - // TODO: check oci-layout exists - - _, err := os.Stat(filepath.Join(path, "index.json")) - if err != nil { - return "", err - } - - return Path(path), nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/layout/write.go b/vendor/github.com/google/go-containerregistry/pkg/v1/layout/write.go deleted file mode 100644 index d6e35c391..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/layout/write.go +++ /dev/null @@ -1,482 +0,0 @@ -// Copyright 2018 Google LLC 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 layout - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "os" - "path/filepath" - - "github.com/google/go-containerregistry/pkg/logs" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/match" - "github.com/google/go-containerregistry/pkg/v1/mutate" - "github.com/google/go-containerregistry/pkg/v1/partial" - "github.com/google/go-containerregistry/pkg/v1/stream" - "github.com/google/go-containerregistry/pkg/v1/types" - "golang.org/x/sync/errgroup" -) - -var layoutFile = `{ - "imageLayoutVersion": "1.0.0" -}` - -// AppendImage writes a v1.Image to the Path and updates -// the index.json to reference it. -func (l Path) AppendImage(img v1.Image, options ...Option) error { - if err := l.WriteImage(img); err != nil { - return err - } - - desc, err := partial.Descriptor(img) - if err != nil { - return err - } - - o := makeOptions(options...) - for _, opt := range o.descOpts { - opt(desc) - } - - return l.AppendDescriptor(*desc) -} - -// AppendIndex writes a v1.ImageIndex to the Path and updates -// the index.json to reference it. -func (l Path) AppendIndex(ii v1.ImageIndex, options ...Option) error { - if err := l.WriteIndex(ii); err != nil { - return err - } - - desc, err := partial.Descriptor(ii) - if err != nil { - return err - } - - o := makeOptions(options...) - for _, opt := range o.descOpts { - opt(desc) - } - - return l.AppendDescriptor(*desc) -} - -// AppendDescriptor adds a descriptor to the index.json of the Path. -func (l Path) AppendDescriptor(desc v1.Descriptor) error { - ii, err := l.ImageIndex() - if err != nil { - return err - } - - index, err := ii.IndexManifest() - if err != nil { - return err - } - - index.Manifests = append(index.Manifests, desc) - - rawIndex, err := json.MarshalIndent(index, "", " ") - if err != nil { - return err - } - - return l.WriteFile("index.json", rawIndex, os.ModePerm) -} - -// ReplaceImage writes a v1.Image to the Path and updates -// the index.json to reference it, replacing any existing one that matches matcher, if found. -func (l Path) ReplaceImage(img v1.Image, matcher match.Matcher, options ...Option) error { - if err := l.WriteImage(img); err != nil { - return err - } - - return l.replaceDescriptor(img, matcher, options...) -} - -// ReplaceIndex writes a v1.ImageIndex to the Path and updates -// the index.json to reference it, replacing any existing one that matches matcher, if found. -func (l Path) ReplaceIndex(ii v1.ImageIndex, matcher match.Matcher, options ...Option) error { - if err := l.WriteIndex(ii); err != nil { - return err - } - - return l.replaceDescriptor(ii, matcher, options...) -} - -// replaceDescriptor adds a descriptor to the index.json of the Path, replacing -// any one matching matcher, if found. -func (l Path) replaceDescriptor(append mutate.Appendable, matcher match.Matcher, options ...Option) error { - ii, err := l.ImageIndex() - if err != nil { - return err - } - - desc, err := partial.Descriptor(append) - if err != nil { - return err - } - - o := makeOptions(options...) - for _, opt := range o.descOpts { - opt(desc) - } - - add := mutate.IndexAddendum{ - Add: append, - Descriptor: *desc, - } - ii = mutate.AppendManifests(mutate.RemoveManifests(ii, matcher), add) - - index, err := ii.IndexManifest() - if err != nil { - return err - } - - rawIndex, err := json.MarshalIndent(index, "", " ") - if err != nil { - return err - } - - return l.WriteFile("index.json", rawIndex, os.ModePerm) -} - -// RemoveDescriptors removes any descriptors that match the match.Matcher from the index.json of the Path. -func (l Path) RemoveDescriptors(matcher match.Matcher) error { - ii, err := l.ImageIndex() - if err != nil { - return err - } - ii = mutate.RemoveManifests(ii, matcher) - - index, err := ii.IndexManifest() - if err != nil { - return err - } - - rawIndex, err := json.MarshalIndent(index, "", " ") - if err != nil { - return err - } - - return l.WriteFile("index.json", rawIndex, os.ModePerm) -} - -// WriteFile write a file with arbitrary data at an arbitrary location in a v1 -// layout. Used mostly internally to write files like "oci-layout" and -// "index.json", also can be used to write other arbitrary files. Do *not* use -// this to write blobs. Use only WriteBlob() for that. -func (l Path) WriteFile(name string, data []byte, perm os.FileMode) error { - if err := os.MkdirAll(l.path(), os.ModePerm); err != nil && !os.IsExist(err) { - return err - } - - return os.WriteFile(l.path(name), data, perm) -} - -// WriteBlob copies a file to the blobs/ directory in the Path from the given ReadCloser at -// blobs/{hash.Algorithm}/{hash.Hex}. -func (l Path) WriteBlob(hash v1.Hash, r io.ReadCloser) error { - return l.writeBlob(hash, -1, r, nil) -} - -func (l Path) writeBlob(hash v1.Hash, size int64, rc io.ReadCloser, renamer func() (v1.Hash, error)) error { - defer rc.Close() - if hash.Hex == "" && renamer == nil { - panic("writeBlob called an invalid hash and no renamer") - } - - dir := l.path("blobs", hash.Algorithm) - if err := os.MkdirAll(dir, os.ModePerm); err != nil && !os.IsExist(err) { - return err - } - - // Check if blob already exists and is the correct size - file := filepath.Join(dir, hash.Hex) - if s, err := os.Stat(file); err == nil && !s.IsDir() && (s.Size() == size || size == -1) { - return nil - } - - // If a renamer func was provided write to a temporary file - open := func() (*os.File, error) { return os.Create(file) } - if renamer != nil { - open = func() (*os.File, error) { return os.CreateTemp(dir, hash.Hex) } - } - w, err := open() - if err != nil { - return err - } - if renamer != nil { - // Delete temp file if an error is encountered before renaming - defer func() { - if err := os.Remove(w.Name()); err != nil && !errors.Is(err, os.ErrNotExist) { - logs.Warn.Printf("error removing temporary file after encountering an error while writing blob: %v", err) - } - }() - } - defer w.Close() - - // Write to file and exit if not renaming - if n, err := io.Copy(w, rc); err != nil || renamer == nil { - return err - } else if size != -1 && n != size { - return fmt.Errorf("expected blob size %d, but only wrote %d", size, n) - } - - // Always close reader before renaming, since Close computes the digest in - // the case of streaming layers. If Close is not called explicitly, it will - // occur in a goroutine that is not guaranteed to succeed before renamer is - // called. When renamer is the layer's Digest method, it can return - // ErrNotComputed. - if err := rc.Close(); err != nil { - return err - } - - // Always close file before renaming - if err := w.Close(); err != nil { - return err - } - - // Rename file based on the final hash - finalHash, err := renamer() - if err != nil { - return fmt.Errorf("error getting final digest of layer: %w", err) - } - - renamePath := l.path("blobs", finalHash.Algorithm, finalHash.Hex) - return os.Rename(w.Name(), renamePath) -} - -// writeLayer writes the compressed layer to a blob. Unlike WriteBlob it will -// write to a temporary file (suffixed with .tmp) within the layout until the -// compressed reader is fully consumed and written to disk. Also unlike -// WriteBlob, it will not skip writing and exit without error when a blob file -// exists, but does not have the correct size. (The blob hash is not -// considered, because it may be expensive to compute.) -func (l Path) writeLayer(layer v1.Layer) error { - d, err := layer.Digest() - if errors.Is(err, stream.ErrNotComputed) { - // Allow digest errors, since streams may not have calculated the hash - // yet. Instead, use an empty value, which will be transformed into a - // random file name with `os.CreateTemp` and the final digest will be - // calculated after writing to a temp file and before renaming to the - // final path. - d = v1.Hash{Algorithm: "sha256", Hex: ""} - } else if err != nil { - return err - } - - s, err := layer.Size() - if errors.Is(err, stream.ErrNotComputed) { - // Allow size errors, since streams may not have calculated the size - // yet. Instead, use zero as a sentinel value meaning that no size - // comparison can be done and any sized blob file should be considered - // valid and not overwritten. - // - // TODO: Provide an option to always overwrite blobs. - s = -1 - } else if err != nil { - return err - } - - r, err := layer.Compressed() - if err != nil { - return err - } - - if err := l.writeBlob(d, s, r, layer.Digest); err != nil { - return fmt.Errorf("error writing layer: %w", err) - } - return nil -} - -// RemoveBlob removes a file from the blobs directory in the Path -// at blobs/{hash.Algorithm}/{hash.Hex} -// It does *not* remove any reference to it from other manifests or indexes, or -// from the root index.json. -func (l Path) RemoveBlob(hash v1.Hash) error { - dir := l.path("blobs", hash.Algorithm) - err := os.Remove(filepath.Join(dir, hash.Hex)) - if err != nil && !os.IsNotExist(err) { - return err - } - return nil -} - -// WriteImage writes an image, including its manifest, config and all of its -// layers, to the blobs directory. If any blob already exists, as determined by -// the hash filename, does not write it. -// This function does *not* update the `index.json` file. If you want to write the -// image and also update the `index.json`, call AppendImage(), which wraps this -// and also updates the `index.json`. -func (l Path) WriteImage(img v1.Image) error { - layers, err := img.Layers() - if err != nil { - return err - } - - // Write the layers concurrently. - var g errgroup.Group - for _, layer := range layers { - layer := layer - g.Go(func() error { - return l.writeLayer(layer) - }) - } - if err := g.Wait(); err != nil { - return err - } - - // Write the config. - cfgName, err := img.ConfigName() - if err != nil { - return err - } - cfgBlob, err := img.RawConfigFile() - if err != nil { - return err - } - if err := l.WriteBlob(cfgName, io.NopCloser(bytes.NewReader(cfgBlob))); err != nil { - return err - } - - // Write the img manifest. - d, err := img.Digest() - if err != nil { - return err - } - manifest, err := img.RawManifest() - if err != nil { - return err - } - - return l.WriteBlob(d, io.NopCloser(bytes.NewReader(manifest))) -} - -type withLayer interface { - Layer(v1.Hash) (v1.Layer, error) -} - -type withBlob interface { - Blob(v1.Hash) (io.ReadCloser, error) -} - -func (l Path) writeIndexToFile(indexFile string, ii v1.ImageIndex) error { - index, err := ii.IndexManifest() - if err != nil { - return err - } - - // Walk the descriptors and write any v1.Image or v1.ImageIndex that we find. - // If we come across something we don't expect, just write it as a blob. - for _, desc := range index.Manifests { - switch desc.MediaType { - case types.OCIImageIndex, types.DockerManifestList: - ii, err := ii.ImageIndex(desc.Digest) - if err != nil { - return err - } - if err := l.WriteIndex(ii); err != nil { - return err - } - case types.OCIManifestSchema1, types.DockerManifestSchema2: - img, err := ii.Image(desc.Digest) - if err != nil { - return err - } - if err := l.WriteImage(img); err != nil { - return err - } - default: - // TODO: The layout could reference arbitrary things, which we should - // probably just pass through. - - var blob io.ReadCloser - // Workaround for #819. - if wl, ok := ii.(withLayer); ok { - layer, lerr := wl.Layer(desc.Digest) - if lerr != nil { - return lerr - } - blob, err = layer.Compressed() - } else if wb, ok := ii.(withBlob); ok { - blob, err = wb.Blob(desc.Digest) - } - if err != nil { - return err - } - if err := l.WriteBlob(desc.Digest, blob); err != nil { - return err - } - } - } - - rawIndex, err := ii.RawManifest() - if err != nil { - return err - } - - return l.WriteFile(indexFile, rawIndex, os.ModePerm) -} - -// WriteIndex writes an index to the blobs directory. Walks down the children, -// including its children manifests and/or indexes, and down the tree until all of -// config and all layers, have been written. If any blob already exists, as determined by -// the hash filename, does not write it. -// This function does *not* update the `index.json` file. If you want to write the -// index and also update the `index.json`, call AppendIndex(), which wraps this -// and also updates the `index.json`. -func (l Path) WriteIndex(ii v1.ImageIndex) error { - // Always just write oci-layout file, since it's small. - if err := l.WriteFile("oci-layout", []byte(layoutFile), os.ModePerm); err != nil { - return err - } - - h, err := ii.Digest() - if err != nil { - return err - } - - indexFile := filepath.Join("blobs", h.Algorithm, h.Hex) - return l.writeIndexToFile(indexFile, ii) -} - -// Write constructs a Path at path from an ImageIndex. -// -// The contents are written in the following format: -// At the top level, there is: -// -// One oci-layout file containing the version of this image-layout. -// One index.json file listing descriptors for the contained images. -// -// Under blobs/, there is, for each image: -// -// One file for each layer, named after the layer's SHA. -// One file for each config blob, named after its SHA. -// One file for each manifest blob, named after its SHA. -func Write(path string, ii v1.ImageIndex) (Path, error) { - lp := Path(path) - // Always just write oci-layout file, since it's small. - if err := lp.WriteFile("oci-layout", []byte(layoutFile), os.ModePerm); err != nil { - return "", err - } - - // TODO create blobs/ in case there is a blobs file which would prevent the directory from being created - - return lp, lp.writeIndexToFile("index.json", ii) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/manifest.go b/vendor/github.com/google/go-containerregistry/pkg/v1/manifest.go deleted file mode 100644 index 22d483f3b..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/manifest.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2018 Google LLC 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 v1 - -import ( - "encoding/json" - "io" - - "github.com/google/go-containerregistry/pkg/v1/types" -) - -// Manifest represents the OCI image manifest in a structured way. -type Manifest struct { - SchemaVersion int64 `json:"schemaVersion"` - MediaType types.MediaType `json:"mediaType,omitempty"` - Config Descriptor `json:"config"` - Layers []Descriptor `json:"layers"` - Annotations map[string]string `json:"annotations,omitempty"` - Subject *Descriptor `json:"subject,omitempty"` -} - -// IndexManifest represents an OCI image index in a structured way. -type IndexManifest struct { - SchemaVersion int64 `json:"schemaVersion"` - MediaType types.MediaType `json:"mediaType,omitempty"` - Manifests []Descriptor `json:"manifests"` - Annotations map[string]string `json:"annotations,omitempty"` - Subject *Descriptor `json:"subject,omitempty"` -} - -// Descriptor holds a reference from the manifest to one of its constituent elements. -type Descriptor struct { - MediaType types.MediaType `json:"mediaType"` - Size int64 `json:"size"` - Digest Hash `json:"digest"` - Data []byte `json:"data,omitempty"` - URLs []string `json:"urls,omitempty"` - Annotations map[string]string `json:"annotations,omitempty"` - Platform *Platform `json:"platform,omitempty"` - ArtifactType string `json:"artifactType,omitempty"` -} - -// ParseManifest parses the io.Reader's contents into a Manifest. -func ParseManifest(r io.Reader) (*Manifest, error) { - m := Manifest{} - if err := json.NewDecoder(r).Decode(&m); err != nil { - return nil, err - } - return &m, nil -} - -// ParseIndexManifest parses the io.Reader's contents into an IndexManifest. -func ParseIndexManifest(r io.Reader) (*IndexManifest, error) { - im := IndexManifest{} - if err := json.NewDecoder(r).Decode(&im); err != nil { - return nil, err - } - return &im, nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/match/match.go b/vendor/github.com/google/go-containerregistry/pkg/v1/match/match.go deleted file mode 100644 index 98b1ff909..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/match/match.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2020 Google LLC 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 match provides functionality for conveniently matching a v1.Descriptor. -package match - -import ( - v1 "github.com/google/go-containerregistry/pkg/v1" - imagespec "github.com/opencontainers/image-spec/specs-go/v1" -) - -// Matcher function that is given a v1.Descriptor, and returns whether or -// not it matches a given rule. Can match on anything it wants in the Descriptor. -type Matcher func(desc v1.Descriptor) bool - -// Name returns a match.Matcher that matches based on the value of the -// -// "org.opencontainers.image.ref.name" annotation: -// -// github.com/opencontainers/image-spec/blob/v1.0.1/annotations.md#pre-defined-annotation-keys -func Name(name string) Matcher { - return Annotation(imagespec.AnnotationRefName, name) -} - -// Annotation returns a match.Matcher that matches based on the provided annotation. -func Annotation(key, value string) Matcher { - return func(desc v1.Descriptor) bool { - if desc.Annotations == nil { - return false - } - if aValue, ok := desc.Annotations[key]; ok && aValue == value { - return true - } - return false - } -} - -// Platforms returns a match.Matcher that matches on any one of the provided platforms. -// Ignores any descriptors that do not have a platform. -func Platforms(platforms ...v1.Platform) Matcher { - return func(desc v1.Descriptor) bool { - if desc.Platform == nil { - return false - } - for _, platform := range platforms { - if desc.Platform.Equals(platform) { - return true - } - } - return false - } -} - -// MediaTypes returns a match.Matcher that matches at least one of the provided media types. -func MediaTypes(mediaTypes ...string) Matcher { - mts := map[string]bool{} - for _, media := range mediaTypes { - mts[media] = true - } - return func(desc v1.Descriptor) bool { - if desc.MediaType == "" { - return false - } - if _, ok := mts[string(desc.MediaType)]; ok { - return true - } - return false - } -} - -// Digests returns a match.Matcher that matches at least one of the provided Digests -func Digests(digests ...v1.Hash) Matcher { - digs := map[v1.Hash]bool{} - for _, digest := range digests { - digs[digest] = true - } - return func(desc v1.Descriptor) bool { - _, ok := digs[desc.Digest] - return ok - } -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/README.md b/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/README.md deleted file mode 100644 index 19e161243..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/README.md +++ /dev/null @@ -1,56 +0,0 @@ -# `mutate` - -[![GoDoc](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/mutate?status.svg)](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/mutate) - -The `v1.Image`, `v1.ImageIndex`, and `v1.Layer` interfaces provide only -accessor methods, so they are essentially immutable. If you want to change -something about them, you need to produce a new instance of that interface. - -A common use case for this library is to read an image from somewhere (a source), -change something about it, and write the image somewhere else (a sink). - -Graphically, this looks something like: - -

- -

- -## Mutations - -This is obviously not a comprehensive set of useful transformations (PRs welcome!), -but a rough summary of what the `mutate` package currently does: - -### `Config` and `ConfigFile` - -These allow you to change the [image configuration](https://github.com/opencontainers/image-spec/blob/master/config.md#properties), -e.g. to change the entrypoint, environment, author, etc. - -### `Time`, `Canonical`, and `CreatedAt` - -These are useful in the context of [reproducible builds](https://reproducible-builds.org/), -where you may want to strip timestamps and other non-reproducible information. - -### `Append`, `AppendLayers`, and `AppendManifests` - -These functions allow the extension of a `v1.Image` or `v1.ImageIndex` with -new layers or manifests. - -For constructing an image `FROM scratch`, see the [`empty`](/pkg/v1/empty) package. - -### `MediaType` and `IndexMediaType` - -Sometimes, it is necessary to change the media type of an image or index, -e.g. to appease a registry with strict validation of images (_looking at you, GCR_). - -### `Rebase` - -Rebase has [its own README](/cmd/crane/rebase.md). - -This is the underlying implementation of [`crane rebase`](https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_rebase.md). - -### `Extract` - -Extract will flatten an image filesystem into a single tar stream, -respecting whiteout files. - -This is the underlying implementation of [`crane export`](https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane_export.md). diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/doc.go b/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/doc.go deleted file mode 100644 index dfbd9951e..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/doc.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2018 Google LLC 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 mutate provides facilities for mutating v1.Images of any kind. -package mutate diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/image.go b/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/image.go deleted file mode 100644 index 3ea27fe47..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/image.go +++ /dev/null @@ -1,293 +0,0 @@ -// Copyright 2019 Google LLC 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 mutate - -import ( - "bytes" - "encoding/json" - "errors" - "sync" - - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/partial" - "github.com/google/go-containerregistry/pkg/v1/stream" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -type image struct { - base v1.Image - adds []Addendum - - computed bool - configFile *v1.ConfigFile - manifest *v1.Manifest - annotations map[string]string - mediaType *types.MediaType - configMediaType *types.MediaType - diffIDMap map[v1.Hash]v1.Layer - digestMap map[v1.Hash]v1.Layer - subject *v1.Descriptor - - sync.Mutex -} - -var _ v1.Image = (*image)(nil) - -func (i *image) MediaType() (types.MediaType, error) { - if i.mediaType != nil { - return *i.mediaType, nil - } - return i.base.MediaType() -} - -func (i *image) compute() error { - i.Lock() - defer i.Unlock() - - // Don't re-compute if already computed. - if i.computed { - return nil - } - var configFile *v1.ConfigFile - if i.configFile != nil { - configFile = i.configFile - } else { - cf, err := i.base.ConfigFile() - if err != nil { - return err - } - configFile = cf.DeepCopy() - } - diffIDs := configFile.RootFS.DiffIDs - history := configFile.History - - diffIDMap := make(map[v1.Hash]v1.Layer) - digestMap := make(map[v1.Hash]v1.Layer) - - for _, add := range i.adds { - history = append(history, add.History) - if add.Layer != nil { - diffID, err := add.Layer.DiffID() - if err != nil { - return err - } - diffIDs = append(diffIDs, diffID) - diffIDMap[diffID] = add.Layer - } - } - - m, err := i.base.Manifest() - if err != nil { - return err - } - manifest := m.DeepCopy() - manifestLayers := manifest.Layers - for _, add := range i.adds { - if add.Layer == nil { - // Empty layers include only history in manifest. - continue - } - - desc, err := partial.Descriptor(add.Layer) - if err != nil { - return err - } - - // Fields in the addendum override the original descriptor. - if len(add.Annotations) != 0 { - desc.Annotations = add.Annotations - } - if len(add.URLs) != 0 { - desc.URLs = add.URLs - } - - if add.MediaType != "" { - desc.MediaType = add.MediaType - } - - manifestLayers = append(manifestLayers, *desc) - digestMap[desc.Digest] = add.Layer - } - - configFile.RootFS.DiffIDs = diffIDs - configFile.History = history - - manifest.Layers = manifestLayers - - rcfg, err := json.Marshal(configFile) - if err != nil { - return err - } - d, sz, err := v1.SHA256(bytes.NewBuffer(rcfg)) - if err != nil { - return err - } - manifest.Config.Digest = d - manifest.Config.Size = sz - - // If Data was set in the base image, we need to update it in the mutated image. - if m.Config.Data != nil { - manifest.Config.Data = rcfg - } - - // If the user wants to mutate the media type of the config - if i.configMediaType != nil { - manifest.Config.MediaType = *i.configMediaType - } - - if i.mediaType != nil { - manifest.MediaType = *i.mediaType - } - - if i.annotations != nil { - if manifest.Annotations == nil { - manifest.Annotations = map[string]string{} - } - - for k, v := range i.annotations { - manifest.Annotations[k] = v - } - } - manifest.Subject = i.subject - - i.configFile = configFile - i.manifest = manifest - i.diffIDMap = diffIDMap - i.digestMap = digestMap - i.computed = true - return nil -} - -// Layers returns the ordered collection of filesystem layers that comprise this image. -// The order of the list is oldest/base layer first, and most-recent/top layer last. -func (i *image) Layers() ([]v1.Layer, error) { - if err := i.compute(); errors.Is(err, stream.ErrNotComputed) { - // Image contains a streamable layer which has not yet been - // consumed. Just return the layers we have in case the caller - // is going to consume the layers. - layers, err := i.base.Layers() - if err != nil { - return nil, err - } - for _, add := range i.adds { - layers = append(layers, add.Layer) - } - return layers, nil - } else if err != nil { - return nil, err - } - - diffIDs, err := partial.DiffIDs(i) - if err != nil { - return nil, err - } - ls := make([]v1.Layer, 0, len(diffIDs)) - for _, h := range diffIDs { - l, err := i.LayerByDiffID(h) - if err != nil { - return nil, err - } - ls = append(ls, l) - } - return ls, nil -} - -// ConfigName returns the hash of the image's config file. -func (i *image) ConfigName() (v1.Hash, error) { - if err := i.compute(); err != nil { - return v1.Hash{}, err - } - return partial.ConfigName(i) -} - -// ConfigFile returns this image's config file. -func (i *image) ConfigFile() (*v1.ConfigFile, error) { - if err := i.compute(); err != nil { - return nil, err - } - return i.configFile.DeepCopy(), nil -} - -// RawConfigFile returns the serialized bytes of ConfigFile() -func (i *image) RawConfigFile() ([]byte, error) { - if err := i.compute(); err != nil { - return nil, err - } - return json.Marshal(i.configFile) -} - -// Digest returns the sha256 of this image's manifest. -func (i *image) Digest() (v1.Hash, error) { - if err := i.compute(); err != nil { - return v1.Hash{}, err - } - return partial.Digest(i) -} - -// Size implements v1.Image. -func (i *image) Size() (int64, error) { - if err := i.compute(); err != nil { - return -1, err - } - return partial.Size(i) -} - -// Manifest returns this image's Manifest object. -func (i *image) Manifest() (*v1.Manifest, error) { - if err := i.compute(); err != nil { - return nil, err - } - return i.manifest.DeepCopy(), nil -} - -// RawManifest returns the serialized bytes of Manifest() -func (i *image) RawManifest() ([]byte, error) { - if err := i.compute(); err != nil { - return nil, err - } - return json.Marshal(i.manifest) -} - -// LayerByDigest returns a Layer for interacting with a particular layer of -// the image, looking it up by "digest" (the compressed hash). -func (i *image) LayerByDigest(h v1.Hash) (v1.Layer, error) { - if cn, err := i.ConfigName(); err != nil { - return nil, err - } else if h == cn { - return partial.ConfigLayer(i) - } - if layer, ok := i.digestMap[h]; ok { - return layer, nil - } - return i.base.LayerByDigest(h) -} - -// LayerByDiffID is an analog to LayerByDigest, looking up by "diff id" -// (the uncompressed hash). -func (i *image) LayerByDiffID(h v1.Hash) (v1.Layer, error) { - if layer, ok := i.diffIDMap[h]; ok { - return layer, nil - } - return i.base.LayerByDiffID(h) -} - -func validate(adds []Addendum) error { - for _, add := range adds { - if add.Layer == nil && !add.History.EmptyLayer { - return errors.New("unable to add a nil layer to the image") - } - } - return nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/index.go b/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/index.go deleted file mode 100644 index 512effef6..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/index.go +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright 2019 Google LLC 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 mutate - -import ( - "encoding/json" - "errors" - "fmt" - "sync" - - "github.com/google/go-containerregistry/pkg/logs" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/match" - "github.com/google/go-containerregistry/pkg/v1/partial" - "github.com/google/go-containerregistry/pkg/v1/stream" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -func computeDescriptor(ia IndexAddendum) (*v1.Descriptor, error) { - desc, err := partial.Descriptor(ia.Add) - if err != nil { - return nil, err - } - - // The IndexAddendum allows overriding Descriptor values. - if ia.Descriptor.Size != 0 { - desc.Size = ia.Descriptor.Size - } - if string(ia.Descriptor.MediaType) != "" { - desc.MediaType = ia.Descriptor.MediaType - } - if ia.Descriptor.Digest != (v1.Hash{}) { - desc.Digest = ia.Descriptor.Digest - } - if ia.Descriptor.Platform != nil { - desc.Platform = ia.Descriptor.Platform - } - if len(ia.Descriptor.URLs) != 0 { - desc.URLs = ia.Descriptor.URLs - } - if len(ia.Descriptor.Annotations) != 0 { - desc.Annotations = ia.Descriptor.Annotations - } - if ia.Descriptor.Data != nil { - desc.Data = ia.Descriptor.Data - } - - return desc, nil -} - -type index struct { - base v1.ImageIndex - adds []IndexAddendum - // remove is removed before adds - remove match.Matcher - - computed bool - manifest *v1.IndexManifest - annotations map[string]string - mediaType *types.MediaType - imageMap map[v1.Hash]v1.Image - indexMap map[v1.Hash]v1.ImageIndex - layerMap map[v1.Hash]v1.Layer - subject *v1.Descriptor - - sync.Mutex -} - -var _ v1.ImageIndex = (*index)(nil) - -func (i *index) MediaType() (types.MediaType, error) { - if i.mediaType != nil { - return *i.mediaType, nil - } - return i.base.MediaType() -} - -func (i *index) Size() (int64, error) { return partial.Size(i) } - -func (i *index) compute() error { - i.Lock() - defer i.Unlock() - - // Don't re-compute if already computed. - if i.computed { - return nil - } - - i.imageMap = make(map[v1.Hash]v1.Image) - i.indexMap = make(map[v1.Hash]v1.ImageIndex) - i.layerMap = make(map[v1.Hash]v1.Layer) - - m, err := i.base.IndexManifest() - if err != nil { - return err - } - manifest := m.DeepCopy() - manifests := manifest.Manifests - - if i.remove != nil { - var cleanedManifests []v1.Descriptor - for _, m := range manifests { - if !i.remove(m) { - cleanedManifests = append(cleanedManifests, m) - } - } - manifests = cleanedManifests - } - - for _, add := range i.adds { - desc, err := computeDescriptor(add) - if err != nil { - return err - } - - manifests = append(manifests, *desc) - if idx, ok := add.Add.(v1.ImageIndex); ok { - i.indexMap[desc.Digest] = idx - } else if img, ok := add.Add.(v1.Image); ok { - i.imageMap[desc.Digest] = img - } else if l, ok := add.Add.(v1.Layer); ok { - i.layerMap[desc.Digest] = l - } else { - logs.Warn.Printf("Unexpected index addendum: %T", add.Add) - } - } - - manifest.Manifests = manifests - - if i.mediaType != nil { - manifest.MediaType = *i.mediaType - } - - if i.annotations != nil { - if manifest.Annotations == nil { - manifest.Annotations = map[string]string{} - } - for k, v := range i.annotations { - manifest.Annotations[k] = v - } - } - manifest.Subject = i.subject - - i.manifest = manifest - i.computed = true - return nil -} - -func (i *index) Image(h v1.Hash) (v1.Image, error) { - if img, ok := i.imageMap[h]; ok { - return img, nil - } - return i.base.Image(h) -} - -func (i *index) ImageIndex(h v1.Hash) (v1.ImageIndex, error) { - if idx, ok := i.indexMap[h]; ok { - return idx, nil - } - return i.base.ImageIndex(h) -} - -type withLayer interface { - Layer(v1.Hash) (v1.Layer, error) -} - -// Workaround for #819. -func (i *index) Layer(h v1.Hash) (v1.Layer, error) { - if layer, ok := i.layerMap[h]; ok { - return layer, nil - } - if wl, ok := i.base.(withLayer); ok { - return wl.Layer(h) - } - return nil, fmt.Errorf("layer not found: %s", h) -} - -// Digest returns the sha256 of this image's manifest. -func (i *index) Digest() (v1.Hash, error) { - if err := i.compute(); err != nil { - return v1.Hash{}, err - } - return partial.Digest(i) -} - -// Manifest returns this image's Manifest object. -func (i *index) IndexManifest() (*v1.IndexManifest, error) { - if err := i.compute(); err != nil { - return nil, err - } - return i.manifest.DeepCopy(), nil -} - -// RawManifest returns the serialized bytes of Manifest() -func (i *index) RawManifest() ([]byte, error) { - if err := i.compute(); err != nil { - return nil, err - } - return json.Marshal(i.manifest) -} - -func (i *index) Manifests() ([]partial.Describable, error) { - if err := i.compute(); errors.Is(err, stream.ErrNotComputed) { - // Index contains a streamable layer which has not yet been - // consumed. Just return the manifests we have in case the caller - // is going to consume the streamable layers. - manifests, err := partial.Manifests(i.base) - if err != nil { - return nil, err - } - for _, add := range i.adds { - manifests = append(manifests, add.Add) - } - return manifests, nil - } else if err != nil { - return nil, err - } - - return partial.ComputeManifests(i) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/mutate.go b/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/mutate.go deleted file mode 100644 index 1a24b10d7..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/mutate.go +++ /dev/null @@ -1,555 +0,0 @@ -// Copyright 2018 Google LLC 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 mutate - -import ( - "archive/tar" - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "path/filepath" - "strings" - "time" - - "github.com/google/go-containerregistry/internal/gzip" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/empty" - "github.com/google/go-containerregistry/pkg/v1/match" - "github.com/google/go-containerregistry/pkg/v1/partial" - "github.com/google/go-containerregistry/pkg/v1/tarball" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -const whiteoutPrefix = ".wh." - -// Addendum contains layers and history to be appended -// to a base image -type Addendum struct { - Layer v1.Layer - History v1.History - URLs []string - Annotations map[string]string - MediaType types.MediaType -} - -// AppendLayers applies layers to a base image. -func AppendLayers(base v1.Image, layers ...v1.Layer) (v1.Image, error) { - additions := make([]Addendum, 0, len(layers)) - for _, layer := range layers { - additions = append(additions, Addendum{Layer: layer}) - } - - return Append(base, additions...) -} - -// Append will apply the list of addendums to the base image -func Append(base v1.Image, adds ...Addendum) (v1.Image, error) { - if len(adds) == 0 { - return base, nil - } - if err := validate(adds); err != nil { - return nil, err - } - - return &image{ - base: base, - adds: adds, - }, nil -} - -// Appendable is an interface that represents something that can be appended -// to an ImageIndex. We need to be able to construct a v1.Descriptor in order -// to append something, and this is the minimum required information for that. -type Appendable interface { - MediaType() (types.MediaType, error) - Digest() (v1.Hash, error) - Size() (int64, error) -} - -// IndexAddendum represents an appendable thing and all the properties that -// we may want to override in the resulting v1.Descriptor. -type IndexAddendum struct { - Add Appendable - v1.Descriptor -} - -// AppendManifests appends a manifest to the ImageIndex. -func AppendManifests(base v1.ImageIndex, adds ...IndexAddendum) v1.ImageIndex { - return &index{ - base: base, - adds: adds, - } -} - -// RemoveManifests removes any descriptors that match the match.Matcher. -func RemoveManifests(base v1.ImageIndex, matcher match.Matcher) v1.ImageIndex { - return &index{ - base: base, - remove: matcher, - } -} - -// Config mutates the provided v1.Image to have the provided v1.Config -func Config(base v1.Image, cfg v1.Config) (v1.Image, error) { - cf, err := base.ConfigFile() - if err != nil { - return nil, err - } - - cf.Config = cfg - - return ConfigFile(base, cf) -} - -// Subject mutates the subject on an image or index manifest. -// -// The input is expected to be a v1.Image or v1.ImageIndex, and -// returns the same type. You can type-assert the result like so: -// -// img := Subject(empty.Image, subj).(v1.Image) -// -// Or for an index: -// -// idx := Subject(empty.Index, subj).(v1.ImageIndex) -// -// If the input is not an Image or ImageIndex, the result will -// attempt to lazily annotate the raw manifest. -func Subject(f partial.WithRawManifest, subject v1.Descriptor) partial.WithRawManifest { - if img, ok := f.(v1.Image); ok { - return &image{ - base: img, - subject: &subject, - } - } - if idx, ok := f.(v1.ImageIndex); ok { - return &index{ - base: idx, - subject: &subject, - } - } - return arbitraryRawManifest{a: f, subject: &subject} -} - -// Annotations mutates the annotations on an annotatable image or index manifest. -// -// The annotatable input is expected to be a v1.Image or v1.ImageIndex, and -// returns the same type. You can type-assert the result like so: -// -// img := Annotations(empty.Image, map[string]string{ -// "foo": "bar", -// }).(v1.Image) -// -// Or for an index: -// -// idx := Annotations(empty.Index, map[string]string{ -// "foo": "bar", -// }).(v1.ImageIndex) -// -// If the input Annotatable is not an Image or ImageIndex, the result will -// attempt to lazily annotate the raw manifest. -func Annotations(f partial.WithRawManifest, anns map[string]string) partial.WithRawManifest { - if img, ok := f.(v1.Image); ok { - return &image{ - base: img, - annotations: anns, - } - } - if idx, ok := f.(v1.ImageIndex); ok { - return &index{ - base: idx, - annotations: anns, - } - } - return arbitraryRawManifest{a: f, anns: anns} -} - -type arbitraryRawManifest struct { - a partial.WithRawManifest - anns map[string]string - subject *v1.Descriptor -} - -func (a arbitraryRawManifest) RawManifest() ([]byte, error) { - b, err := a.a.RawManifest() - if err != nil { - return nil, err - } - var m map[string]any - if err := json.Unmarshal(b, &m); err != nil { - return nil, err - } - if ann, ok := m["annotations"]; ok { - if annm, ok := ann.(map[string]string); ok { - for k, v := range a.anns { - annm[k] = v - } - } else { - return nil, fmt.Errorf(".annotations is not a map: %T", ann) - } - } else { - m["annotations"] = a.anns - } - if a.subject != nil { - m["subject"] = a.subject - } - return json.Marshal(m) -} - -// ConfigFile mutates the provided v1.Image to have the provided v1.ConfigFile -func ConfigFile(base v1.Image, cfg *v1.ConfigFile) (v1.Image, error) { - m, err := base.Manifest() - if err != nil { - return nil, err - } - - image := &image{ - base: base, - manifest: m.DeepCopy(), - configFile: cfg, - } - - return image, nil -} - -// CreatedAt mutates the provided v1.Image to have the provided v1.Time -func CreatedAt(base v1.Image, created v1.Time) (v1.Image, error) { - cf, err := base.ConfigFile() - if err != nil { - return nil, err - } - - cfg := cf.DeepCopy() - cfg.Created = created - - return ConfigFile(base, cfg) -} - -// Extract takes an image and returns an io.ReadCloser containing the image's -// flattened filesystem. -// -// Callers can read the filesystem contents by passing the reader to -// tar.NewReader, or io.Copy it directly to some output. -// -// If a caller doesn't read the full contents, they should Close it to free up -// resources used during extraction. -func Extract(img v1.Image) io.ReadCloser { - pr, pw := io.Pipe() - - go func() { - // Close the writer with any errors encountered during - // extraction. These errors will be returned by the reader end - // on subsequent reads. If err == nil, the reader will return - // EOF. - pw.CloseWithError(extract(img, pw)) - }() - - return pr -} - -// Adapted from https://github.com/google/containerregistry/blob/da03b395ccdc4e149e34fbb540483efce962dc64/client/v2_2/docker_image_.py#L816 -func extract(img v1.Image, w io.Writer) error { - tarWriter := tar.NewWriter(w) - defer tarWriter.Close() - - fileMap := map[string]bool{} - - layers, err := img.Layers() - if err != nil { - return fmt.Errorf("retrieving image layers: %w", err) - } - - // we iterate through the layers in reverse order because it makes handling - // whiteout layers more efficient, since we can just keep track of the removed - // files as we see .wh. layers and ignore those in previous layers. - for i := len(layers) - 1; i >= 0; i-- { - layer := layers[i] - layerReader, err := layer.Uncompressed() - if err != nil { - return fmt.Errorf("reading layer contents: %w", err) - } - defer layerReader.Close() - tarReader := tar.NewReader(layerReader) - for { - header, err := tarReader.Next() - if errors.Is(err, io.EOF) { - break - } - if err != nil { - return fmt.Errorf("reading tar: %w", err) - } - - // Some tools prepend everything with "./", so if we don't Clean the - // name, we may have duplicate entries, which angers tar-split. - header.Name = filepath.Clean(header.Name) - // force PAX format to remove Name/Linkname length limit of 100 characters - // required by USTAR and to not depend on internal tar package guess which - // prefers USTAR over PAX - header.Format = tar.FormatPAX - - basename := filepath.Base(header.Name) - dirname := filepath.Dir(header.Name) - tombstone := strings.HasPrefix(basename, whiteoutPrefix) - if tombstone { - basename = basename[len(whiteoutPrefix):] - } - - // check if we have seen value before - // if we're checking a directory, don't filepath.Join names - var name string - if header.Typeflag == tar.TypeDir { - name = header.Name - } else { - name = filepath.Join(dirname, basename) - } - - if _, ok := fileMap[name]; ok { - continue - } - - // check for a whited out parent directory - if inWhiteoutDir(fileMap, name) { - continue - } - - // mark file as handled. non-directory implicitly tombstones - // any entries with a matching (or child) name - fileMap[name] = tombstone || !(header.Typeflag == tar.TypeDir) - if !tombstone { - if err := tarWriter.WriteHeader(header); err != nil { - return err - } - if header.Size > 0 { - if _, err := io.CopyN(tarWriter, tarReader, header.Size); err != nil { - return err - } - } - } - } - } - return nil -} - -func inWhiteoutDir(fileMap map[string]bool, file string) bool { - for { - if file == "" { - break - } - dirname := filepath.Dir(file) - if file == dirname { - break - } - if val, ok := fileMap[dirname]; ok && val { - return true - } - file = dirname - } - return false -} - -func max(a, b int) int { - if a > b { - return a - } - return b -} - -// Time sets all timestamps in an image to the given timestamp. -func Time(img v1.Image, t time.Time) (v1.Image, error) { - newImage := empty.Image - - layers, err := img.Layers() - if err != nil { - return nil, fmt.Errorf("getting image layers: %w", err) - } - - ocf, err := img.ConfigFile() - if err != nil { - return nil, fmt.Errorf("getting original config file: %w", err) - } - - addendums := make([]Addendum, max(len(ocf.History), len(layers))) - var historyIdx, addendumIdx int - for layerIdx := 0; layerIdx < len(layers); addendumIdx, layerIdx = addendumIdx+1, layerIdx+1 { - newLayer, err := layerTime(layers[layerIdx], t) - if err != nil { - return nil, fmt.Errorf("setting layer times: %w", err) - } - - // try to search for the history entry that corresponds to this layer - for ; historyIdx < len(ocf.History); historyIdx++ { - addendums[addendumIdx].History = ocf.History[historyIdx] - // if it's an EmptyLayer, do not set the Layer and have the Addendum with just the History - // and move on to the next History entry - if ocf.History[historyIdx].EmptyLayer { - addendumIdx++ - continue - } - // otherwise, we can exit from the cycle - historyIdx++ - break - } - if addendumIdx < len(addendums) { - addendums[addendumIdx].Layer = newLayer - } - } - - // add all leftover History entries - for ; historyIdx < len(ocf.History); historyIdx, addendumIdx = historyIdx+1, addendumIdx+1 { - addendums[addendumIdx].History = ocf.History[historyIdx] - } - - newImage, err = Append(newImage, addendums...) - if err != nil { - return nil, fmt.Errorf("appending layers: %w", err) - } - - cf, err := newImage.ConfigFile() - if err != nil { - return nil, fmt.Errorf("setting config file: %w", err) - } - - cfg := cf.DeepCopy() - - // Copy basic config over - cfg.Architecture = ocf.Architecture - cfg.OS = ocf.OS - cfg.OSVersion = ocf.OSVersion - cfg.Config = ocf.Config - - // Strip away timestamps from the config file - cfg.Created = v1.Time{Time: t} - - for i, h := range cfg.History { - h.Created = v1.Time{Time: t} - h.CreatedBy = ocf.History[i].CreatedBy - h.Comment = ocf.History[i].Comment - h.EmptyLayer = ocf.History[i].EmptyLayer - // Explicitly ignore Author field; which hinders reproducibility - h.Author = "" - cfg.History[i] = h - } - - return ConfigFile(newImage, cfg) -} - -func layerTime(layer v1.Layer, t time.Time) (v1.Layer, error) { - layerReader, err := layer.Uncompressed() - if err != nil { - return nil, fmt.Errorf("getting layer: %w", err) - } - defer layerReader.Close() - w := new(bytes.Buffer) - tarWriter := tar.NewWriter(w) - defer tarWriter.Close() - - tarReader := tar.NewReader(layerReader) - for { - header, err := tarReader.Next() - if errors.Is(err, io.EOF) { - break - } - if err != nil { - return nil, fmt.Errorf("reading layer: %w", err) - } - - header.ModTime = t - - //PAX and GNU Format support additional timestamps in the header - if header.Format == tar.FormatPAX || header.Format == tar.FormatGNU { - header.AccessTime = t - header.ChangeTime = t - } - - if err := tarWriter.WriteHeader(header); err != nil { - return nil, fmt.Errorf("writing tar header: %w", err) - } - - if header.Typeflag == tar.TypeReg { - // TODO(#1168): This should be lazy, and not buffer the entire layer contents. - if _, err = io.CopyN(tarWriter, tarReader, header.Size); err != nil { - return nil, fmt.Errorf("writing layer file: %w", err) - } - } - } - - if err := tarWriter.Close(); err != nil { - return nil, err - } - - b := w.Bytes() - // gzip the contents, then create the layer - opener := func() (io.ReadCloser, error) { - return gzip.ReadCloser(io.NopCloser(bytes.NewReader(b))), nil - } - layer, err = tarball.LayerFromOpener(opener) - if err != nil { - return nil, fmt.Errorf("creating layer: %w", err) - } - - return layer, nil -} - -// Canonical is a helper function to combine Time and configFile -// to remove any randomness during a docker build. -func Canonical(img v1.Image) (v1.Image, error) { - // Set all timestamps to 0 - created := time.Time{} - img, err := Time(img, created) - if err != nil { - return nil, err - } - - cf, err := img.ConfigFile() - if err != nil { - return nil, err - } - - // Get rid of host-dependent random config - cfg := cf.DeepCopy() - - cfg.Container = "" - cfg.Config.Hostname = "" - cfg.DockerVersion = "" - - return ConfigFile(img, cfg) -} - -// MediaType modifies the MediaType() of the given image. -func MediaType(img v1.Image, mt types.MediaType) v1.Image { - return &image{ - base: img, - mediaType: &mt, - } -} - -// ConfigMediaType modifies the MediaType() of the given image's Config. -// -// If !mt.IsConfig(), this will be the image's artifactType in any indexes it's a part of. -func ConfigMediaType(img v1.Image, mt types.MediaType) v1.Image { - return &image{ - base: img, - configMediaType: &mt, - } -} - -// IndexMediaType modifies the MediaType() of the given index. -func IndexMediaType(idx v1.ImageIndex, mt types.MediaType) v1.ImageIndex { - return &index{ - base: idx, - mediaType: &mt, - } -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/rebase.go b/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/rebase.go deleted file mode 100644 index c606e0b76..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/mutate/rebase.go +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright 2018 Google LLC 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 mutate - -import ( - "fmt" - - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/empty" -) - -// Rebase returns a new v1.Image where the oldBase in orig is replaced by newBase. -func Rebase(orig, oldBase, newBase v1.Image) (v1.Image, error) { - // Verify that oldBase's layers are present in orig, otherwise orig is - // not based on oldBase at all. - origLayers, err := orig.Layers() - if err != nil { - return nil, fmt.Errorf("failed to get layers for original: %w", err) - } - oldBaseLayers, err := oldBase.Layers() - if err != nil { - return nil, err - } - if len(oldBaseLayers) > len(origLayers) { - return nil, fmt.Errorf("image %q is not based on %q (too few layers)", orig, oldBase) - } - for i, l := range oldBaseLayers { - oldLayerDigest, err := l.Digest() - if err != nil { - return nil, fmt.Errorf("failed to get digest of layer %d of %q: %w", i, oldBase, err) - } - origLayerDigest, err := origLayers[i].Digest() - if err != nil { - return nil, fmt.Errorf("failed to get digest of layer %d of %q: %w", i, orig, err) - } - if oldLayerDigest != origLayerDigest { - return nil, fmt.Errorf("image %q is not based on %q (layer %d mismatch)", orig, oldBase, i) - } - } - - oldConfig, err := oldBase.ConfigFile() - if err != nil { - return nil, fmt.Errorf("failed to get config for old base: %w", err) - } - - origConfig, err := orig.ConfigFile() - if err != nil { - return nil, fmt.Errorf("failed to get config for original: %w", err) - } - - newConfig, err := newBase.ConfigFile() - if err != nil { - return nil, fmt.Errorf("could not get config for new base: %w", err) - } - - // Stitch together an image that contains: - // - original image's config - // - new base image's os/arch properties - // - new base image's layers + top of original image's layers - // - new base image's history + top of original image's history - rebasedImage, err := Config(empty.Image, *origConfig.Config.DeepCopy()) - if err != nil { - return nil, fmt.Errorf("failed to create empty image with original config: %w", err) - } - - // Add new config properties from existing images. - rebasedConfig, err := rebasedImage.ConfigFile() - if err != nil { - return nil, fmt.Errorf("could not get config for rebased image: %w", err) - } - // OS/Arch properties from new base - rebasedConfig.Architecture = newConfig.Architecture - rebasedConfig.OS = newConfig.OS - rebasedConfig.OSVersion = newConfig.OSVersion - - // Apply config properties to rebased. - rebasedImage, err = ConfigFile(rebasedImage, rebasedConfig) - if err != nil { - return nil, fmt.Errorf("failed to replace config for rebased image: %w", err) - } - - // Get new base layers and config for history. - newBaseLayers, err := newBase.Layers() - if err != nil { - return nil, fmt.Errorf("could not get new base layers for new base: %w", err) - } - // Add new base layers. - rebasedImage, err = Append(rebasedImage, createAddendums(0, 0, newConfig.History, newBaseLayers)...) - if err != nil { - return nil, fmt.Errorf("failed to append new base image: %w", err) - } - - // Add original layers above the old base. - rebasedImage, err = Append(rebasedImage, createAddendums(len(oldConfig.History), len(oldBaseLayers)+1, origConfig.History, origLayers)...) - if err != nil { - return nil, fmt.Errorf("failed to append original image: %w", err) - } - - return rebasedImage, nil -} - -// createAddendums makes a list of addendums from a history and layers starting from a specific history and layer -// indexes. -func createAddendums(startHistory, startLayer int, history []v1.History, layers []v1.Layer) []Addendum { - var adds []Addendum - // History should be a superset of layers; empty layers (e.g. ENV statements) only exist in history. - // They cannot be iterated identically but must be walked independently, only advancing the iterator for layers - // when a history entry for a non-empty layer is seen. - layerIndex := 0 - for historyIndex := range history { - var layer v1.Layer - emptyLayer := history[historyIndex].EmptyLayer - if !emptyLayer { - layer = layers[layerIndex] - layerIndex++ - } - if historyIndex >= startHistory || layerIndex >= startLayer { - adds = append(adds, Addendum{ - Layer: layer, - History: history[historyIndex], - }) - } - } - // In the event history was malformed or non-existent, append the remaining layers. - for i := layerIndex; i < len(layers); i++ { - if i >= startLayer { - adds = append(adds, Addendum{Layer: layers[layerIndex]}) - } - } - - return adds -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/partial/README.md b/vendor/github.com/google/go-containerregistry/pkg/v1/partial/README.md deleted file mode 100644 index 53ebbc6cc..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/partial/README.md +++ /dev/null @@ -1,82 +0,0 @@ -# `partial` - -[![GoDoc](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/partial?status.svg)](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/partial) - -## Partial Implementations - -There are roughly two kinds of image representations: compressed and uncompressed. - -The implementations for these kinds of images are almost identical, with the only -major difference being how blobs (config and layers) are fetched. This common -code lives in this package, where you provide a _partial_ implementation of a -compressed or uncompressed image, and you get back a full `v1.Image` implementation. - -### Examples - -In a registry, blobs are compressed, so it's easiest to implement a `v1.Image` in terms -of compressed layers. `remote.remoteImage` does this by implementing `CompressedImageCore`: - -```go -type CompressedImageCore interface { - RawConfigFile() ([]byte, error) - MediaType() (types.MediaType, error) - RawManifest() ([]byte, error) - LayerByDigest(v1.Hash) (CompressedLayer, error) -} -``` - -In a tarball, blobs are (often) uncompressed, so it's easiest to implement a `v1.Image` in terms -of uncompressed layers. `tarball.uncompressedImage` does this by implementing `UncompressedImageCore`: - -```go -type UncompressedImageCore interface { - RawConfigFile() ([]byte, error) - MediaType() (types.MediaType, error) - LayerByDiffID(v1.Hash) (UncompressedLayer, error) -} -``` - -## Optional Methods - -Where possible, we access some information via optional methods as an optimization. - -### [`partial.Descriptor`](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/partial#Descriptor) - -There are some properties of a [`Descriptor`](https://github.com/opencontainers/image-spec/blob/master/descriptor.md#properties) that aren't derivable from just image data: - -* `MediaType` -* `Platform` -* `URLs` -* `Annotations` - -For example, in a `tarball.Image`, there is a `LayerSources` field that contains -an entire layer descriptor with `URLs` information for foreign layers. This -information can be passed through to callers by implementing this optional -`Descriptor` method. - -See [`#654`](https://github.com/google/go-containerregistry/pull/654). - -### [`partial.UncompressedSize`](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/partial#UncompressedSize) - -Usually, you don't need to know the uncompressed size of a layer, since that -information isn't stored in a config file (just he sha256 is needed); however, -there are cases where it is very helpful to know the layer size, e.g. when -writing the uncompressed layer into a tarball. - -See [`#655`](https://github.com/google/go-containerregistry/pull/655). - -### [`partial.Exists`](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/partial#Exists) - -We generally don't care about the existence of something as granular as a -layer, and would rather ensure all the invariants of an image are upheld via -the `validate` package. However, there are situations where we want to do a -quick smoke test to ensure that the underlying storage engine hasn't been -corrupted by something e.g. deleting files or blobs. Thus, we've exposed an -optional `Exists` method that does an existence check without actually reading -any bytes. - -The `remote` package implements this via `HEAD` requests. - -The `layout` package implements this via `os.Stat`. - -See [`#838`](https://github.com/google/go-containerregistry/pull/838). diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/partial/compressed.go b/vendor/github.com/google/go-containerregistry/pkg/v1/partial/compressed.go deleted file mode 100644 index 44989ac96..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/partial/compressed.go +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright 2018 Google LLC 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 partial - -import ( - "io" - - "github.com/google/go-containerregistry/internal/and" - "github.com/google/go-containerregistry/internal/compression" - "github.com/google/go-containerregistry/internal/gzip" - "github.com/google/go-containerregistry/internal/zstd" - comp "github.com/google/go-containerregistry/pkg/compression" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -// CompressedLayer represents the bare minimum interface a natively -// compressed layer must implement for us to produce a v1.Layer -type CompressedLayer interface { - // Digest returns the Hash of the compressed layer. - Digest() (v1.Hash, error) - - // Compressed returns an io.ReadCloser for the compressed layer contents. - Compressed() (io.ReadCloser, error) - - // Size returns the compressed size of the Layer. - Size() (int64, error) - - // Returns the mediaType for the compressed Layer - MediaType() (types.MediaType, error) -} - -// compressedLayerExtender implements v1.Image using the compressed base properties. -type compressedLayerExtender struct { - CompressedLayer -} - -// Uncompressed implements v1.Layer -func (cle *compressedLayerExtender) Uncompressed() (io.ReadCloser, error) { - rc, err := cle.Compressed() - if err != nil { - return nil, err - } - - // Often, the "compressed" bytes are not actually-compressed. - // Peek at the first two bytes to determine whether it's correct to - // wrap this with gzip.UnzipReadCloser or zstd.UnzipReadCloser. - cp, pr, err := compression.PeekCompression(rc) - if err != nil { - return nil, err - } - - prc := &and.ReadCloser{ - Reader: pr, - CloseFunc: rc.Close, - } - - switch cp { - case comp.GZip: - return gzip.UnzipReadCloser(prc) - case comp.ZStd: - return zstd.UnzipReadCloser(prc) - default: - return prc, nil - } -} - -// DiffID implements v1.Layer -func (cle *compressedLayerExtender) DiffID() (v1.Hash, error) { - // If our nested CompressedLayer implements DiffID, - // then delegate to it instead. - if wdi, ok := cle.CompressedLayer.(WithDiffID); ok { - return wdi.DiffID() - } - r, err := cle.Uncompressed() - if err != nil { - return v1.Hash{}, err - } - defer r.Close() - h, _, err := v1.SHA256(r) - return h, err -} - -// CompressedToLayer fills in the missing methods from a CompressedLayer so that it implements v1.Layer -func CompressedToLayer(ul CompressedLayer) (v1.Layer, error) { - return &compressedLayerExtender{ul}, nil -} - -// CompressedImageCore represents the base minimum interface a natively -// compressed image must implement for us to produce a v1.Image. -type CompressedImageCore interface { - ImageCore - - // RawManifest returns the serialized bytes of the manifest. - RawManifest() ([]byte, error) - - // LayerByDigest is a variation on the v1.Image method, which returns - // a CompressedLayer instead. - LayerByDigest(v1.Hash) (CompressedLayer, error) -} - -// compressedImageExtender implements v1.Image by extending CompressedImageCore with the -// appropriate methods computed from the minimal core. -type compressedImageExtender struct { - CompressedImageCore -} - -// Assert that our extender type completes the v1.Image interface -var _ v1.Image = (*compressedImageExtender)(nil) - -// Digest implements v1.Image -func (i *compressedImageExtender) Digest() (v1.Hash, error) { - return Digest(i) -} - -// ConfigName implements v1.Image -func (i *compressedImageExtender) ConfigName() (v1.Hash, error) { - return ConfigName(i) -} - -// Layers implements v1.Image -func (i *compressedImageExtender) Layers() ([]v1.Layer, error) { - hs, err := FSLayers(i) - if err != nil { - return nil, err - } - ls := make([]v1.Layer, 0, len(hs)) - for _, h := range hs { - l, err := i.LayerByDigest(h) - if err != nil { - return nil, err - } - ls = append(ls, l) - } - return ls, nil -} - -// LayerByDigest implements v1.Image -func (i *compressedImageExtender) LayerByDigest(h v1.Hash) (v1.Layer, error) { - cl, err := i.CompressedImageCore.LayerByDigest(h) - if err != nil { - return nil, err - } - return CompressedToLayer(cl) -} - -// LayerByDiffID implements v1.Image -func (i *compressedImageExtender) LayerByDiffID(h v1.Hash) (v1.Layer, error) { - h, err := DiffIDToBlob(i, h) - if err != nil { - return nil, err - } - return i.LayerByDigest(h) -} - -// ConfigFile implements v1.Image -func (i *compressedImageExtender) ConfigFile() (*v1.ConfigFile, error) { - return ConfigFile(i) -} - -// Manifest implements v1.Image -func (i *compressedImageExtender) Manifest() (*v1.Manifest, error) { - return Manifest(i) -} - -// Size implements v1.Image -func (i *compressedImageExtender) Size() (int64, error) { - return Size(i) -} - -// CompressedToImage fills in the missing methods from a CompressedImageCore so that it implements v1.Image -func CompressedToImage(cic CompressedImageCore) (v1.Image, error) { - return &compressedImageExtender{ - CompressedImageCore: cic, - }, nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/partial/doc.go b/vendor/github.com/google/go-containerregistry/pkg/v1/partial/doc.go deleted file mode 100644 index 153dfe4d5..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/partial/doc.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2018 Google LLC 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 partial defines methods for building up a v1.Image from -// minimal subsets that are sufficient for defining a v1.Image. -package partial diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/partial/image.go b/vendor/github.com/google/go-containerregistry/pkg/v1/partial/image.go deleted file mode 100644 index c65f45e0d..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/partial/image.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2018 Google LLC 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 partial - -import ( - "github.com/google/go-containerregistry/pkg/v1/types" -) - -// ImageCore is the core set of properties without which we cannot build a v1.Image -type ImageCore interface { - // RawConfigFile returns the serialized bytes of this image's config file. - RawConfigFile() ([]byte, error) - - // MediaType of this image's manifest. - MediaType() (types.MediaType, error) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/partial/index.go b/vendor/github.com/google/go-containerregistry/pkg/v1/partial/index.go deleted file mode 100644 index 10cfb2b2f..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/partial/index.go +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright 2020 Google LLC 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 partial - -import ( - "fmt" - - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/match" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -// FindManifests given a v1.ImageIndex, find the manifests that fit the matcher. -func FindManifests(index v1.ImageIndex, matcher match.Matcher) ([]v1.Descriptor, error) { - // get the actual manifest list - indexManifest, err := index.IndexManifest() - if err != nil { - return nil, fmt.Errorf("unable to get raw index: %w", err) - } - manifests := []v1.Descriptor{} - // try to get the root of our image - for _, manifest := range indexManifest.Manifests { - if matcher(manifest) { - manifests = append(manifests, manifest) - } - } - return manifests, nil -} - -// FindImages given a v1.ImageIndex, find the images that fit the matcher. If a Descriptor -// matches the provider Matcher, but the referenced item is not an Image, ignores it. -// Only returns those that match the Matcher and are images. -func FindImages(index v1.ImageIndex, matcher match.Matcher) ([]v1.Image, error) { - matches := []v1.Image{} - manifests, err := FindManifests(index, matcher) - if err != nil { - return nil, err - } - for _, desc := range manifests { - // if it is not an image, ignore it - if !desc.MediaType.IsImage() { - continue - } - img, err := index.Image(desc.Digest) - if err != nil { - return nil, err - } - matches = append(matches, img) - } - return matches, nil -} - -// FindIndexes given a v1.ImageIndex, find the indexes that fit the matcher. If a Descriptor -// matches the provider Matcher, but the referenced item is not an Index, ignores it. -// Only returns those that match the Matcher and are indexes. -func FindIndexes(index v1.ImageIndex, matcher match.Matcher) ([]v1.ImageIndex, error) { - matches := []v1.ImageIndex{} - manifests, err := FindManifests(index, matcher) - if err != nil { - return nil, err - } - for _, desc := range manifests { - if !desc.MediaType.IsIndex() { - continue - } - // if it is not an index, ignore it - idx, err := index.ImageIndex(desc.Digest) - if err != nil { - return nil, err - } - matches = append(matches, idx) - } - return matches, nil -} - -type withManifests interface { - Manifests() ([]Describable, error) -} - -type withLayer interface { - Layer(v1.Hash) (v1.Layer, error) -} - -type describable struct { - desc v1.Descriptor -} - -func (d describable) Digest() (v1.Hash, error) { - return d.desc.Digest, nil -} - -func (d describable) Size() (int64, error) { - return d.desc.Size, nil -} - -func (d describable) MediaType() (types.MediaType, error) { - return d.desc.MediaType, nil -} - -func (d describable) Descriptor() (*v1.Descriptor, error) { - return &d.desc, nil -} - -// Manifests is analogous to v1.Image.Layers in that it allows values in the -// returned list to be lazily evaluated, which enables an index to contain -// an image that contains a streaming layer. -// -// This should have been part of the v1.ImageIndex interface, but wasn't. -// It is instead usable through this extension interface. -func Manifests(idx v1.ImageIndex) ([]Describable, error) { - if wm, ok := idx.(withManifests); ok { - return wm.Manifests() - } - - return ComputeManifests(idx) -} - -// ComputeManifests provides a fallback implementation for Manifests. -func ComputeManifests(idx v1.ImageIndex) ([]Describable, error) { - m, err := idx.IndexManifest() - if err != nil { - return nil, err - } - manifests := []Describable{} - for _, desc := range m.Manifests { - switch { - case desc.MediaType.IsImage(): - img, err := idx.Image(desc.Digest) - if err != nil { - return nil, err - } - manifests = append(manifests, img) - case desc.MediaType.IsIndex(): - idx, err := idx.ImageIndex(desc.Digest) - if err != nil { - return nil, err - } - manifests = append(manifests, idx) - default: - if wl, ok := idx.(withLayer); ok { - layer, err := wl.Layer(desc.Digest) - if err != nil { - return nil, err - } - manifests = append(manifests, layer) - } else { - manifests = append(manifests, describable{desc}) - } - } - } - - return manifests, nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/partial/uncompressed.go b/vendor/github.com/google/go-containerregistry/pkg/v1/partial/uncompressed.go deleted file mode 100644 index df20d3aa9..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/partial/uncompressed.go +++ /dev/null @@ -1,223 +0,0 @@ -// Copyright 2018 Google LLC 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 partial - -import ( - "bytes" - "io" - "sync" - - "github.com/google/go-containerregistry/internal/gzip" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -// UncompressedLayer represents the bare minimum interface a natively -// uncompressed layer must implement for us to produce a v1.Layer -type UncompressedLayer interface { - // DiffID returns the Hash of the uncompressed layer. - DiffID() (v1.Hash, error) - - // Uncompressed returns an io.ReadCloser for the uncompressed layer contents. - Uncompressed() (io.ReadCloser, error) - - // Returns the mediaType for the compressed Layer - MediaType() (types.MediaType, error) -} - -// uncompressedLayerExtender implements v1.Image using the uncompressed base properties. -type uncompressedLayerExtender struct { - UncompressedLayer - // Memoize size/hash so that the methods aren't twice as - // expensive as doing this manually. - hash v1.Hash - size int64 - hashSizeError error - once sync.Once -} - -// Compressed implements v1.Layer -func (ule *uncompressedLayerExtender) Compressed() (io.ReadCloser, error) { - u, err := ule.Uncompressed() - if err != nil { - return nil, err - } - return gzip.ReadCloser(u), nil -} - -// Digest implements v1.Layer -func (ule *uncompressedLayerExtender) Digest() (v1.Hash, error) { - ule.calcSizeHash() - return ule.hash, ule.hashSizeError -} - -// Size implements v1.Layer -func (ule *uncompressedLayerExtender) Size() (int64, error) { - ule.calcSizeHash() - return ule.size, ule.hashSizeError -} - -func (ule *uncompressedLayerExtender) calcSizeHash() { - ule.once.Do(func() { - var r io.ReadCloser - r, ule.hashSizeError = ule.Compressed() - if ule.hashSizeError != nil { - return - } - defer r.Close() - ule.hash, ule.size, ule.hashSizeError = v1.SHA256(r) - }) -} - -// UncompressedToLayer fills in the missing methods from an UncompressedLayer so that it implements v1.Layer -func UncompressedToLayer(ul UncompressedLayer) (v1.Layer, error) { - return &uncompressedLayerExtender{UncompressedLayer: ul}, nil -} - -// UncompressedImageCore represents the bare minimum interface a natively -// uncompressed image must implement for us to produce a v1.Image -type UncompressedImageCore interface { - ImageCore - - // LayerByDiffID is a variation on the v1.Image method, which returns - // an UncompressedLayer instead. - LayerByDiffID(v1.Hash) (UncompressedLayer, error) -} - -// UncompressedToImage fills in the missing methods from an UncompressedImageCore so that it implements v1.Image. -func UncompressedToImage(uic UncompressedImageCore) (v1.Image, error) { - return &uncompressedImageExtender{ - UncompressedImageCore: uic, - }, nil -} - -// uncompressedImageExtender implements v1.Image by extending UncompressedImageCore with the -// appropriate methods computed from the minimal core. -type uncompressedImageExtender struct { - UncompressedImageCore - - lock sync.Mutex - manifest *v1.Manifest -} - -// Assert that our extender type completes the v1.Image interface -var _ v1.Image = (*uncompressedImageExtender)(nil) - -// Digest implements v1.Image -func (i *uncompressedImageExtender) Digest() (v1.Hash, error) { - return Digest(i) -} - -// Manifest implements v1.Image -func (i *uncompressedImageExtender) Manifest() (*v1.Manifest, error) { - i.lock.Lock() - defer i.lock.Unlock() - if i.manifest != nil { - return i.manifest, nil - } - - b, err := i.RawConfigFile() - if err != nil { - return nil, err - } - - cfgHash, cfgSize, err := v1.SHA256(bytes.NewReader(b)) - if err != nil { - return nil, err - } - - m := &v1.Manifest{ - SchemaVersion: 2, - MediaType: types.DockerManifestSchema2, - Config: v1.Descriptor{ - MediaType: types.DockerConfigJSON, - Size: cfgSize, - Digest: cfgHash, - }, - } - - ls, err := i.Layers() - if err != nil { - return nil, err - } - - m.Layers = make([]v1.Descriptor, len(ls)) - for i, l := range ls { - desc, err := Descriptor(l) - if err != nil { - return nil, err - } - - m.Layers[i] = *desc - } - - i.manifest = m - return i.manifest, nil -} - -// RawManifest implements v1.Image -func (i *uncompressedImageExtender) RawManifest() ([]byte, error) { - return RawManifest(i) -} - -// Size implements v1.Image -func (i *uncompressedImageExtender) Size() (int64, error) { - return Size(i) -} - -// ConfigName implements v1.Image -func (i *uncompressedImageExtender) ConfigName() (v1.Hash, error) { - return ConfigName(i) -} - -// ConfigFile implements v1.Image -func (i *uncompressedImageExtender) ConfigFile() (*v1.ConfigFile, error) { - return ConfigFile(i) -} - -// Layers implements v1.Image -func (i *uncompressedImageExtender) Layers() ([]v1.Layer, error) { - diffIDs, err := DiffIDs(i) - if err != nil { - return nil, err - } - ls := make([]v1.Layer, 0, len(diffIDs)) - for _, h := range diffIDs { - l, err := i.LayerByDiffID(h) - if err != nil { - return nil, err - } - ls = append(ls, l) - } - return ls, nil -} - -// LayerByDiffID implements v1.Image -func (i *uncompressedImageExtender) LayerByDiffID(diffID v1.Hash) (v1.Layer, error) { - ul, err := i.UncompressedImageCore.LayerByDiffID(diffID) - if err != nil { - return nil, err - } - return UncompressedToLayer(ul) -} - -// LayerByDigest implements v1.Image -func (i *uncompressedImageExtender) LayerByDigest(h v1.Hash) (v1.Layer, error) { - diffID, err := BlobToDiffID(i, h) - if err != nil { - return nil, err - } - return i.LayerByDiffID(diffID) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/partial/with.go b/vendor/github.com/google/go-containerregistry/pkg/v1/partial/with.go deleted file mode 100644 index c8b22b3f9..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/partial/with.go +++ /dev/null @@ -1,436 +0,0 @@ -// Copyright 2018 Google LLC 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 partial - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -// WithRawConfigFile defines the subset of v1.Image used by these helper methods -type WithRawConfigFile interface { - // RawConfigFile returns the serialized bytes of this image's config file. - RawConfigFile() ([]byte, error) -} - -// ConfigFile is a helper for implementing v1.Image -func ConfigFile(i WithRawConfigFile) (*v1.ConfigFile, error) { - b, err := i.RawConfigFile() - if err != nil { - return nil, err - } - return v1.ParseConfigFile(bytes.NewReader(b)) -} - -// ConfigName is a helper for implementing v1.Image -func ConfigName(i WithRawConfigFile) (v1.Hash, error) { - b, err := i.RawConfigFile() - if err != nil { - return v1.Hash{}, err - } - h, _, err := v1.SHA256(bytes.NewReader(b)) - return h, err -} - -type configLayer struct { - hash v1.Hash - content []byte -} - -// Digest implements v1.Layer -func (cl *configLayer) Digest() (v1.Hash, error) { - return cl.hash, nil -} - -// DiffID implements v1.Layer -func (cl *configLayer) DiffID() (v1.Hash, error) { - return cl.hash, nil -} - -// Uncompressed implements v1.Layer -func (cl *configLayer) Uncompressed() (io.ReadCloser, error) { - return io.NopCloser(bytes.NewBuffer(cl.content)), nil -} - -// Compressed implements v1.Layer -func (cl *configLayer) Compressed() (io.ReadCloser, error) { - return io.NopCloser(bytes.NewBuffer(cl.content)), nil -} - -// Size implements v1.Layer -func (cl *configLayer) Size() (int64, error) { - return int64(len(cl.content)), nil -} - -func (cl *configLayer) MediaType() (types.MediaType, error) { - // Defaulting this to OCIConfigJSON as it should remain - // backwards compatible with DockerConfigJSON - return types.OCIConfigJSON, nil -} - -var _ v1.Layer = (*configLayer)(nil) - -// withConfigLayer allows partial image implementations to provide a layer -// for their config file. -type withConfigLayer interface { - ConfigLayer() (v1.Layer, error) -} - -// ConfigLayer implements v1.Layer from the raw config bytes. -// This is so that clients (e.g. remote) can access the config as a blob. -// -// Images that want to return a specific layer implementation can implement -// withConfigLayer. -func ConfigLayer(i WithRawConfigFile) (v1.Layer, error) { - if wcl, ok := unwrap(i).(withConfigLayer); ok { - return wcl.ConfigLayer() - } - - h, err := ConfigName(i) - if err != nil { - return nil, err - } - rcfg, err := i.RawConfigFile() - if err != nil { - return nil, err - } - return &configLayer{ - hash: h, - content: rcfg, - }, nil -} - -// WithConfigFile defines the subset of v1.Image used by these helper methods -type WithConfigFile interface { - // ConfigFile returns this image's config file. - ConfigFile() (*v1.ConfigFile, error) -} - -// DiffIDs is a helper for implementing v1.Image -func DiffIDs(i WithConfigFile) ([]v1.Hash, error) { - cfg, err := i.ConfigFile() - if err != nil { - return nil, err - } - return cfg.RootFS.DiffIDs, nil -} - -// RawConfigFile is a helper for implementing v1.Image -func RawConfigFile(i WithConfigFile) ([]byte, error) { - cfg, err := i.ConfigFile() - if err != nil { - return nil, err - } - return json.Marshal(cfg) -} - -// WithRawManifest defines the subset of v1.Image used by these helper methods -type WithRawManifest interface { - // RawManifest returns the serialized bytes of this image's config file. - RawManifest() ([]byte, error) -} - -// Digest is a helper for implementing v1.Image -func Digest(i WithRawManifest) (v1.Hash, error) { - mb, err := i.RawManifest() - if err != nil { - return v1.Hash{}, err - } - digest, _, err := v1.SHA256(bytes.NewReader(mb)) - return digest, err -} - -// Manifest is a helper for implementing v1.Image -func Manifest(i WithRawManifest) (*v1.Manifest, error) { - b, err := i.RawManifest() - if err != nil { - return nil, err - } - return v1.ParseManifest(bytes.NewReader(b)) -} - -// WithManifest defines the subset of v1.Image used by these helper methods -type WithManifest interface { - // Manifest returns this image's Manifest object. - Manifest() (*v1.Manifest, error) -} - -// RawManifest is a helper for implementing v1.Image -func RawManifest(i WithManifest) ([]byte, error) { - m, err := i.Manifest() - if err != nil { - return nil, err - } - return json.Marshal(m) -} - -// Size is a helper for implementing v1.Image -func Size(i WithRawManifest) (int64, error) { - b, err := i.RawManifest() - if err != nil { - return -1, err - } - return int64(len(b)), nil -} - -// FSLayers is a helper for implementing v1.Image -func FSLayers(i WithManifest) ([]v1.Hash, error) { - m, err := i.Manifest() - if err != nil { - return nil, err - } - fsl := make([]v1.Hash, len(m.Layers)) - for i, l := range m.Layers { - fsl[i] = l.Digest - } - return fsl, nil -} - -// BlobSize is a helper for implementing v1.Image -func BlobSize(i WithManifest, h v1.Hash) (int64, error) { - d, err := BlobDescriptor(i, h) - if err != nil { - return -1, err - } - return d.Size, nil -} - -// BlobDescriptor is a helper for implementing v1.Image -func BlobDescriptor(i WithManifest, h v1.Hash) (*v1.Descriptor, error) { - m, err := i.Manifest() - if err != nil { - return nil, err - } - - if m.Config.Digest == h { - return &m.Config, nil - } - - for _, l := range m.Layers { - if l.Digest == h { - return &l, nil - } - } - return nil, fmt.Errorf("blob %v not found", h) -} - -// WithManifestAndConfigFile defines the subset of v1.Image used by these helper methods -type WithManifestAndConfigFile interface { - WithConfigFile - - // Manifest returns this image's Manifest object. - Manifest() (*v1.Manifest, error) -} - -// BlobToDiffID is a helper for mapping between compressed -// and uncompressed blob hashes. -func BlobToDiffID(i WithManifestAndConfigFile, h v1.Hash) (v1.Hash, error) { - blobs, err := FSLayers(i) - if err != nil { - return v1.Hash{}, err - } - diffIDs, err := DiffIDs(i) - if err != nil { - return v1.Hash{}, err - } - if len(blobs) != len(diffIDs) { - return v1.Hash{}, fmt.Errorf("mismatched fs layers (%d) and diff ids (%d)", len(blobs), len(diffIDs)) - } - for i, blob := range blobs { - if blob == h { - return diffIDs[i], nil - } - } - return v1.Hash{}, fmt.Errorf("unknown blob %v", h) -} - -// DiffIDToBlob is a helper for mapping between uncompressed -// and compressed blob hashes. -func DiffIDToBlob(wm WithManifestAndConfigFile, h v1.Hash) (v1.Hash, error) { - blobs, err := FSLayers(wm) - if err != nil { - return v1.Hash{}, err - } - diffIDs, err := DiffIDs(wm) - if err != nil { - return v1.Hash{}, err - } - if len(blobs) != len(diffIDs) { - return v1.Hash{}, fmt.Errorf("mismatched fs layers (%d) and diff ids (%d)", len(blobs), len(diffIDs)) - } - for i, diffID := range diffIDs { - if diffID == h { - return blobs[i], nil - } - } - return v1.Hash{}, fmt.Errorf("unknown diffID %v", h) -} - -// WithDiffID defines the subset of v1.Layer for exposing the DiffID method. -type WithDiffID interface { - DiffID() (v1.Hash, error) -} - -// withDescriptor allows partial layer implementations to provide a layer -// descriptor to the partial image manifest builder. This allows partial -// uncompressed layers to provide foreign layer metadata like URLs to the -// uncompressed image manifest. -type withDescriptor interface { - Descriptor() (*v1.Descriptor, error) -} - -// Describable represents something for which we can produce a v1.Descriptor. -type Describable interface { - Digest() (v1.Hash, error) - MediaType() (types.MediaType, error) - Size() (int64, error) -} - -// Descriptor returns a v1.Descriptor given a Describable. It also encodes -// some logic for unwrapping things that have been wrapped by -// CompressedToLayer, UncompressedToLayer, CompressedToImage, or -// UncompressedToImage. -func Descriptor(d Describable) (*v1.Descriptor, error) { - // If Describable implements Descriptor itself, return that. - if wd, ok := unwrap(d).(withDescriptor); ok { - return wd.Descriptor() - } - - // If all else fails, compute the descriptor from the individual methods. - var ( - desc v1.Descriptor - err error - ) - - if desc.Size, err = d.Size(); err != nil { - return nil, err - } - if desc.Digest, err = d.Digest(); err != nil { - return nil, err - } - if desc.MediaType, err = d.MediaType(); err != nil { - return nil, err - } - if wat, ok := d.(withArtifactType); ok { - if desc.ArtifactType, err = wat.ArtifactType(); err != nil { - return nil, err - } - } else { - if wrm, ok := d.(WithRawManifest); ok && desc.MediaType.IsImage() { - mf, _ := Manifest(wrm) - // Failing to parse as a manifest should just be ignored. - // The manifest might not be valid, and that's okay. - if mf != nil && !mf.Config.MediaType.IsConfig() { - desc.ArtifactType = string(mf.Config.MediaType) - } - } - } - - return &desc, nil -} - -type withArtifactType interface { - ArtifactType() (string, error) -} - -type withUncompressedSize interface { - UncompressedSize() (int64, error) -} - -// UncompressedSize returns the size of the Uncompressed layer. If the -// underlying implementation doesn't implement UncompressedSize directly, -// this will compute the uncompressedSize by reading everything returned -// by Compressed(). This is potentially expensive and may consume the contents -// for streaming layers. -func UncompressedSize(l v1.Layer) (int64, error) { - // If the layer implements UncompressedSize itself, return that. - if wus, ok := unwrap(l).(withUncompressedSize); ok { - return wus.UncompressedSize() - } - - // The layer doesn't implement UncompressedSize, we need to compute it. - rc, err := l.Uncompressed() - if err != nil { - return -1, err - } - defer rc.Close() - - return io.Copy(io.Discard, rc) -} - -type withExists interface { - Exists() (bool, error) -} - -// Exists checks to see if a layer exists. This is a hack to work around the -// mistakes of the partial package. Don't use this. -func Exists(l v1.Layer) (bool, error) { - // If the layer implements Exists itself, return that. - if we, ok := unwrap(l).(withExists); ok { - return we.Exists() - } - - // The layer doesn't implement Exists, so we hope that calling Compressed() - // is enough to trigger an error if the layer does not exist. - rc, err := l.Compressed() - if err != nil { - return false, err - } - defer rc.Close() - - // We may want to try actually reading a single byte, but if we need to do - // that, we should just fix this hack. - return true, nil -} - -// Recursively unwrap our wrappers so that we can check for the original implementation. -// We might want to expose this? -func unwrap(i any) any { - if ule, ok := i.(*uncompressedLayerExtender); ok { - return unwrap(ule.UncompressedLayer) - } - if cle, ok := i.(*compressedLayerExtender); ok { - return unwrap(cle.CompressedLayer) - } - if uie, ok := i.(*uncompressedImageExtender); ok { - return unwrap(uie.UncompressedImageCore) - } - if cie, ok := i.(*compressedImageExtender); ok { - return unwrap(cie.CompressedImageCore) - } - return i -} - -// ArtifactType returns the artifact type for the given manifest. -// -// If the manifest reports its own artifact type, that's returned, otherwise -// the manifest is parsed and, if successful, its config.mediaType is returned. -func ArtifactType(w WithManifest) (string, error) { - if wat, ok := w.(withArtifactType); ok { - return wat.ArtifactType() - } - mf, _ := w.Manifest() - // Failing to parse as a manifest should just be ignored. - // The manifest might not be valid, and that's okay. - if mf != nil && !mf.Config.MediaType.IsConfig() { - return string(mf.Config.MediaType), nil - } - return "", nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/platform.go b/vendor/github.com/google/go-containerregistry/pkg/v1/platform.go deleted file mode 100644 index 59ca40269..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/platform.go +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright 2018 Google LLC 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 v1 - -import ( - "fmt" - "sort" - "strings" -) - -// Platform represents the target os/arch for an image. -type Platform struct { - Architecture string `json:"architecture"` - OS string `json:"os"` - OSVersion string `json:"os.version,omitempty"` - OSFeatures []string `json:"os.features,omitempty"` - Variant string `json:"variant,omitempty"` - Features []string `json:"features,omitempty"` -} - -func (p Platform) String() string { - if p.OS == "" { - return "" - } - var b strings.Builder - b.WriteString(p.OS) - if p.Architecture != "" { - b.WriteString("/") - b.WriteString(p.Architecture) - } - if p.Variant != "" { - b.WriteString("/") - b.WriteString(p.Variant) - } - if p.OSVersion != "" { - b.WriteString(":") - b.WriteString(p.OSVersion) - } - return b.String() -} - -// ParsePlatform parses a string representing a Platform, if possible. -func ParsePlatform(s string) (*Platform, error) { - var p Platform - parts := strings.Split(strings.TrimSpace(s), ":") - if len(parts) == 2 { - p.OSVersion = parts[1] - } - parts = strings.Split(parts[0], "/") - if len(parts) > 0 { - p.OS = parts[0] - } - if len(parts) > 1 { - p.Architecture = parts[1] - } - if len(parts) > 2 { - p.Variant = parts[2] - } - if len(parts) > 3 { - return nil, fmt.Errorf("too many slashes in platform spec: %s", s) - } - return &p, nil -} - -// Equals returns true if the given platform is semantically equivalent to this one. -// The order of Features and OSFeatures is not important. -func (p Platform) Equals(o Platform) bool { - return p.OS == o.OS && - p.Architecture == o.Architecture && - p.Variant == o.Variant && - p.OSVersion == o.OSVersion && - stringSliceEqualIgnoreOrder(p.OSFeatures, o.OSFeatures) && - stringSliceEqualIgnoreOrder(p.Features, o.Features) -} - -// Satisfies returns true if this Platform "satisfies" the given spec Platform. -// -// Note that this is different from Equals and that Satisfies is not reflexive. -// -// The given spec represents "requirements" such that any missing values in the -// spec are not compared. -// -// For OSFeatures and Features, Satisfies will return true if this Platform's -// fields contain a superset of the values in the spec's fields (order ignored). -func (p Platform) Satisfies(spec Platform) bool { - return satisfies(spec.OS, p.OS) && - satisfies(spec.Architecture, p.Architecture) && - satisfies(spec.Variant, p.Variant) && - satisfies(spec.OSVersion, p.OSVersion) && - satisfiesList(spec.OSFeatures, p.OSFeatures) && - satisfiesList(spec.Features, p.Features) -} - -func satisfies(want, have string) bool { - return want == "" || want == have -} - -func satisfiesList(want, have []string) bool { - if len(want) == 0 { - return true - } - - set := map[string]struct{}{} - for _, h := range have { - set[h] = struct{}{} - } - - for _, w := range want { - if _, ok := set[w]; !ok { - return false - } - } - - return true -} - -// stringSliceEqual compares 2 string slices and returns if their contents are identical. -func stringSliceEqual(a, b []string) bool { - if len(a) != len(b) { - return false - } - for i, elm := range a { - if elm != b[i] { - return false - } - } - return true -} - -// stringSliceEqualIgnoreOrder compares 2 string slices and returns if their contents are identical, ignoring order -func stringSliceEqualIgnoreOrder(a, b []string) bool { - if a != nil && b != nil { - sort.Strings(a) - sort.Strings(b) - } - return stringSliceEqual(a, b) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/progress.go b/vendor/github.com/google/go-containerregistry/pkg/v1/progress.go deleted file mode 100644 index 844f04d93..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/progress.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2020 Google LLC 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 v1 - -// Update representation of an update of transfer progress. Some functions -// in this module can take a channel to which updates will be sent while a -// transfer is in progress. -// +k8s:deepcopy-gen=false -type Update struct { - Total int64 - Complete int64 - Error error -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/README.md b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/README.md deleted file mode 100644 index c1e81b310..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/README.md +++ /dev/null @@ -1,117 +0,0 @@ -# `remote` - -[![GoDoc](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/remote?status.svg)](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/remote) - -The `remote` package implements a client for accessing a registry, -per the [OCI distribution spec](https://github.com/opencontainers/distribution-spec/blob/master/spec.md). - -It leans heavily on the lower level [`transport`](/pkg/v1/remote/transport) package, which handles the -authentication handshake and structured errors. - -## Usage - -```go -package main - -import ( - "github.com/google/go-containerregistry/pkg/authn" - "github.com/google/go-containerregistry/pkg/name" - "github.com/google/go-containerregistry/pkg/v1/remote" -) - -func main() { - ref, err := name.ParseReference("gcr.io/google-containers/pause") - if err != nil { - panic(err) - } - - img, err := remote.Image(ref, remote.WithAuthFromKeychain(authn.DefaultKeychain)) - if err != nil { - panic(err) - } - - // do stuff with img -} -``` - -## Structure - -

- -

- - -## Background - -There are a lot of confusingly similar terms that come up when talking about images in registries. - -### Anatomy of an image - -In general... - -* A tag refers to an image manifest. -* An image manifest references a config file and an orderered list of _compressed_ layers by sha256 digest. -* A config file references an ordered list of _uncompressed_ layers by sha256 digest and contains runtime configuration. -* The sha256 digest of the config file is the [image id](https://github.com/opencontainers/image-spec/blob/master/config.md#imageid) for the image. - -For example, an image with two layers would look something like this: - -![image anatomy](/images/image-anatomy.dot.svg) - -### Anatomy of an index - -In the normal case, an [index](https://github.com/opencontainers/image-spec/blob/master/image-index.md) is used to represent a multi-platform image. -This was the original use case for a [manifest -list](https://docs.docker.com/registry/spec/manifest-v2-2/#manifest-list). - -![image index anatomy](/images/index-anatomy.dot.svg) - -It is possible for an index to reference another index, per the OCI -[image-spec](https://github.com/opencontainers/image-spec/blob/master/media-types.md#compatibility-matrix). -In theory, both an image and image index can reference arbitrary things via -[descriptors](https://github.com/opencontainers/image-spec/blob/master/descriptor.md), -e.g. see the [image layout -example](https://github.com/opencontainers/image-spec/blob/master/image-layout.md#index-example), -which references an application/xml file from an image index. - -That could look something like this: - -![strange image index anatomy](/images/index-anatomy-strange.dot.svg) - -Using a recursive index like this might not be possible with all registries, -but this flexibility allows for some interesting applications, e.g. the -[OCI Artifacts](https://github.com/opencontainers/artifacts) effort. - -### Anatomy of an image upload - -The structure of an image requires a delicate ordering when uploading an image to a registry. -Below is a (slightly simplified) figure that describes how an image is prepared for upload -to a registry and how the data flows between various artifacts: - -![upload](/images/upload.dot.svg) - -Note that: - -* A config file references the uncompressed layer contents by sha256. -* A manifest references the compressed layer contents by sha256 and the size of the layer. -* A manifest references the config file contents by sha256 and the size of the file. - -It follows that during an upload, we need to upload layers before the config file, -and we need to upload the config file before the manifest. - -Sometimes, we know all of this information ahead of time, (e.g. when copying from remote.Image), -so the ordering is less important. - -In other cases, e.g. when using a [`stream.Layer`](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/stream#Layer), -we can't compute anything until we have already uploaded the layer, so we need to be careful about ordering. - -## Caveats - -### schema 1 - -This package does not support schema 1 images, see [`#377`](https://github.com/google/go-containerregistry/issues/377), -however, it's possible to do _something_ useful with them via [`remote.Get`](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/remote#Get), -which doesn't try to interpret what is returned by the registry. - -[`crane.Copy`](https://godoc.org/github.com/google/go-containerregistry/pkg/crane#Copy) takes advantage of this to implement support for copying schema 1 images, -see [here](https://github.com/google/go-containerregistry/blob/main/pkg/internal/legacy/copy.go). diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/catalog.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/catalog.go deleted file mode 100644 index a0281b9fd..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/catalog.go +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright 2019 Google LLC 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 remote - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - - "github.com/google/go-containerregistry/pkg/name" - "github.com/google/go-containerregistry/pkg/v1/remote/transport" -) - -type Catalogs struct { - Repos []string `json:"repositories"` - Next string `json:"next,omitempty"` -} - -// CatalogPage calls /_catalog, returning the list of repositories on the registry. -func CatalogPage(target name.Registry, last string, n int, options ...Option) ([]string, error) { - o, err := makeOptions(options...) - if err != nil { - return nil, err - } - - f, err := newPuller(o).fetcher(o.context, target) - if err != nil { - return nil, err - } - - uri := url.URL{ - Scheme: target.Scheme(), - Host: target.RegistryStr(), - Path: "/v2/_catalog", - RawQuery: fmt.Sprintf("last=%s&n=%d", url.QueryEscape(last), n), - } - - req, err := http.NewRequest(http.MethodGet, uri.String(), nil) - if err != nil { - return nil, err - } - resp, err := f.client.Do(req.WithContext(o.context)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if err := transport.CheckError(resp, http.StatusOK); err != nil { - return nil, err - } - - var parsed Catalogs - if err := json.NewDecoder(resp.Body).Decode(&parsed); err != nil { - return nil, err - } - - return parsed.Repos, nil -} - -// Catalog calls /_catalog, returning the list of repositories on the registry. -func Catalog(ctx context.Context, target name.Registry, options ...Option) ([]string, error) { - o, err := makeOptions(options...) - if err != nil { - return nil, err - } - - // WithContext overrides the ctx passed directly. - if o.context != context.Background() { - ctx = o.context - } - - return newPuller(o).catalog(ctx, target, o.pageSize) -} - -func (f *fetcher) catalogPage(ctx context.Context, reg name.Registry, next string, pageSize int) (*Catalogs, error) { - if next == "" { - uri := &url.URL{ - Scheme: reg.Scheme(), - Host: reg.RegistryStr(), - Path: "/v2/_catalog", - } - if pageSize > 0 { - uri.RawQuery = fmt.Sprintf("n=%d", pageSize) - } - next = uri.String() - } - - req, err := http.NewRequestWithContext(ctx, "GET", next, nil) - if err != nil { - return nil, err - } - - resp, err := f.client.Do(req) - if err != nil { - return nil, err - } - - if err := transport.CheckError(resp, http.StatusOK); err != nil { - return nil, err - } - - parsed := Catalogs{} - if err := json.NewDecoder(resp.Body).Decode(&parsed); err != nil { - return nil, err - } - - if err := resp.Body.Close(); err != nil { - return nil, err - } - - uri, err := getNextPageURL(resp) - if err != nil { - return nil, err - } - - if uri != nil { - parsed.Next = uri.String() - } - - return &parsed, nil -} - -type Catalogger struct { - f *fetcher - reg name.Registry - pageSize int - - page *Catalogs - err error - - needMore bool -} - -func (l *Catalogger) Next(ctx context.Context) (*Catalogs, error) { - if l.needMore { - l.page, l.err = l.f.catalogPage(ctx, l.reg, l.page.Next, l.pageSize) - } else { - l.needMore = true - } - return l.page, l.err -} - -func (l *Catalogger) HasNext() bool { - return l.page != nil && (!l.needMore || l.page.Next != "") -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/check.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/check.go deleted file mode 100644 index b4395c239..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/check.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2019 Google LLC 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 remote - -import ( - "context" - "fmt" - "net/http" - - "github.com/google/go-containerregistry/pkg/authn" - "github.com/google/go-containerregistry/pkg/name" - "github.com/google/go-containerregistry/pkg/v1/remote/transport" -) - -// CheckPushPermission returns an error if the given keychain cannot authorize -// a push operation to the given ref. -// -// This can be useful to check whether the caller has permission to push an -// image before doing work to construct the image. -// -// TODO(#412): Remove the need for this method. -func CheckPushPermission(ref name.Reference, kc authn.Keychain, t http.RoundTripper) error { - auth, err := kc.Resolve(ref.Context().Registry) - if err != nil { - return fmt.Errorf("resolving authorization for %v failed: %w", ref.Context().Registry, err) - } - - scopes := []string{ref.Scope(transport.PushScope)} - tr, err := transport.NewWithContext(context.TODO(), ref.Context().Registry, auth, t, scopes) - if err != nil { - return fmt.Errorf("creating push check transport for %v failed: %w", ref.Context().Registry, err) - } - // TODO(jasonhall): Against GCR, just doing the token handshake is - // enough, but this doesn't extend to Dockerhub - // (https://github.com/docker/hub-feedback/issues/1771), so we actually - // need to initiate an upload to tell whether the credentials can - // authorize a push. Figure out how to return early here when we can, - // to avoid a roundtrip for spec-compliant registries. - w := writer{ - repo: ref.Context(), - client: &http.Client{Transport: tr}, - } - loc, _, err := w.initiateUpload(context.Background(), "", "", "") - if loc != "" { - // Since we're only initiating the upload to check whether we - // can, we should attempt to cancel it, in case initiating - // reserves some resources on the server. We shouldn't wait for - // cancelling to complete, and we don't care if it fails. - go w.cancelUpload(loc) - } - return err -} - -func (w *writer) cancelUpload(loc string) { - req, err := http.NewRequest(http.MethodDelete, loc, nil) - if err != nil { - return - } - _, _ = w.client.Do(req) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/delete.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/delete.go deleted file mode 100644 index 36e1d0816..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/delete.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2018 Google LLC 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 remote - -import ( - "github.com/google/go-containerregistry/pkg/name" -) - -// Delete removes the specified image reference from the remote registry. -func Delete(ref name.Reference, options ...Option) error { - o, err := makeOptions(options...) - if err != nil { - return err - } - return newPusher(o).Delete(o.context, ref) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/descriptor.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/descriptor.go deleted file mode 100644 index fafe910e9..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/descriptor.go +++ /dev/null @@ -1,198 +0,0 @@ -// Copyright 2018 Google LLC 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 remote - -import ( - "context" - "errors" - "fmt" - - "github.com/google/go-containerregistry/pkg/logs" - "github.com/google/go-containerregistry/pkg/name" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/partial" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -var allManifestMediaTypes = append(append([]types.MediaType{ - types.DockerManifestSchema1, - types.DockerManifestSchema1Signed, -}, acceptableImageMediaTypes...), acceptableIndexMediaTypes...) - -// ErrSchema1 indicates that we received a schema1 manifest from the registry. -// This library doesn't have plans to support this legacy image format: -// https://github.com/google/go-containerregistry/issues/377 -var ErrSchema1 = errors.New("see https://github.com/google/go-containerregistry/issues/377") - -// newErrSchema1 returns an ErrSchema1 with the unexpected MediaType. -func newErrSchema1(schema types.MediaType) error { - return fmt.Errorf("unsupported MediaType: %q, %w", schema, ErrSchema1) -} - -// Descriptor provides access to metadata about remote artifact and accessors -// for efficiently converting it into a v1.Image or v1.ImageIndex. -type Descriptor struct { - fetcher fetcher - v1.Descriptor - - ref name.Reference - Manifest []byte - ctx context.Context - - // So we can share this implementation with Image. - platform v1.Platform -} - -func (d *Descriptor) toDesc() v1.Descriptor { - return d.Descriptor -} - -// RawManifest exists to satisfy the Taggable interface. -func (d *Descriptor) RawManifest() ([]byte, error) { - return d.Manifest, nil -} - -// Get returns a remote.Descriptor for the given reference. The response from -// the registry is left un-interpreted, for the most part. This is useful for -// querying what kind of artifact a reference represents. -// -// See Head if you don't need the response body. -func Get(ref name.Reference, options ...Option) (*Descriptor, error) { - return get(ref, allManifestMediaTypes, options...) -} - -// Head returns a v1.Descriptor for the given reference by issuing a HEAD -// request. -// -// Note that the server response will not have a body, so any errors encountered -// should be retried with Get to get more details. -func Head(ref name.Reference, options ...Option) (*v1.Descriptor, error) { - o, err := makeOptions(options...) - if err != nil { - return nil, err - } - - return newPuller(o).Head(o.context, ref) -} - -// Handle options and fetch the manifest with the acceptable MediaTypes in the -// Accept header. -func get(ref name.Reference, acceptable []types.MediaType, options ...Option) (*Descriptor, error) { - o, err := makeOptions(options...) - if err != nil { - return nil, err - } - return newPuller(o).get(o.context, ref, acceptable, o.platform) -} - -// Image converts the Descriptor into a v1.Image. -// -// If the fetched artifact is already an image, it will just return it. -// -// If the fetched artifact is an index, it will attempt to resolve the index to -// a child image with the appropriate platform. -// -// See WithPlatform to set the desired platform. -func (d *Descriptor) Image() (v1.Image, error) { - switch d.MediaType { - case types.DockerManifestSchema1, types.DockerManifestSchema1Signed: - // We don't care to support schema 1 images: - // https://github.com/google/go-containerregistry/issues/377 - return nil, newErrSchema1(d.MediaType) - case types.OCIImageIndex, types.DockerManifestList: - // We want an image but the registry has an index, resolve it to an image. - return d.remoteIndex().imageByPlatform(d.platform) - case types.OCIManifestSchema1, types.DockerManifestSchema2: - // These are expected. Enumerated here to allow a default case. - default: - // We could just return an error here, but some registries (e.g. static - // registries) don't set the Content-Type headers correctly, so instead... - logs.Warn.Printf("Unexpected media type for Image(): %s", d.MediaType) - } - - // Wrap the v1.Layers returned by this v1.Image in a hint for downstream - // remote.Write calls to facilitate cross-repo "mounting". - imgCore, err := partial.CompressedToImage(d.remoteImage()) - if err != nil { - return nil, err - } - return &mountableImage{ - Image: imgCore, - Reference: d.ref, - }, nil -} - -// Schema1 converts the Descriptor into a v1.Image for v2 schema 1 media types. -// -// The v1.Image returned by this method does not implement the entire interface because it would be inefficient. -// This exists mostly to make it easier to copy schema 1 images around or look at their filesystems. -// This is separate from Image() to avoid a backward incompatible change for callers expecting ErrSchema1. -func (d *Descriptor) Schema1() (v1.Image, error) { - i := &schema1{ - ref: d.ref, - fetcher: d.fetcher, - ctx: d.ctx, - manifest: d.Manifest, - mediaType: d.MediaType, - descriptor: &d.Descriptor, - } - - return &mountableImage{ - Image: i, - Reference: d.ref, - }, nil -} - -// ImageIndex converts the Descriptor into a v1.ImageIndex. -func (d *Descriptor) ImageIndex() (v1.ImageIndex, error) { - switch d.MediaType { - case types.DockerManifestSchema1, types.DockerManifestSchema1Signed: - // We don't care to support schema 1 images: - // https://github.com/google/go-containerregistry/issues/377 - return nil, newErrSchema1(d.MediaType) - case types.OCIManifestSchema1, types.DockerManifestSchema2: - // We want an index but the registry has an image, nothing we can do. - return nil, fmt.Errorf("unexpected media type for ImageIndex(): %s; call Image() instead", d.MediaType) - case types.OCIImageIndex, types.DockerManifestList: - // These are expected. - default: - // We could just return an error here, but some registries (e.g. static - // registries) don't set the Content-Type headers correctly, so instead... - logs.Warn.Printf("Unexpected media type for ImageIndex(): %s", d.MediaType) - } - return d.remoteIndex(), nil -} - -func (d *Descriptor) remoteImage() *remoteImage { - return &remoteImage{ - ref: d.ref, - ctx: d.ctx, - fetcher: d.fetcher, - manifest: d.Manifest, - mediaType: d.MediaType, - descriptor: &d.Descriptor, - } -} - -func (d *Descriptor) remoteIndex() *remoteIndex { - return &remoteIndex{ - ref: d.ref, - ctx: d.ctx, - fetcher: d.fetcher, - manifest: d.Manifest, - mediaType: d.MediaType, - descriptor: &d.Descriptor, - } -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/doc.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/doc.go deleted file mode 100644 index 846ba07cd..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/doc.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2018 Google LLC 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 remote provides facilities for reading/writing v1.Images from/to -// a remote image registry. -package remote diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/fetcher.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/fetcher.go deleted file mode 100644 index 4e61002be..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/fetcher.go +++ /dev/null @@ -1,317 +0,0 @@ -// Copyright 2023 Google LLC 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 remote - -import ( - "bytes" - "context" - "fmt" - "io" - "net/http" - "net/url" - "strings" - - "github.com/google/go-containerregistry/internal/redact" - "github.com/google/go-containerregistry/internal/verify" - "github.com/google/go-containerregistry/pkg/authn" - "github.com/google/go-containerregistry/pkg/name" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/remote/transport" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -const ( - kib = 1024 - mib = 1024 * kib - manifestLimit = 100 * mib -) - -// fetcher implements methods for reading from a registry. -type fetcher struct { - target resource - client *http.Client -} - -func makeFetcher(ctx context.Context, target resource, o *options) (*fetcher, error) { - auth := o.auth - if o.keychain != nil { - kauth, err := o.keychain.Resolve(target) - if err != nil { - return nil, err - } - auth = kauth - } - - reg, ok := target.(name.Registry) - if !ok { - repo, ok := target.(name.Repository) - if !ok { - return nil, fmt.Errorf("unexpected resource: %T", target) - } - reg = repo.Registry - } - - tr, err := transport.NewWithContext(ctx, reg, auth, o.transport, []string{target.Scope(transport.PullScope)}) - if err != nil { - return nil, err - } - return &fetcher{ - target: target, - client: &http.Client{Transport: tr}, - }, nil -} - -func (f *fetcher) Do(req *http.Request) (*http.Response, error) { - return f.client.Do(req) -} - -type resource interface { - Scheme() string - RegistryStr() string - Scope(string) string - - authn.Resource -} - -// url returns a url.Url for the specified path in the context of this remote image reference. -func (f *fetcher) url(resource, identifier string) url.URL { - u := url.URL{ - Scheme: f.target.Scheme(), - Host: f.target.RegistryStr(), - // Default path if this is not a repository. - Path: "/v2/_catalog", - } - if repo, ok := f.target.(name.Repository); ok { - u.Path = fmt.Sprintf("/v2/%s/%s/%s", repo.RepositoryStr(), resource, identifier) - } - return u -} - -func (f *fetcher) get(ctx context.Context, ref name.Reference, acceptable []types.MediaType, platform v1.Platform) (*Descriptor, error) { - b, desc, err := f.fetchManifest(ctx, ref, acceptable) - if err != nil { - return nil, err - } - return &Descriptor{ - ref: ref, - ctx: ctx, - fetcher: *f, - Manifest: b, - Descriptor: *desc, - platform: platform, - }, nil -} - -func (f *fetcher) fetchManifest(ctx context.Context, ref name.Reference, acceptable []types.MediaType) ([]byte, *v1.Descriptor, error) { - u := f.url("manifests", ref.Identifier()) - req, err := http.NewRequest(http.MethodGet, u.String(), nil) - if err != nil { - return nil, nil, err - } - accept := []string{} - for _, mt := range acceptable { - accept = append(accept, string(mt)) - } - req.Header.Set("Accept", strings.Join(accept, ",")) - - resp, err := f.client.Do(req.WithContext(ctx)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - if err := transport.CheckError(resp, http.StatusOK); err != nil { - return nil, nil, err - } - - manifest, err := io.ReadAll(io.LimitReader(resp.Body, manifestLimit)) - if err != nil { - return nil, nil, err - } - - digest, size, err := v1.SHA256(bytes.NewReader(manifest)) - if err != nil { - return nil, nil, err - } - - mediaType := types.MediaType(resp.Header.Get("Content-Type")) - contentDigest, err := v1.NewHash(resp.Header.Get("Docker-Content-Digest")) - if err == nil && mediaType == types.DockerManifestSchema1Signed { - // If we can parse the digest from the header, and it's a signed schema 1 - // manifest, let's use that for the digest to appease older registries. - digest = contentDigest - } - - // Validate the digest matches what we asked for, if pulling by digest. - if dgst, ok := ref.(name.Digest); ok { - if digest.String() != dgst.DigestStr() { - return nil, nil, fmt.Errorf("manifest digest: %q does not match requested digest: %q for %q", digest, dgst.DigestStr(), ref) - } - } - - var artifactType string - mf, _ := v1.ParseManifest(bytes.NewReader(manifest)) - // Failing to parse as a manifest should just be ignored. - // The manifest might not be valid, and that's okay. - if mf != nil && !mf.Config.MediaType.IsConfig() { - artifactType = string(mf.Config.MediaType) - } - - // Do nothing for tags; I give up. - // - // We'd like to validate that the "Docker-Content-Digest" header matches what is returned by the registry, - // but so many registries implement this incorrectly that it's not worth checking. - // - // For reference: - // https://github.com/GoogleContainerTools/kaniko/issues/298 - - // Return all this info since we have to calculate it anyway. - desc := v1.Descriptor{ - Digest: digest, - Size: size, - MediaType: mediaType, - ArtifactType: artifactType, - } - - return manifest, &desc, nil -} - -func (f *fetcher) headManifest(ctx context.Context, ref name.Reference, acceptable []types.MediaType) (*v1.Descriptor, error) { - u := f.url("manifests", ref.Identifier()) - req, err := http.NewRequest(http.MethodHead, u.String(), nil) - if err != nil { - return nil, err - } - accept := []string{} - for _, mt := range acceptable { - accept = append(accept, string(mt)) - } - req.Header.Set("Accept", strings.Join(accept, ",")) - - resp, err := f.client.Do(req.WithContext(ctx)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if err := transport.CheckError(resp, http.StatusOK); err != nil { - return nil, err - } - - mth := resp.Header.Get("Content-Type") - if mth == "" { - return nil, fmt.Errorf("HEAD %s: response did not include Content-Type header", u.String()) - } - mediaType := types.MediaType(mth) - - size := resp.ContentLength - if size == -1 { - return nil, fmt.Errorf("GET %s: response did not include Content-Length header", u.String()) - } - - dh := resp.Header.Get("Docker-Content-Digest") - if dh == "" { - return nil, fmt.Errorf("HEAD %s: response did not include Docker-Content-Digest header", u.String()) - } - digest, err := v1.NewHash(dh) - if err != nil { - return nil, err - } - - // Validate the digest matches what we asked for, if pulling by digest. - if dgst, ok := ref.(name.Digest); ok { - if digest.String() != dgst.DigestStr() { - return nil, fmt.Errorf("manifest digest: %q does not match requested digest: %q for %q", digest, dgst.DigestStr(), ref) - } - } - - // Return all this info since we have to calculate it anyway. - return &v1.Descriptor{ - Digest: digest, - Size: size, - MediaType: mediaType, - }, nil -} - -func (f *fetcher) fetchBlob(ctx context.Context, size int64, h v1.Hash) (io.ReadCloser, error) { - u := f.url("blobs", h.String()) - req, err := http.NewRequest(http.MethodGet, u.String(), nil) - if err != nil { - return nil, err - } - - resp, err := f.client.Do(req.WithContext(ctx)) - if err != nil { - return nil, redact.Error(err) - } - - if err := transport.CheckError(resp, http.StatusOK); err != nil { - resp.Body.Close() - return nil, err - } - - // Do whatever we can. - // If we have an expected size and Content-Length doesn't match, return an error. - // If we don't have an expected size and we do have a Content-Length, use Content-Length. - if hsize := resp.ContentLength; hsize != -1 { - if size == verify.SizeUnknown { - size = hsize - } else if hsize != size { - return nil, fmt.Errorf("GET %s: Content-Length header %d does not match expected size %d", u.String(), hsize, size) - } - } - - return verify.ReadCloser(resp.Body, size, h) -} - -func (f *fetcher) headBlob(ctx context.Context, h v1.Hash) (*http.Response, error) { - u := f.url("blobs", h.String()) - req, err := http.NewRequest(http.MethodHead, u.String(), nil) - if err != nil { - return nil, err - } - - resp, err := f.client.Do(req.WithContext(ctx)) - if err != nil { - return nil, redact.Error(err) - } - - if err := transport.CheckError(resp, http.StatusOK); err != nil { - resp.Body.Close() - return nil, err - } - - return resp, nil -} - -func (f *fetcher) blobExists(ctx context.Context, h v1.Hash) (bool, error) { - u := f.url("blobs", h.String()) - req, err := http.NewRequest(http.MethodHead, u.String(), nil) - if err != nil { - return false, err - } - - resp, err := f.client.Do(req.WithContext(ctx)) - if err != nil { - return false, redact.Error(err) - } - defer resp.Body.Close() - - if err := transport.CheckError(resp, http.StatusOK, http.StatusNotFound); err != nil { - return false, err - } - - return resp.StatusCode == http.StatusOK, nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/image.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/image.go deleted file mode 100644 index f085967ed..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/image.go +++ /dev/null @@ -1,277 +0,0 @@ -// Copyright 2018 Google LLC 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 remote - -import ( - "bytes" - "context" - "io" - "net/http" - "net/url" - "sync" - - "github.com/google/go-containerregistry/internal/redact" - "github.com/google/go-containerregistry/internal/verify" - "github.com/google/go-containerregistry/pkg/name" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/partial" - "github.com/google/go-containerregistry/pkg/v1/remote/transport" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -var acceptableImageMediaTypes = []types.MediaType{ - types.DockerManifestSchema2, - types.OCIManifestSchema1, -} - -// remoteImage accesses an image from a remote registry -type remoteImage struct { - fetcher fetcher - ref name.Reference - ctx context.Context - manifestLock sync.Mutex // Protects manifest - manifest []byte - configLock sync.Mutex // Protects config - config []byte - mediaType types.MediaType - descriptor *v1.Descriptor -} - -func (r *remoteImage) ArtifactType() (string, error) { - // kind of a hack, but RawManifest does appropriate locking/memoization - // and makes sure r.descriptor is populated. - if _, err := r.RawManifest(); err != nil { - return "", err - } - return r.descriptor.ArtifactType, nil -} - -var _ partial.CompressedImageCore = (*remoteImage)(nil) - -// Image provides access to a remote image reference. -func Image(ref name.Reference, options ...Option) (v1.Image, error) { - desc, err := Get(ref, options...) - if err != nil { - return nil, err - } - - return desc.Image() -} - -func (r *remoteImage) MediaType() (types.MediaType, error) { - if string(r.mediaType) != "" { - return r.mediaType, nil - } - return types.DockerManifestSchema2, nil -} - -func (r *remoteImage) RawManifest() ([]byte, error) { - r.manifestLock.Lock() - defer r.manifestLock.Unlock() - if r.manifest != nil { - return r.manifest, nil - } - - // NOTE(jonjohnsonjr): We should never get here because the public entrypoints - // do type-checking via remote.Descriptor. I've left this here for tests that - // directly instantiate a remoteImage. - manifest, desc, err := r.fetcher.fetchManifest(r.ctx, r.ref, acceptableImageMediaTypes) - if err != nil { - return nil, err - } - - if r.descriptor == nil { - r.descriptor = desc - } - r.mediaType = desc.MediaType - r.manifest = manifest - return r.manifest, nil -} - -func (r *remoteImage) RawConfigFile() ([]byte, error) { - r.configLock.Lock() - defer r.configLock.Unlock() - if r.config != nil { - return r.config, nil - } - - m, err := partial.Manifest(r) - if err != nil { - return nil, err - } - - if m.Config.Data != nil { - if err := verify.Descriptor(m.Config); err != nil { - return nil, err - } - r.config = m.Config.Data - return r.config, nil - } - - body, err := r.fetcher.fetchBlob(r.ctx, m.Config.Size, m.Config.Digest) - if err != nil { - return nil, err - } - defer body.Close() - - r.config, err = io.ReadAll(body) - if err != nil { - return nil, err - } - return r.config, nil -} - -// Descriptor retains the original descriptor from an index manifest. -// See partial.Descriptor. -func (r *remoteImage) Descriptor() (*v1.Descriptor, error) { - // kind of a hack, but RawManifest does appropriate locking/memoization - // and makes sure r.descriptor is populated. - _, err := r.RawManifest() - return r.descriptor, err -} - -func (r *remoteImage) ConfigLayer() (v1.Layer, error) { - if _, err := r.RawManifest(); err != nil { - return nil, err - } - m, err := partial.Manifest(r) - if err != nil { - return nil, err - } - - return partial.CompressedToLayer(&remoteImageLayer{ - ri: r, - ctx: r.ctx, - digest: m.Config.Digest, - }) -} - -// remoteImageLayer implements partial.CompressedLayer -type remoteImageLayer struct { - ri *remoteImage - ctx context.Context - digest v1.Hash -} - -// Digest implements partial.CompressedLayer -func (rl *remoteImageLayer) Digest() (v1.Hash, error) { - return rl.digest, nil -} - -// Compressed implements partial.CompressedLayer -func (rl *remoteImageLayer) Compressed() (io.ReadCloser, error) { - urls := []url.URL{rl.ri.fetcher.url("blobs", rl.digest.String())} - - // Add alternative layer sources from URLs (usually none). - d, err := partial.BlobDescriptor(rl, rl.digest) - if err != nil { - return nil, err - } - - if d.Data != nil { - return verify.ReadCloser(io.NopCloser(bytes.NewReader(d.Data)), d.Size, d.Digest) - } - - // We don't want to log binary layers -- this can break terminals. - ctx := redact.NewContext(rl.ctx, "omitting binary blobs from logs") - - for _, s := range d.URLs { - u, err := url.Parse(s) - if err != nil { - return nil, err - } - urls = append(urls, *u) - } - - // The lastErr for most pulls will be the same (the first error), but for - // foreign layers we'll want to surface the last one, since we try to pull - // from the registry first, which would often fail. - // TODO: Maybe we don't want to try pulling from the registry first? - var lastErr error - for _, u := range urls { - req, err := http.NewRequest(http.MethodGet, u.String(), nil) - if err != nil { - return nil, err - } - - resp, err := rl.ri.fetcher.Do(req.WithContext(ctx)) - if err != nil { - lastErr = err - continue - } - - if err := transport.CheckError(resp, http.StatusOK); err != nil { - resp.Body.Close() - lastErr = err - continue - } - - return verify.ReadCloser(resp.Body, d.Size, rl.digest) - } - - return nil, lastErr -} - -// Manifest implements partial.WithManifest so that we can use partial.BlobSize below. -func (rl *remoteImageLayer) Manifest() (*v1.Manifest, error) { - return partial.Manifest(rl.ri) -} - -// MediaType implements v1.Layer -func (rl *remoteImageLayer) MediaType() (types.MediaType, error) { - bd, err := partial.BlobDescriptor(rl, rl.digest) - if err != nil { - return "", err - } - - return bd.MediaType, nil -} - -// Size implements partial.CompressedLayer -func (rl *remoteImageLayer) Size() (int64, error) { - // Look up the size of this digest in the manifest to avoid a request. - return partial.BlobSize(rl, rl.digest) -} - -// ConfigFile implements partial.WithManifestAndConfigFile so that we can use partial.BlobToDiffID below. -func (rl *remoteImageLayer) ConfigFile() (*v1.ConfigFile, error) { - return partial.ConfigFile(rl.ri) -} - -// DiffID implements partial.WithDiffID so that we don't recompute a DiffID that we already have -// available in our ConfigFile. -func (rl *remoteImageLayer) DiffID() (v1.Hash, error) { - return partial.BlobToDiffID(rl, rl.digest) -} - -// Descriptor retains the original descriptor from an image manifest. -// See partial.Descriptor. -func (rl *remoteImageLayer) Descriptor() (*v1.Descriptor, error) { - return partial.BlobDescriptor(rl, rl.digest) -} - -// See partial.Exists. -func (rl *remoteImageLayer) Exists() (bool, error) { - return rl.ri.fetcher.blobExists(rl.ri.ctx, rl.digest) -} - -// LayerByDigest implements partial.CompressedLayer -func (r *remoteImage) LayerByDigest(h v1.Hash) (partial.CompressedLayer, error) { - return &remoteImageLayer{ - ri: r, - ctx: r.ctx, - digest: h, - }, nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/index.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/index.go deleted file mode 100644 index b80972c80..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/index.go +++ /dev/null @@ -1,287 +0,0 @@ -// Copyright 2018 Google LLC 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 remote - -import ( - "bytes" - "context" - "fmt" - "sync" - - "github.com/google/go-containerregistry/internal/verify" - "github.com/google/go-containerregistry/pkg/name" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/partial" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -var acceptableIndexMediaTypes = []types.MediaType{ - types.DockerManifestList, - types.OCIImageIndex, -} - -// remoteIndex accesses an index from a remote registry -type remoteIndex struct { - fetcher fetcher - ref name.Reference - ctx context.Context - manifestLock sync.Mutex // Protects manifest - manifest []byte - mediaType types.MediaType - descriptor *v1.Descriptor -} - -// Index provides access to a remote index reference. -func Index(ref name.Reference, options ...Option) (v1.ImageIndex, error) { - desc, err := get(ref, acceptableIndexMediaTypes, options...) - if err != nil { - return nil, err - } - - return desc.ImageIndex() -} - -func (r *remoteIndex) MediaType() (types.MediaType, error) { - if string(r.mediaType) != "" { - return r.mediaType, nil - } - return types.DockerManifestList, nil -} - -func (r *remoteIndex) Digest() (v1.Hash, error) { - return partial.Digest(r) -} - -func (r *remoteIndex) Size() (int64, error) { - return partial.Size(r) -} - -func (r *remoteIndex) RawManifest() ([]byte, error) { - r.manifestLock.Lock() - defer r.manifestLock.Unlock() - if r.manifest != nil { - return r.manifest, nil - } - - // NOTE(jonjohnsonjr): We should never get here because the public entrypoints - // do type-checking via remote.Descriptor. I've left this here for tests that - // directly instantiate a remoteIndex. - manifest, desc, err := r.fetcher.fetchManifest(r.ctx, r.ref, acceptableIndexMediaTypes) - if err != nil { - return nil, err - } - - if r.descriptor == nil { - r.descriptor = desc - } - r.mediaType = desc.MediaType - r.manifest = manifest - return r.manifest, nil -} - -func (r *remoteIndex) IndexManifest() (*v1.IndexManifest, error) { - b, err := r.RawManifest() - if err != nil { - return nil, err - } - return v1.ParseIndexManifest(bytes.NewReader(b)) -} - -func (r *remoteIndex) Image(h v1.Hash) (v1.Image, error) { - desc, err := r.childByHash(h) - if err != nil { - return nil, err - } - - // Descriptor.Image will handle coercing nested indexes into an Image. - return desc.Image() -} - -// Descriptor retains the original descriptor from an index manifest. -// See partial.Descriptor. -func (r *remoteIndex) Descriptor() (*v1.Descriptor, error) { - // kind of a hack, but RawManifest does appropriate locking/memoization - // and makes sure r.descriptor is populated. - _, err := r.RawManifest() - return r.descriptor, err -} - -func (r *remoteIndex) ImageIndex(h v1.Hash) (v1.ImageIndex, error) { - desc, err := r.childByHash(h) - if err != nil { - return nil, err - } - return desc.ImageIndex() -} - -// Workaround for #819. -func (r *remoteIndex) Layer(h v1.Hash) (v1.Layer, error) { - index, err := r.IndexManifest() - if err != nil { - return nil, err - } - for _, childDesc := range index.Manifests { - if h == childDesc.Digest { - l, err := partial.CompressedToLayer(&remoteLayer{ - fetcher: r.fetcher, - ctx: r.ctx, - digest: h, - }) - if err != nil { - return nil, err - } - return &MountableLayer{ - Layer: l, - Reference: r.ref.Context().Digest(h.String()), - }, nil - } - } - return nil, fmt.Errorf("layer not found: %s", h) -} - -func (r *remoteIndex) imageByPlatform(platform v1.Platform) (v1.Image, error) { - desc, err := r.childByPlatform(platform) - if err != nil { - return nil, err - } - - // Descriptor.Image will handle coercing nested indexes into an Image. - return desc.Image() -} - -// This naively matches the first manifest with matching platform attributes. -// -// We should probably use this instead: -// -// github.com/containerd/containerd/platforms -// -// But first we'd need to migrate to: -// -// github.com/opencontainers/image-spec/specs-go/v1 -func (r *remoteIndex) childByPlatform(platform v1.Platform) (*Descriptor, error) { - index, err := r.IndexManifest() - if err != nil { - return nil, err - } - for _, childDesc := range index.Manifests { - // If platform is missing from child descriptor, assume it's amd64/linux. - p := defaultPlatform - if childDesc.Platform != nil { - p = *childDesc.Platform - } - - if matchesPlatform(p, platform) { - return r.childDescriptor(childDesc, platform) - } - } - return nil, fmt.Errorf("no child with platform %+v in index %s", platform, r.ref) -} - -func (r *remoteIndex) childByHash(h v1.Hash) (*Descriptor, error) { - index, err := r.IndexManifest() - if err != nil { - return nil, err - } - for _, childDesc := range index.Manifests { - if h == childDesc.Digest { - return r.childDescriptor(childDesc, defaultPlatform) - } - } - return nil, fmt.Errorf("no child with digest %s in index %s", h, r.ref) -} - -// Convert one of this index's child's v1.Descriptor into a remote.Descriptor, with the given platform option. -func (r *remoteIndex) childDescriptor(child v1.Descriptor, platform v1.Platform) (*Descriptor, error) { - ref := r.ref.Context().Digest(child.Digest.String()) - var ( - manifest []byte - err error - ) - if child.Data != nil { - if err := verify.Descriptor(child); err != nil { - return nil, err - } - manifest = child.Data - } else { - manifest, _, err = r.fetcher.fetchManifest(r.ctx, ref, []types.MediaType{child.MediaType}) - if err != nil { - return nil, err - } - } - - if child.MediaType.IsImage() { - mf, _ := v1.ParseManifest(bytes.NewReader(manifest)) - // Failing to parse as a manifest should just be ignored. - // The manifest might not be valid, and that's okay. - if mf != nil && !mf.Config.MediaType.IsConfig() { - child.ArtifactType = string(mf.Config.MediaType) - } - } - - return &Descriptor{ - ref: ref, - ctx: r.ctx, - fetcher: r.fetcher, - Manifest: manifest, - Descriptor: child, - platform: platform, - }, nil -} - -// matchesPlatform checks if the given platform matches the required platforms. -// The given platform matches the required platform if -// - architecture and OS are identical. -// - OS version and variant are identical if provided. -// - features and OS features of the required platform are subsets of those of the given platform. -func matchesPlatform(given, required v1.Platform) bool { - // Required fields that must be identical. - if given.Architecture != required.Architecture || given.OS != required.OS { - return false - } - - // Optional fields that may be empty, but must be identical if provided. - if required.OSVersion != "" && given.OSVersion != required.OSVersion { - return false - } - if required.Variant != "" && given.Variant != required.Variant { - return false - } - - // Verify required platform's features are a subset of given platform's features. - if !isSubset(given.OSFeatures, required.OSFeatures) { - return false - } - if !isSubset(given.Features, required.Features) { - return false - } - - return true -} - -// isSubset checks if the required array of strings is a subset of the given lst. -func isSubset(lst, required []string) bool { - set := make(map[string]bool) - for _, value := range lst { - set[value] = true - } - - for _, value := range required { - if _, ok := set[value]; !ok { - return false - } - } - - return true -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/layer.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/layer.go deleted file mode 100644 index 39c205950..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/layer.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2019 Google LLC 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 remote - -import ( - "context" - "io" - - "github.com/google/go-containerregistry/internal/redact" - "github.com/google/go-containerregistry/internal/verify" - "github.com/google/go-containerregistry/pkg/name" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -// remoteImagelayer implements partial.CompressedLayer -type remoteLayer struct { - ctx context.Context - fetcher fetcher - digest v1.Hash -} - -// Compressed implements partial.CompressedLayer -func (rl *remoteLayer) Compressed() (io.ReadCloser, error) { - // We don't want to log binary layers -- this can break terminals. - ctx := redact.NewContext(rl.ctx, "omitting binary blobs from logs") - return rl.fetcher.fetchBlob(ctx, verify.SizeUnknown, rl.digest) -} - -// Compressed implements partial.CompressedLayer -func (rl *remoteLayer) Size() (int64, error) { - resp, err := rl.fetcher.headBlob(rl.ctx, rl.digest) - if err != nil { - return -1, err - } - defer resp.Body.Close() - return resp.ContentLength, nil -} - -// Digest implements partial.CompressedLayer -func (rl *remoteLayer) Digest() (v1.Hash, error) { - return rl.digest, nil -} - -// MediaType implements v1.Layer -func (rl *remoteLayer) MediaType() (types.MediaType, error) { - return types.DockerLayer, nil -} - -// See partial.Exists. -func (rl *remoteLayer) Exists() (bool, error) { - return rl.fetcher.blobExists(rl.ctx, rl.digest) -} - -// Layer reads the given blob reference from a registry as a Layer. A blob -// reference here is just a punned name.Digest where the digest portion is the -// digest of the blob to be read and the repository portion is the repo where -// that blob lives. -func Layer(ref name.Digest, options ...Option) (v1.Layer, error) { - o, err := makeOptions(options...) - if err != nil { - return nil, err - } - return newPuller(o).Layer(o.context, ref) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/list.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/list.go deleted file mode 100644 index 910d2a94c..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/list.go +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright 2018 Google LLC 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 remote - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strings" - - "github.com/google/go-containerregistry/pkg/name" - "github.com/google/go-containerregistry/pkg/v1/remote/transport" -) - -// ListWithContext calls List with the given context. -// -// Deprecated: Use List and WithContext. This will be removed in a future release. -func ListWithContext(ctx context.Context, repo name.Repository, options ...Option) ([]string, error) { - return List(repo, append(options, WithContext(ctx))...) -} - -// List calls /tags/list for the given repository, returning the list of tags -// in the "tags" property. -func List(repo name.Repository, options ...Option) ([]string, error) { - o, err := makeOptions(options...) - if err != nil { - return nil, err - } - return newPuller(o).List(o.context, repo) -} - -type Tags struct { - Name string `json:"name"` - Tags []string `json:"tags"` - Next string `json:"next,omitempty"` -} - -func (f *fetcher) listPage(ctx context.Context, repo name.Repository, next string, pageSize int) (*Tags, error) { - if next == "" { - uri := &url.URL{ - Scheme: repo.Scheme(), - Host: repo.RegistryStr(), - Path: fmt.Sprintf("/v2/%s/tags/list", repo.RepositoryStr()), - } - if pageSize > 0 { - uri.RawQuery = fmt.Sprintf("n=%d", pageSize) - } - next = uri.String() - } - - req, err := http.NewRequestWithContext(ctx, "GET", next, nil) - if err != nil { - return nil, err - } - - resp, err := f.client.Do(req) - if err != nil { - return nil, err - } - - if err := transport.CheckError(resp, http.StatusOK); err != nil { - return nil, err - } - - parsed := Tags{} - if err := json.NewDecoder(resp.Body).Decode(&parsed); err != nil { - return nil, err - } - - if err := resp.Body.Close(); err != nil { - return nil, err - } - - uri, err := getNextPageURL(resp) - if err != nil { - return nil, err - } - - if uri != nil { - parsed.Next = uri.String() - } - - return &parsed, nil -} - -// getNextPageURL checks if there is a Link header in a http.Response which -// contains a link to the next page. If yes it returns the url.URL of the next -// page otherwise it returns nil. -func getNextPageURL(resp *http.Response) (*url.URL, error) { - link := resp.Header.Get("Link") - if link == "" { - return nil, nil - } - - if link[0] != '<' { - return nil, fmt.Errorf("failed to parse link header: missing '<' in: %s", link) - } - - end := strings.Index(link, ">") - if end == -1 { - return nil, fmt.Errorf("failed to parse link header: missing '>' in: %s", link) - } - link = link[1:end] - - linkURL, err := url.Parse(link) - if err != nil { - return nil, err - } - if resp.Request == nil || resp.Request.URL == nil { - return nil, nil - } - linkURL = resp.Request.URL.ResolveReference(linkURL) - return linkURL, nil -} - -type Lister struct { - f *fetcher - repo name.Repository - pageSize int - - page *Tags - err error - - needMore bool -} - -func (l *Lister) Next(ctx context.Context) (*Tags, error) { - if l.needMore { - l.page, l.err = l.f.listPage(ctx, l.repo, l.page.Next, l.pageSize) - } else { - l.needMore = true - } - return l.page, l.err -} - -func (l *Lister) HasNext() bool { - return l.page != nil && (!l.needMore || l.page.Next != "") -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/mount.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/mount.go deleted file mode 100644 index 36d088567..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/mount.go +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2018 Google LLC 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 remote - -import ( - "github.com/google/go-containerregistry/pkg/name" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/partial" -) - -// MountableLayer wraps a v1.Layer in a shim that enables the layer to be -// "mounted" when published to another registry. -type MountableLayer struct { - v1.Layer - - Reference name.Reference -} - -// Descriptor retains the original descriptor from an image manifest. -// See partial.Descriptor. -func (ml *MountableLayer) Descriptor() (*v1.Descriptor, error) { - return partial.Descriptor(ml.Layer) -} - -// Exists is a hack. See partial.Exists. -func (ml *MountableLayer) Exists() (bool, error) { - return partial.Exists(ml.Layer) -} - -// mountableImage wraps the v1.Layer references returned by the embedded v1.Image -// in MountableLayer's so that remote.Write might attempt to mount them from their -// source repository. -type mountableImage struct { - v1.Image - - Reference name.Reference -} - -// Layers implements v1.Image -func (mi *mountableImage) Layers() ([]v1.Layer, error) { - ls, err := mi.Image.Layers() - if err != nil { - return nil, err - } - mls := make([]v1.Layer, 0, len(ls)) - for _, l := range ls { - mls = append(mls, &MountableLayer{ - Layer: l, - Reference: mi.Reference, - }) - } - return mls, nil -} - -// LayerByDigest implements v1.Image -func (mi *mountableImage) LayerByDigest(d v1.Hash) (v1.Layer, error) { - l, err := mi.Image.LayerByDigest(d) - if err != nil { - return nil, err - } - return &MountableLayer{ - Layer: l, - Reference: mi.Reference, - }, nil -} - -// LayerByDiffID implements v1.Image -func (mi *mountableImage) LayerByDiffID(d v1.Hash) (v1.Layer, error) { - l, err := mi.Image.LayerByDiffID(d) - if err != nil { - return nil, err - } - return &MountableLayer{ - Layer: l, - Reference: mi.Reference, - }, nil -} - -// Descriptor retains the original descriptor from an index manifest. -// See partial.Descriptor. -func (mi *mountableImage) Descriptor() (*v1.Descriptor, error) { - return partial.Descriptor(mi.Image) -} - -// ConfigLayer retains the original reference so that it can be mounted. -// See partial.ConfigLayer. -func (mi *mountableImage) ConfigLayer() (v1.Layer, error) { - l, err := partial.ConfigLayer(mi.Image) - if err != nil { - return nil, err - } - return &MountableLayer{ - Layer: l, - Reference: mi.Reference, - }, nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/multi_write.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/multi_write.go deleted file mode 100644 index a6705de89..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/multi_write.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2020 Google LLC 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 remote - -import ( - "github.com/google/go-containerregistry/pkg/name" - "golang.org/x/sync/errgroup" -) - -// MultiWrite writes the given Images or ImageIndexes to the given refs, as -// efficiently as possible, by deduping shared layer blobs while uploading them -// in parallel. -func MultiWrite(todo map[name.Reference]Taggable, options ...Option) (rerr error) { - o, err := makeOptions(options...) - if err != nil { - return err - } - if o.progress != nil { - defer func() { o.progress.Close(rerr) }() - } - p := newPusher(o) - - g, ctx := errgroup.WithContext(o.context) - g.SetLimit(o.jobs) - - for ref, t := range todo { - ref, t := ref, t - g.Go(func() error { - return p.Push(ctx, ref, t) - }) - } - - return g.Wait() -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/options.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/options.go deleted file mode 100644 index 99a2bb2eb..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/options.go +++ /dev/null @@ -1,349 +0,0 @@ -// Copyright 2018 Google LLC 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 remote - -import ( - "context" - "errors" - "io" - "net" - "net/http" - "syscall" - "time" - - "github.com/google/go-containerregistry/internal/retry" - "github.com/google/go-containerregistry/pkg/authn" - "github.com/google/go-containerregistry/pkg/logs" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/remote/transport" -) - -// Option is a functional option for remote operations. -type Option func(*options) error - -type options struct { - auth authn.Authenticator - keychain authn.Keychain - transport http.RoundTripper - context context.Context - jobs int - userAgent string - allowNondistributableArtifacts bool - progress *progress - retryBackoff Backoff - retryPredicate retry.Predicate - retryStatusCodes []int - - // Only these options can overwrite Reuse()d options. - platform v1.Platform - pageSize int - filter map[string]string - - // Set by Reuse, we currently store one or the other. - puller *Puller - pusher *Pusher -} - -var defaultPlatform = v1.Platform{ - Architecture: "amd64", - OS: "linux", -} - -// Backoff is an alias of retry.Backoff to expose this configuration option to consumers of this lib -type Backoff = retry.Backoff - -var defaultRetryPredicate retry.Predicate = func(err error) bool { - // Various failure modes here, as we're often reading from and writing to - // the network. - if retry.IsTemporary(err) || errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, io.EOF) || errors.Is(err, syscall.EPIPE) || errors.Is(err, syscall.ECONNRESET) || errors.Is(err, net.ErrClosed) { - logs.Warn.Printf("retrying %v", err) - return true - } - return false -} - -// Try this three times, waiting 1s after first failure, 3s after second. -var defaultRetryBackoff = Backoff{ - Duration: 1.0 * time.Second, - Factor: 3.0, - Jitter: 0.1, - Steps: 3, -} - -// Useful for tests -var fastBackoff = Backoff{ - Duration: 1.0 * time.Millisecond, - Factor: 3.0, - Jitter: 0.1, - Steps: 3, -} - -var defaultRetryStatusCodes = []int{ - http.StatusRequestTimeout, - http.StatusInternalServerError, - http.StatusBadGateway, - http.StatusServiceUnavailable, - http.StatusGatewayTimeout, - 499, // nginx-specific, client closed request - 522, // Cloudflare-specific, connection timeout -} - -const ( - defaultJobs = 4 - - // ECR returns an error if n > 1000: - // https://github.com/google/go-containerregistry/issues/1091 - defaultPageSize = 1000 -) - -// DefaultTransport is based on http.DefaultTransport with modifications -// documented inline below. -var DefaultTransport http.RoundTripper = &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - }).DialContext, - ForceAttemptHTTP2: true, - MaxIdleConns: 100, - IdleConnTimeout: 90 * time.Second, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - // We usually are dealing with 2 hosts (at most), split MaxIdleConns between them. - MaxIdleConnsPerHost: 50, -} - -func makeOptions(opts ...Option) (*options, error) { - o := &options{ - transport: DefaultTransport, - platform: defaultPlatform, - context: context.Background(), - jobs: defaultJobs, - pageSize: defaultPageSize, - retryPredicate: defaultRetryPredicate, - retryBackoff: defaultRetryBackoff, - retryStatusCodes: defaultRetryStatusCodes, - } - - for _, option := range opts { - if err := option(o); err != nil { - return nil, err - } - } - - switch { - case o.auth != nil && o.keychain != nil: - // It is a better experience to explicitly tell a caller their auth is misconfigured - // than potentially fail silently when the correct auth is overridden by option misuse. - return nil, errors.New("provide an option for either authn.Authenticator or authn.Keychain, not both") - case o.auth == nil: - o.auth = authn.Anonymous - } - - // transport.Wrapper is a signal that consumers are opt-ing into providing their own transport without any additional wrapping. - // This is to allow consumers full control over the transports logic, such as providing retry logic. - if _, ok := o.transport.(*transport.Wrapper); !ok { - // Wrap the transport in something that logs requests and responses. - // It's expensive to generate the dumps, so skip it if we're writing - // to nothing. - if logs.Enabled(logs.Debug) { - o.transport = transport.NewLogger(o.transport) - } - - // Wrap the transport in something that can retry network flakes. - o.transport = transport.NewRetry(o.transport, transport.WithRetryPredicate(defaultRetryPredicate), transport.WithRetryStatusCodes(o.retryStatusCodes...)) - - // Wrap this last to prevent transport.New from double-wrapping. - if o.userAgent != "" { - o.transport = transport.NewUserAgent(o.transport, o.userAgent) - } - } - - return o, nil -} - -// WithTransport is a functional option for overriding the default transport -// for remote operations. -// If transport.Wrapper is provided, this signals that the consumer does *not* want any further wrapping to occur. -// i.e. logging, retry and useragent -// -// The default transport is DefaultTransport. -func WithTransport(t http.RoundTripper) Option { - return func(o *options) error { - o.transport = t - return nil - } -} - -// WithAuth is a functional option for overriding the default authenticator -// for remote operations. -// It is an error to use both WithAuth and WithAuthFromKeychain in the same Option set. -// -// The default authenticator is authn.Anonymous. -func WithAuth(auth authn.Authenticator) Option { - return func(o *options) error { - o.auth = auth - return nil - } -} - -// WithAuthFromKeychain is a functional option for overriding the default -// authenticator for remote operations, using an authn.Keychain to find -// credentials. -// It is an error to use both WithAuth and WithAuthFromKeychain in the same Option set. -// -// The default authenticator is authn.Anonymous. -func WithAuthFromKeychain(keys authn.Keychain) Option { - return func(o *options) error { - o.keychain = keys - return nil - } -} - -// WithPlatform is a functional option for overriding the default platform -// that Image and Descriptor.Image use for resolving an index to an image. -// -// The default platform is amd64/linux. -func WithPlatform(p v1.Platform) Option { - return func(o *options) error { - o.platform = p - return nil - } -} - -// WithContext is a functional option for setting the context in http requests -// performed by a given function. Note that this context is used for _all_ -// http requests, not just the initial volley. E.g., for remote.Image, the -// context will be set on http requests generated by subsequent calls to -// RawConfigFile() and even methods on layers returned by Layers(). -// -// The default context is context.Background(). -func WithContext(ctx context.Context) Option { - return func(o *options) error { - o.context = ctx - return nil - } -} - -// WithJobs is a functional option for setting the parallelism of remote -// operations performed by a given function. Note that not all remote -// operations support parallelism. -// -// The default value is 4. -func WithJobs(jobs int) Option { - return func(o *options) error { - if jobs <= 0 { - return errors.New("jobs must be greater than zero") - } - o.jobs = jobs - return nil - } -} - -// WithUserAgent adds the given string to the User-Agent header for any HTTP -// requests. This header will also include "go-containerregistry/${version}". -// -// If you want to completely overwrite the User-Agent header, use WithTransport. -func WithUserAgent(ua string) Option { - return func(o *options) error { - o.userAgent = ua - return nil - } -} - -// WithNondistributable includes non-distributable (foreign) layers -// when writing images, see: -// https://github.com/opencontainers/image-spec/blob/master/layer.md#non-distributable-layers -// -// The default behaviour is to skip these layers -func WithNondistributable(o *options) error { - o.allowNondistributableArtifacts = true - return nil -} - -// WithProgress takes a channel that will receive progress updates as bytes are written. -// -// Sending updates to an unbuffered channel will block writes, so callers -// should provide a buffered channel to avoid potential deadlocks. -func WithProgress(updates chan<- v1.Update) Option { - return func(o *options) error { - o.progress = &progress{updates: updates} - o.progress.lastUpdate = &v1.Update{} - return nil - } -} - -// WithPageSize sets the given size as the value of parameter 'n' in the request. -// -// To omit the `n` parameter entirely, use WithPageSize(0). -// The default value is 1000. -func WithPageSize(size int) Option { - return func(o *options) error { - o.pageSize = size - return nil - } -} - -// WithRetryBackoff sets the httpBackoff for retry HTTP operations. -func WithRetryBackoff(backoff Backoff) Option { - return func(o *options) error { - o.retryBackoff = backoff - return nil - } -} - -// WithRetryPredicate sets the predicate for retry HTTP operations. -func WithRetryPredicate(predicate retry.Predicate) Option { - return func(o *options) error { - o.retryPredicate = predicate - return nil - } -} - -// WithRetryStatusCodes sets which http response codes will be retried. -func WithRetryStatusCodes(codes ...int) Option { - return func(o *options) error { - o.retryStatusCodes = codes - return nil - } -} - -// WithFilter sets the filter querystring for HTTP operations. -func WithFilter(key string, value string) Option { - return func(o *options) error { - if o.filter == nil { - o.filter = map[string]string{} - } - o.filter[key] = value - return nil - } -} - -// Reuse takes a Puller or Pusher and reuses it for remote interactions -// rather than starting from a clean slate. For example, it will reuse token exchanges -// when possible and avoid sending redundant HEAD requests. -// -// Reuse will take precedence over other options passed to most remote functions because -// most options deal with setting up auth and transports, which Reuse intetionally skips. -func Reuse[I *Puller | *Pusher](i I) Option { - return func(o *options) error { - if puller, ok := any(i).(*Puller); ok { - o.puller = puller - } else if pusher, ok := any(i).(*Pusher); ok { - o.pusher = pusher - } - return nil - } -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/progress.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/progress.go deleted file mode 100644 index fe60c8c35..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/progress.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2022 Google LLC 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 remote - -import ( - "io" - "sync" - "sync/atomic" - - v1 "github.com/google/go-containerregistry/pkg/v1" -) - -type progress struct { - sync.Mutex - updates chan<- v1.Update - lastUpdate *v1.Update -} - -func (p *progress) total(delta int64) { - p.Lock() - defer p.Unlock() - atomic.AddInt64(&p.lastUpdate.Total, delta) -} - -func (p *progress) complete(delta int64) { - p.Lock() - defer p.Unlock() - p.updates <- v1.Update{ - Total: p.lastUpdate.Total, - Complete: atomic.AddInt64(&p.lastUpdate.Complete, delta), - } -} - -func (p *progress) err(err error) error { - if err != nil && p.updates != nil { - p.updates <- v1.Update{Error: err} - } - return err -} - -func (p *progress) Close(err error) { - _ = p.err(err) - close(p.updates) -} - -type progressReader struct { - rc io.ReadCloser - - count *int64 // number of bytes this reader has read, to support resetting on retry. - progress *progress -} - -func (r *progressReader) Read(b []byte) (int, error) { - n, err := r.rc.Read(b) - if err != nil { - return n, err - } - atomic.AddInt64(r.count, int64(n)) - // TODO: warn/debug log if sending takes too long, or if sending is blocked while context is canceled. - r.progress.complete(int64(n)) - return n, nil -} - -func (r *progressReader) Close() error { return r.rc.Close() } diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/puller.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/puller.go deleted file mode 100644 index 7da8017ee..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/puller.go +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright 2023 Google LLC 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 remote - -import ( - "context" - "sync" - - "github.com/google/go-containerregistry/pkg/name" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/partial" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -type Puller struct { - o *options - - // map[resource]*reader - readers sync.Map -} - -func NewPuller(options ...Option) (*Puller, error) { - o, err := makeOptions(options...) - if err != nil { - return nil, err - } - - return newPuller(o), nil -} - -func newPuller(o *options) *Puller { - if o.puller != nil { - return o.puller - } - return &Puller{ - o: o, - } -} - -type reader struct { - // in - target resource - o *options - - // f() - once sync.Once - - // out - f *fetcher - err error -} - -// this will run once per reader instance -func (r *reader) init(ctx context.Context) error { - r.once.Do(func() { - r.f, r.err = makeFetcher(ctx, r.target, r.o) - }) - return r.err -} - -func (p *Puller) fetcher(ctx context.Context, target resource) (*fetcher, error) { - v, _ := p.readers.LoadOrStore(target, &reader{ - target: target, - o: p.o, - }) - rr := v.(*reader) - return rr.f, rr.init(ctx) -} - -// Head is like remote.Head, but avoids re-authenticating when possible. -func (p *Puller) Head(ctx context.Context, ref name.Reference) (*v1.Descriptor, error) { - f, err := p.fetcher(ctx, ref.Context()) - if err != nil { - return nil, err - } - - return f.headManifest(ctx, ref, allManifestMediaTypes) -} - -// Get is like remote.Get, but avoids re-authenticating when possible. -func (p *Puller) Get(ctx context.Context, ref name.Reference) (*Descriptor, error) { - return p.get(ctx, ref, allManifestMediaTypes, p.o.platform) -} - -func (p *Puller) get(ctx context.Context, ref name.Reference, acceptable []types.MediaType, platform v1.Platform) (*Descriptor, error) { - f, err := p.fetcher(ctx, ref.Context()) - if err != nil { - return nil, err - } - return f.get(ctx, ref, acceptable, platform) -} - -// Layer is like remote.Layer, but avoids re-authenticating when possible. -func (p *Puller) Layer(ctx context.Context, ref name.Digest) (v1.Layer, error) { - f, err := p.fetcher(ctx, ref.Context()) - if err != nil { - return nil, err - } - - h, err := v1.NewHash(ref.Identifier()) - if err != nil { - return nil, err - } - l, err := partial.CompressedToLayer(&remoteLayer{ - fetcher: *f, - ctx: ctx, - digest: h, - }) - if err != nil { - return nil, err - } - return &MountableLayer{ - Layer: l, - Reference: ref, - }, nil -} - -// List lists tags in a repo and handles pagination, returning the full list of tags. -func (p *Puller) List(ctx context.Context, repo name.Repository) ([]string, error) { - lister, err := p.Lister(ctx, repo) - if err != nil { - return nil, err - } - - tagList := []string{} - for lister.HasNext() { - tags, err := lister.Next(ctx) - if err != nil { - return nil, err - } - tagList = append(tagList, tags.Tags...) - } - - return tagList, nil -} - -// Lister lists tags in a repo and returns a Lister for paginating through the results. -func (p *Puller) Lister(ctx context.Context, repo name.Repository) (*Lister, error) { - return p.lister(ctx, repo, p.o.pageSize) -} - -func (p *Puller) lister(ctx context.Context, repo name.Repository, pageSize int) (*Lister, error) { - f, err := p.fetcher(ctx, repo) - if err != nil { - return nil, err - } - page, err := f.listPage(ctx, repo, "", pageSize) - if err != nil { - return nil, err - } - return &Lister{ - f: f, - repo: repo, - pageSize: pageSize, - page: page, - err: err, - }, nil -} - -// Catalog lists repos in a registry and handles pagination, returning the full list of repos. -func (p *Puller) Catalog(ctx context.Context, reg name.Registry) ([]string, error) { - return p.catalog(ctx, reg, p.o.pageSize) -} - -func (p *Puller) catalog(ctx context.Context, reg name.Registry, pageSize int) ([]string, error) { - catalogger, err := p.catalogger(ctx, reg, pageSize) - if err != nil { - return nil, err - } - repoList := []string{} - for catalogger.HasNext() { - repos, err := catalogger.Next(ctx) - if err != nil { - return nil, err - } - repoList = append(repoList, repos.Repos...) - } - return repoList, nil -} - -// Catalogger lists repos in a registry and returns a Catalogger for paginating through the results. -func (p *Puller) Catalogger(ctx context.Context, reg name.Registry) (*Catalogger, error) { - return p.catalogger(ctx, reg, p.o.pageSize) -} - -func (p *Puller) catalogger(ctx context.Context, reg name.Registry, pageSize int) (*Catalogger, error) { - f, err := p.fetcher(ctx, reg) - if err != nil { - return nil, err - } - page, err := f.catalogPage(ctx, reg, "", pageSize) - if err != nil { - return nil, err - } - return &Catalogger{ - f: f, - reg: reg, - pageSize: pageSize, - page: page, - err: err, - }, nil -} - -func (p *Puller) referrers(ctx context.Context, d name.Digest, filter map[string]string) (v1.ImageIndex, error) { - f, err := p.fetcher(ctx, d.Context()) - if err != nil { - return nil, err - } - return f.fetchReferrers(ctx, filter, d) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/pusher.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/pusher.go deleted file mode 100644 index 1c07bd475..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/pusher.go +++ /dev/null @@ -1,559 +0,0 @@ -// Copyright 2023 Google LLC 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 remote - -import ( - "bytes" - "context" - "errors" - "fmt" - "net/http" - "net/url" - "sync" - - "github.com/google/go-containerregistry/pkg/logs" - "github.com/google/go-containerregistry/pkg/name" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/partial" - "github.com/google/go-containerregistry/pkg/v1/remote/transport" - "github.com/google/go-containerregistry/pkg/v1/stream" - "github.com/google/go-containerregistry/pkg/v1/types" - "golang.org/x/sync/errgroup" -) - -type manifest interface { - Taggable - partial.Describable -} - -// key is either v1.Hash or v1.Layer (for stream.Layer) -type workers struct { - // map[v1.Hash|v1.Layer]*sync.Once - onces sync.Map - - // map[v1.Hash|v1.Layer]error - errors sync.Map -} - -func nop() error { - return nil -} - -func (w *workers) err(digest v1.Hash) error { - v, ok := w.errors.Load(digest) - if !ok || v == nil { - return nil - } - return v.(error) -} - -func (w *workers) Do(digest v1.Hash, f func() error) error { - // We don't care if it was loaded or not because the sync.Once will do it for us. - once, _ := w.onces.LoadOrStore(digest, &sync.Once{}) - - once.(*sync.Once).Do(func() { - w.errors.Store(digest, f()) - }) - - err := w.err(digest) - if err != nil { - // Allow this to be retried by another caller. - w.onces.Delete(digest) - } - return err -} - -func (w *workers) Stream(layer v1.Layer, f func() error) error { - // We don't care if it was loaded or not because the sync.Once will do it for us. - once, _ := w.onces.LoadOrStore(layer, &sync.Once{}) - - once.(*sync.Once).Do(func() { - w.errors.Store(layer, f()) - }) - - v, ok := w.errors.Load(layer) - if !ok || v == nil { - return nil - } - - return v.(error) -} - -type Pusher struct { - o *options - - // map[name.Repository]*repoWriter - writers sync.Map -} - -func NewPusher(options ...Option) (*Pusher, error) { - o, err := makeOptions(options...) - if err != nil { - return nil, err - } - - return newPusher(o), nil -} - -func newPusher(o *options) *Pusher { - if o.pusher != nil { - return o.pusher - } - return &Pusher{ - o: o, - } -} - -func (p *Pusher) writer(ctx context.Context, repo name.Repository, o *options) (*repoWriter, error) { - v, _ := p.writers.LoadOrStore(repo, &repoWriter{ - repo: repo, - o: o, - }) - rw := v.(*repoWriter) - return rw, rw.init(ctx) -} - -func (p *Pusher) Push(ctx context.Context, ref name.Reference, t Taggable) error { - w, err := p.writer(ctx, ref.Context(), p.o) - if err != nil { - return err - } - return w.writeManifest(ctx, ref, t) -} - -func (p *Pusher) Upload(ctx context.Context, repo name.Repository, l v1.Layer) error { - w, err := p.writer(ctx, repo, p.o) - if err != nil { - return err - } - return w.writeLayer(ctx, l) -} - -func (p *Pusher) Delete(ctx context.Context, ref name.Reference) error { - w, err := p.writer(ctx, ref.Context(), p.o) - if err != nil { - return err - } - - u := url.URL{ - Scheme: ref.Context().Registry.Scheme(), - Host: ref.Context().RegistryStr(), - Path: fmt.Sprintf("/v2/%s/manifests/%s", ref.Context().RepositoryStr(), ref.Identifier()), - } - - req, err := http.NewRequest(http.MethodDelete, u.String(), nil) - if err != nil { - return err - } - - resp, err := w.w.client.Do(req.WithContext(ctx)) - if err != nil { - return err - } - defer resp.Body.Close() - - return transport.CheckError(resp, http.StatusOK, http.StatusAccepted) - - // TODO(jason): If the manifest had a `subject`, and if the registry - // doesn't support Referrers, update the index pointed to by the - // subject's fallback tag to remove the descriptor for this manifest. -} - -type repoWriter struct { - repo name.Repository - o *options - once sync.Once - - w *writer - err error - - work *workers -} - -// this will run once per repoWriter instance -func (rw *repoWriter) init(ctx context.Context) error { - rw.once.Do(func() { - rw.work = &workers{} - rw.w, rw.err = makeWriter(ctx, rw.repo, nil, rw.o) - }) - return rw.err -} - -func (rw *repoWriter) writeDeps(ctx context.Context, m manifest) error { - if img, ok := m.(v1.Image); ok { - return rw.writeLayers(ctx, img) - } - - if idx, ok := m.(v1.ImageIndex); ok { - return rw.writeChildren(ctx, idx) - } - - // This has no deps, not an error (e.g. something you want to just PUT). - return nil -} - -type describable struct { - desc v1.Descriptor -} - -func (d describable) Digest() (v1.Hash, error) { - return d.desc.Digest, nil -} - -func (d describable) Size() (int64, error) { - return d.desc.Size, nil -} - -func (d describable) MediaType() (types.MediaType, error) { - return d.desc.MediaType, nil -} - -type tagManifest struct { - Taggable - partial.Describable -} - -func taggableToManifest(t Taggable) (manifest, error) { - if m, ok := t.(manifest); ok { - return m, nil - } - - if d, ok := t.(*Descriptor); ok { - if d.MediaType.IsIndex() { - return d.ImageIndex() - } - - if d.MediaType.IsImage() { - return d.Image() - } - - if d.MediaType.IsSchema1() { - return d.Schema1() - } - - return tagManifest{t, describable{d.toDesc()}}, nil - } - - desc := v1.Descriptor{ - // A reasonable default if Taggable doesn't implement MediaType. - MediaType: types.DockerManifestSchema2, - } - - b, err := t.RawManifest() - if err != nil { - return nil, err - } - - if wmt, ok := t.(withMediaType); ok { - desc.MediaType, err = wmt.MediaType() - if err != nil { - return nil, err - } - } - - desc.Digest, desc.Size, err = v1.SHA256(bytes.NewReader(b)) - if err != nil { - return nil, err - } - - return tagManifest{t, describable{desc}}, nil -} - -func (rw *repoWriter) writeManifest(ctx context.Context, ref name.Reference, t Taggable) error { - m, err := taggableToManifest(t) - if err != nil { - return err - } - - needDeps := true - - digest, err := m.Digest() - if errors.Is(err, stream.ErrNotComputed) { - if err := rw.writeDeps(ctx, m); err != nil { - return err - } - - needDeps = false - - digest, err = m.Digest() - if err != nil { - return err - } - } else if err != nil { - return err - } - - // This may be a lazy child where we have no ref until digest is computed. - if ref == nil { - ref = rw.repo.Digest(digest.String()) - } - - // For tags, we want to do this check outside of our Work.Do closure because - // we don't want to dedupe based on the manifest digest. - _, byTag := ref.(name.Tag) - if byTag { - if exists, err := rw.manifestExists(ctx, ref, t); err != nil { - return err - } else if exists { - return nil - } - } - - // The following work.Do will get deduped by digest, so it won't happen unless - // this tag happens to be the first commitManifest to run for that digest. - needPut := byTag - - if err := rw.work.Do(digest, func() error { - if !byTag { - if exists, err := rw.manifestExists(ctx, ref, t); err != nil { - return err - } else if exists { - return nil - } - } - - if needDeps { - if err := rw.writeDeps(ctx, m); err != nil { - return err - } - } - - needPut = false - return rw.commitManifest(ctx, ref, m) - }); err != nil { - return err - } - - if !needPut { - return nil - } - - // Only runs for tags that got deduped by digest. - return rw.commitManifest(ctx, ref, m) -} - -func (rw *repoWriter) writeChildren(ctx context.Context, idx v1.ImageIndex) error { - children, err := partial.Manifests(idx) - if err != nil { - return err - } - - g, ctx := errgroup.WithContext(ctx) - g.SetLimit(rw.o.jobs) - - for _, child := range children { - child := child - if err := rw.writeChild(ctx, child, g); err != nil { - return err - } - } - - return g.Wait() -} - -func (rw *repoWriter) writeChild(ctx context.Context, child partial.Describable, g *errgroup.Group) error { - switch child := child.(type) { - case v1.ImageIndex: - // For recursive index, we want to do a depth-first launching of goroutines - // to avoid deadlocking. - // - // Note that this is rare, so the impact of this should be really small. - return rw.writeManifest(ctx, nil, child) - case v1.Image: - g.Go(func() error { - return rw.writeManifest(ctx, nil, child) - }) - case v1.Layer: - g.Go(func() error { - return rw.writeLayer(ctx, child) - }) - default: - // This can't happen. - return fmt.Errorf("encountered unknown child: %T", child) - } - return nil -} - -// TODO: Consider caching some representation of the tags/digests in the destination -// repository as a hint to avoid this optimistic check in cases where we will most -// likely have to do a PUT anyway, e.g. if we are overwriting a tag we just wrote. -func (rw *repoWriter) manifestExists(ctx context.Context, ref name.Reference, t Taggable) (bool, error) { - f := &fetcher{ - target: ref.Context(), - client: rw.w.client, - } - - m, err := taggableToManifest(t) - if err != nil { - return false, err - } - - digest, err := m.Digest() - if err != nil { - // Possibly due to streaming layers. - return false, nil - } - got, err := f.headManifest(ctx, ref, allManifestMediaTypes) - if err != nil { - var terr *transport.Error - if errors.As(err, &terr) { - if terr.StatusCode == http.StatusNotFound { - return false, nil - } - - // We treat a 403 here as non-fatal because this existence check is an optimization and - // some registries will return a 403 instead of a 404 in certain situations. - // E.g. https://jfrog.atlassian.net/browse/RTFACT-13797 - if terr.StatusCode == http.StatusForbidden { - logs.Debug.Printf("manifestExists unexpected 403: %v", err) - return false, nil - } - } - - return false, err - } - - if digest != got.Digest { - // Mark that we saw this digest in the registry so we don't have to check it again. - rw.work.Do(got.Digest, nop) - - return false, nil - } - - if tag, ok := ref.(name.Tag); ok { - logs.Progress.Printf("existing manifest: %s@%s", tag.Identifier(), got.Digest) - } else { - logs.Progress.Print("existing manifest: ", got.Digest) - } - - return true, nil -} - -func (rw *repoWriter) commitManifest(ctx context.Context, ref name.Reference, m manifest) error { - if rw.o.progress != nil { - size, err := m.Size() - if err != nil { - return err - } - rw.o.progress.total(size) - } - - return rw.w.commitManifest(ctx, m, ref) -} - -func (rw *repoWriter) writeLayers(pctx context.Context, img v1.Image) error { - ls, err := img.Layers() - if err != nil { - return err - } - - g, ctx := errgroup.WithContext(pctx) - g.SetLimit(rw.o.jobs) - - for _, l := range ls { - l := l - - g.Go(func() error { - return rw.writeLayer(ctx, l) - }) - } - - mt, err := img.MediaType() - if err != nil { - return err - } - - if mt.IsSchema1() { - return g.Wait() - } - - cl, err := partial.ConfigLayer(img) - if errors.Is(err, stream.ErrNotComputed) { - if err := g.Wait(); err != nil { - return err - } - - cl, err := partial.ConfigLayer(img) - if err != nil { - return err - } - - return rw.writeLayer(pctx, cl) - } else if err != nil { - return err - } - - g.Go(func() error { - return rw.writeLayer(ctx, cl) - }) - - return g.Wait() -} - -func (rw *repoWriter) writeLayer(ctx context.Context, l v1.Layer) error { - // Skip any non-distributable things. - mt, err := l.MediaType() - if err != nil { - return err - } - if !mt.IsDistributable() && !rw.o.allowNondistributableArtifacts { - return nil - } - - digest, err := l.Digest() - if err != nil { - if errors.Is(err, stream.ErrNotComputed) { - return rw.lazyWriteLayer(ctx, l) - } - return err - } - - return rw.work.Do(digest, func() error { - if rw.o.progress != nil { - size, err := l.Size() - if err != nil { - return err - } - rw.o.progress.total(size) - } - return rw.w.uploadOne(ctx, l) - }) -} - -func (rw *repoWriter) lazyWriteLayer(ctx context.Context, l v1.Layer) error { - return rw.work.Stream(l, func() error { - if err := rw.w.uploadOne(ctx, l); err != nil { - return err - } - - // Mark this upload completed. - digest, err := l.Digest() - if err != nil { - return err - } - - rw.work.Do(digest, nop) - - if rw.o.progress != nil { - size, err := l.Size() - if err != nil { - return err - } - rw.o.progress.total(size) - } - - return nil - }) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/referrers.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/referrers.go deleted file mode 100644 index e30ca57ed..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/referrers.go +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2023 Google LLC 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 remote - -import ( - "bytes" - "context" - "errors" - "io" - "net/http" - "strings" - - "github.com/google/go-containerregistry/pkg/name" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/empty" - "github.com/google/go-containerregistry/pkg/v1/mutate" - "github.com/google/go-containerregistry/pkg/v1/remote/transport" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -// Referrers returns a list of descriptors that refer to the given manifest digest. -// -// The subject manifest doesn't have to exist in the registry for there to be descriptors that refer to it. -func Referrers(d name.Digest, options ...Option) (v1.ImageIndex, error) { - o, err := makeOptions(options...) - if err != nil { - return nil, err - } - return newPuller(o).referrers(o.context, d, o.filter) -} - -// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#referrers-tag-schema -func fallbackTag(d name.Digest) name.Tag { - return d.Context().Tag(strings.Replace(d.DigestStr(), ":", "-", 1)) -} - -func (f *fetcher) fetchReferrers(ctx context.Context, filter map[string]string, d name.Digest) (v1.ImageIndex, error) { - // Check the Referrers API endpoint first. - u := f.url("referrers", d.DigestStr()) - req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) - if err != nil { - return nil, err - } - req.Header.Set("Accept", string(types.OCIImageIndex)) - - resp, err := f.client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if err := transport.CheckError(resp, http.StatusOK, http.StatusNotFound, http.StatusBadRequest); err != nil { - return nil, err - } - - var b []byte - if resp.StatusCode == http.StatusOK { - b, err = io.ReadAll(resp.Body) - if err != nil { - return nil, err - } - } else { - // The registry doesn't support the Referrers API endpoint, so we'll use the fallback tag scheme. - b, _, err = f.fetchManifest(ctx, fallbackTag(d), []types.MediaType{types.OCIImageIndex}) - var terr *transport.Error - if errors.As(err, &terr) && terr.StatusCode == http.StatusNotFound { - // Not found just means there are no attachments yet. Start with an empty manifest. - return empty.Index, nil - } else if err != nil { - return nil, err - } - } - - h, sz, err := v1.SHA256(bytes.NewReader(b)) - if err != nil { - return nil, err - } - idx := &remoteIndex{ - fetcher: *f, - ctx: ctx, - manifest: b, - mediaType: types.OCIImageIndex, - descriptor: &v1.Descriptor{ - Digest: h, - MediaType: types.OCIImageIndex, - Size: sz, - }, - } - return filterReferrersResponse(filter, idx), nil -} - -// If filter applied, filter out by artifactType. -// See https://github.com/opencontainers/distribution-spec/blob/main/spec.md#listing-referrers -func filterReferrersResponse(filter map[string]string, in v1.ImageIndex) v1.ImageIndex { - if filter == nil { - return in - } - v, ok := filter["artifactType"] - if !ok { - return in - } - return mutate.RemoveManifests(in, func(desc v1.Descriptor) bool { - return desc.ArtifactType != v - }) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/schema1.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/schema1.go deleted file mode 100644 index 4bc1c4c45..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/schema1.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2023 Google LLC 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 remote - -import ( - "bytes" - "context" - "encoding/json" - - "github.com/google/go-containerregistry/pkg/name" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/partial" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -type schema1 struct { - ref name.Reference - ctx context.Context - fetcher fetcher - manifest []byte - mediaType types.MediaType - descriptor *v1.Descriptor -} - -func (s *schema1) Layers() ([]v1.Layer, error) { - m := schema1Manifest{} - if err := json.NewDecoder(bytes.NewReader(s.manifest)).Decode(&m); err != nil { - return nil, err - } - - layers := []v1.Layer{} - for i := len(m.FSLayers) - 1; i >= 0; i-- { - fsl := m.FSLayers[i] - - h, err := v1.NewHash(fsl.BlobSum) - if err != nil { - return nil, err - } - l, err := s.LayerByDigest(h) - if err != nil { - return nil, err - } - layers = append(layers, l) - } - - return layers, nil -} - -func (s *schema1) MediaType() (types.MediaType, error) { - return s.mediaType, nil -} - -func (s *schema1) Size() (int64, error) { - return s.descriptor.Size, nil -} - -func (s *schema1) ConfigName() (v1.Hash, error) { - return partial.ConfigName(s) -} - -func (s *schema1) ConfigFile() (*v1.ConfigFile, error) { - return nil, newErrSchema1(s.mediaType) -} - -func (s *schema1) RawConfigFile() ([]byte, error) { - return []byte("{}"), nil -} - -func (s *schema1) Digest() (v1.Hash, error) { - return s.descriptor.Digest, nil -} - -func (s *schema1) Manifest() (*v1.Manifest, error) { - return nil, newErrSchema1(s.mediaType) -} - -func (s *schema1) RawManifest() ([]byte, error) { - return s.manifest, nil -} - -func (s *schema1) LayerByDigest(h v1.Hash) (v1.Layer, error) { - l, err := partial.CompressedToLayer(&remoteLayer{ - fetcher: s.fetcher, - ctx: s.ctx, - digest: h, - }) - if err != nil { - return nil, err - } - return &MountableLayer{ - Layer: l, - Reference: s.ref.Context().Digest(h.String()), - }, nil -} - -func (s *schema1) LayerByDiffID(v1.Hash) (v1.Layer, error) { - return nil, newErrSchema1(s.mediaType) -} - -type fslayer struct { - BlobSum string `json:"blobSum"` -} - -type schema1Manifest struct { - FSLayers []fslayer `json:"fsLayers"` -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/README.md b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/README.md deleted file mode 100644 index bd4d957b0..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/README.md +++ /dev/null @@ -1,129 +0,0 @@ -# `transport` - -[![GoDoc](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/transport?status.svg)](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/transport) - -The [distribution protocol](https://github.com/opencontainers/distribution-spec) is fairly simple, but correctly [implementing authentication](../../../authn/README.md) is **hard**. - -This package [implements](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/remote/transport#New) an [`http.RoundTripper`](https://godoc.org/net/http#RoundTripper) -that transparently performs: -* [Token -Authentication](https://docs.docker.com/registry/spec/auth/token/) and -* [OAuth2 -Authentication](https://docs.docker.com/registry/spec/auth/oauth/) - -for registry clients. - -## Raison d'être - -> Why not just use the [`docker/distribution`](https://godoc.org/github.com/docker/distribution/registry/client/auth) client? - -Great question! Mostly, because I don't want to depend on [`prometheus/client_golang`](https://github.com/prometheus/client_golang). - -As a performance optimization, that client uses [a cache](https://github.com/docker/distribution/blob/a8371794149d1d95f1e846744b05c87f2f825e5a/registry/client/repository.go#L173) to keep track of a mapping between blob digests and their [descriptors](https://github.com/docker/distribution/blob/a8371794149d1d95f1e846744b05c87f2f825e5a/blobs.go#L57-L86). Unfortunately, the cache [uses prometheus](https://github.com/docker/distribution/blob/a8371794149d1d95f1e846744b05c87f2f825e5a/registry/storage/cache/cachedblobdescriptorstore.go#L44) to track hits and misses, so if you want to use that client you have to pull in all of prometheus, which is pretty large. - -![docker/distribution](../../../../images/docker.dot.svg) - -> Why does it matter if you depend on prometheus? Who cares? - -It's generally polite to your downstream to reduce the number of dependencies your package requires: - -* Downloading your package is faster, which helps our Australian friends and people on airplanes. -* There is less code to compile, which speeds up builds and saves the planet from global warming. -* You reduce the likelihood of inflicting dependency hell upon your consumers. -* [Tim Hockin](https://twitter.com/thockin/status/958606077456654336) prefers it based on his experience working on Kubernetes, and he's a pretty smart guy. - -> Okay, what about [`containerd/containerd`](https://godoc.org/github.com/containerd/containerd/remotes/docker)? - -Similar reasons! That ends up pulling in grpc, protobuf, and logrus. - -![containerd/containerd](../../../../images/containerd.dot.svg) - -> Well... what about [`containers/image`](https://godoc.org/github.com/containers/image/docker)? - -That just uses the the `docker/distribution` client... and more! - -![containers/image](../../../../images/containers.dot.svg) - -> Wow, what about this package? - -Of course, this package isn't perfect either. `transport` depends on `authn`, -which in turn depends on docker's config file parsing and handling package, -which you don't strictly need but almost certainly want if you're going to be -interacting with a registry. - -![google/go-containerregistry](../../../../images/ggcr.dot.svg) - -*These graphs were generated by -[`kisielk/godepgraph`](https://github.com/kisielk/godepgraph).* - -## Usage - -This is heavily used by the -[`remote`](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/remote) -package, which implements higher level image-centric functionality, but this -package is useful if you want to interact directly with the registry to do -something that `remote` doesn't support, e.g. [to handle with schema 1 -images](https://github.com/google/go-containerregistry/pull/509). - -This package also includes some [error -handling](https://github.com/opencontainers/distribution-spec/blob/60be706c34ee7805bdd1d3d11affec53b0dfb8fb/spec.md#errors) -facilities in the form of -[`CheckError`](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/remote/transport#CheckError), -which will parse the response body into a structured error for unexpected http -status codes. - -Here's a "simple" program that writes the result of -[listing tags](https://github.com/opencontainers/distribution-spec/blob/60be706c34ee7805bdd1d3d11affec53b0dfb8fb/spec.md#tags) -for [`gcr.io/google-containers/pause`](https://gcr.io/google-containers/pause) -to stdout. - -```go -package main - -import ( - "io" - "net/http" - "os" - - "github.com/google/go-containerregistry/pkg/authn" - "github.com/google/go-containerregistry/pkg/name" - "github.com/google/go-containerregistry/pkg/v1/remote/transport" -) - -func main() { - repo, err := name.NewRepository("gcr.io/google-containers/pause") - if err != nil { - panic(err) - } - - // Fetch credentials based on your docker config file, which is $HOME/.docker/config.json or $DOCKER_CONFIG. - auth, err := authn.DefaultKeychain.Resolve(repo.Registry) - if err != nil { - panic(err) - } - - // Construct an http.Client that is authorized to pull from gcr.io/google-containers/pause. - scopes := []string{repo.Scope(transport.PullScope)} - t, err := transport.New(repo.Registry, auth, http.DefaultTransport, scopes) - if err != nil { - panic(err) - } - client := &http.Client{Transport: t} - - // Make the actual request. - resp, err := client.Get("https://gcr.io/v2/google-containers/pause/tags/list") - if err != nil { - panic(err) - } - - // Assert that we get a 200, otherwise attempt to parse body as a structured error. - if err := transport.CheckError(resp, http.StatusOK); err != nil { - panic(err) - } - - // Write the response to stdout. - if _, err := io.Copy(os.Stdout, resp.Body); err != nil { - panic(err) - } -} -``` diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/basic.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/basic.go deleted file mode 100644 index fdb362b76..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/basic.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2018 Google LLC 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 transport - -import ( - "encoding/base64" - "fmt" - "net/http" - - "github.com/google/go-containerregistry/pkg/authn" -) - -type basicTransport struct { - inner http.RoundTripper - auth authn.Authenticator - target string -} - -var _ http.RoundTripper = (*basicTransport)(nil) - -// RoundTrip implements http.RoundTripper -func (bt *basicTransport) RoundTrip(in *http.Request) (*http.Response, error) { - if bt.auth != authn.Anonymous { - auth, err := bt.auth.Authorization() - if err != nil { - return nil, err - } - - // http.Client handles redirects at a layer above the http.RoundTripper - // abstraction, so to avoid forwarding Authorization headers to places - // we are redirected, only set it when the authorization header matches - // the host with which we are interacting. - // In case of redirect http.Client can use an empty Host, check URL too. - if in.Host == bt.target || in.URL.Host == bt.target { - if bearer := auth.RegistryToken; bearer != "" { - hdr := fmt.Sprintf("Bearer %s", bearer) - in.Header.Set("Authorization", hdr) - } else if user, pass := auth.Username, auth.Password; user != "" && pass != "" { - delimited := fmt.Sprintf("%s:%s", user, pass) - encoded := base64.StdEncoding.EncodeToString([]byte(delimited)) - hdr := fmt.Sprintf("Basic %s", encoded) - in.Header.Set("Authorization", hdr) - } else if token := auth.Auth; token != "" { - hdr := fmt.Sprintf("Basic %s", token) - in.Header.Set("Authorization", hdr) - } - } - } - return bt.inner.RoundTrip(in) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/bearer.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/bearer.go deleted file mode 100644 index cb1567496..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/bearer.go +++ /dev/null @@ -1,391 +0,0 @@ -// Copyright 2018 Google LLC 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 transport - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net" - "net/http" - "net/url" - "strings" - - authchallenge "github.com/docker/distribution/registry/client/auth/challenge" - "github.com/google/go-containerregistry/internal/redact" - "github.com/google/go-containerregistry/pkg/authn" - "github.com/google/go-containerregistry/pkg/logs" - "github.com/google/go-containerregistry/pkg/name" -) - -type Token struct { - Token string `json:"token"` - AccessToken string `json:"access_token,omitempty"` - RefreshToken string `json:"refresh_token"` - ExpiresIn int `json:"expires_in"` -} - -// Exchange requests a registry Token with the given scopes. -func Exchange(ctx context.Context, reg name.Registry, auth authn.Authenticator, t http.RoundTripper, scopes []string, pr *Challenge) (*Token, error) { - if strings.ToLower(pr.Scheme) != "bearer" { - // TODO: Pretend token for basic? - return nil, fmt.Errorf("challenge scheme %q is not bearer", pr.Scheme) - } - bt, err := fromChallenge(reg, auth, t, pr, scopes...) - if err != nil { - return nil, err - } - authcfg, err := auth.Authorization() - if err != nil { - return nil, err - } - tok, err := bt.Refresh(ctx, authcfg) - if err != nil { - return nil, err - } - return tok, nil -} - -// FromToken returns a transport given a Challenge + Token. -func FromToken(reg name.Registry, auth authn.Authenticator, t http.RoundTripper, pr *Challenge, tok *Token) (http.RoundTripper, error) { - if strings.ToLower(pr.Scheme) != "bearer" { - return &Wrapper{&basicTransport{inner: t, auth: auth, target: reg.RegistryStr()}}, nil - } - bt, err := fromChallenge(reg, auth, t, pr) - if err != nil { - return nil, err - } - if tok.Token != "" { - bt.bearer.RegistryToken = tok.Token - } - return &Wrapper{bt}, nil -} - -func fromChallenge(reg name.Registry, auth authn.Authenticator, t http.RoundTripper, pr *Challenge, scopes ...string) (*bearerTransport, error) { - // We require the realm, which tells us where to send our Basic auth to turn it into Bearer auth. - realm, ok := pr.Parameters["realm"] - if !ok { - return nil, fmt.Errorf("malformed www-authenticate, missing realm: %v", pr.Parameters) - } - service := pr.Parameters["service"] - scheme := "https" - if pr.Insecure { - scheme = "http" - } - return &bearerTransport{ - inner: t, - basic: auth, - realm: realm, - registry: reg, - service: service, - scopes: scopes, - scheme: scheme, - }, nil -} - -type bearerTransport struct { - // Wrapped by bearerTransport. - inner http.RoundTripper - // Basic credentials that we exchange for bearer tokens. - basic authn.Authenticator - // Holds the bearer response from the token service. - bearer authn.AuthConfig - // Registry to which we send bearer tokens. - registry name.Registry - // See https://tools.ietf.org/html/rfc6750#section-3 - realm string - // See https://docs.docker.com/registry/spec/auth/token/ - service string - scopes []string - // Scheme we should use, determined by ping response. - scheme string -} - -var _ http.RoundTripper = (*bearerTransport)(nil) - -var portMap = map[string]string{ - "http": "80", - "https": "443", -} - -func stringSet(ss []string) map[string]struct{} { - set := make(map[string]struct{}) - for _, s := range ss { - set[s] = struct{}{} - } - return set -} - -// RoundTrip implements http.RoundTripper -func (bt *bearerTransport) RoundTrip(in *http.Request) (*http.Response, error) { - sendRequest := func() (*http.Response, error) { - // http.Client handles redirects at a layer above the http.RoundTripper - // abstraction, so to avoid forwarding Authorization headers to places - // we are redirected, only set it when the authorization header matches - // the registry with which we are interacting. - // In case of redirect http.Client can use an empty Host, check URL too. - if matchesHost(bt.registry.RegistryStr(), in, bt.scheme) { - hdr := fmt.Sprintf("Bearer %s", bt.bearer.RegistryToken) - in.Header.Set("Authorization", hdr) - } - return bt.inner.RoundTrip(in) - } - - res, err := sendRequest() - if err != nil { - return nil, err - } - - // If we hit a WWW-Authenticate challenge, it might be due to expired tokens or insufficient scope. - if challenges := authchallenge.ResponseChallenges(res); len(challenges) != 0 { - // close out old response, since we will not return it. - res.Body.Close() - - newScopes := []string{} - for _, wac := range challenges { - // TODO(jonjohnsonjr): Should we also update "realm" or "service"? - if want, ok := wac.Parameters["scope"]; ok { - // Add any scopes that we don't already request. - got := stringSet(bt.scopes) - if _, ok := got[want]; !ok { - newScopes = append(newScopes, want) - } - } - } - - // Some registries seem to only look at the first scope parameter during a token exchange. - // If a request fails because it's missing a scope, we should put those at the beginning, - // otherwise the registry might just ignore it :/ - newScopes = append(newScopes, bt.scopes...) - bt.scopes = newScopes - - // TODO(jonjohnsonjr): Teach transport.Error about "error" and "error_description" from challenge. - - // Retry the request to attempt to get a valid token. - if err = bt.refresh(in.Context()); err != nil { - return nil, err - } - return sendRequest() - } - - return res, err -} - -// It's unclear which authentication flow to use based purely on the protocol, -// so we rely on heuristics and fallbacks to support as many registries as possible. -// The basic token exchange is attempted first, falling back to the oauth flow. -// If the IdentityToken is set, this indicates that we should start with the oauth flow. -func (bt *bearerTransport) refresh(ctx context.Context) error { - auth, err := bt.basic.Authorization() - if err != nil { - return err - } - - if auth.RegistryToken != "" { - bt.bearer.RegistryToken = auth.RegistryToken - return nil - } - - response, err := bt.Refresh(ctx, auth) - if err != nil { - return err - } - - // Some registries set access_token instead of token. See #54. - if response.AccessToken != "" { - response.Token = response.AccessToken - } - - // Find a token to turn into a Bearer authenticator - if response.Token != "" { - bt.bearer.RegistryToken = response.Token - } - - // If we obtained a refresh token from the oauth flow, use that for refresh() now. - if response.RefreshToken != "" { - bt.basic = authn.FromConfig(authn.AuthConfig{ - IdentityToken: response.RefreshToken, - }) - } - - return nil -} - -func (bt *bearerTransport) Refresh(ctx context.Context, auth *authn.AuthConfig) (*Token, error) { - var ( - content []byte - err error - ) - if auth.IdentityToken != "" { - // If the secret being stored is an identity token, - // the Username should be set to , which indicates - // we are using an oauth flow. - content, err = bt.refreshOauth(ctx) - var terr *Error - if errors.As(err, &terr) && terr.StatusCode == http.StatusNotFound { - // Note: Not all token servers implement oauth2. - // If the request to the endpoint returns 404 using the HTTP POST method, - // refer to Token Documentation for using the HTTP GET method supported by all token servers. - content, err = bt.refreshBasic(ctx) - } - } else { - content, err = bt.refreshBasic(ctx) - } - if err != nil { - return nil, err - } - - var response Token - if err := json.Unmarshal(content, &response); err != nil { - return nil, err - } - - if response.Token == "" && response.AccessToken == "" { - return &response, fmt.Errorf("no token in bearer response:\n%s", content) - } - - return &response, nil -} - -func matchesHost(host string, in *http.Request, scheme string) bool { - canonicalHeaderHost := canonicalAddress(in.Host, scheme) - canonicalURLHost := canonicalAddress(in.URL.Host, scheme) - canonicalRegistryHost := canonicalAddress(host, scheme) - return canonicalHeaderHost == canonicalRegistryHost || canonicalURLHost == canonicalRegistryHost -} - -func canonicalAddress(host, scheme string) (address string) { - // The host may be any one of: - // - hostname - // - hostname:port - // - ipv4 - // - ipv4:port - // - ipv6 - // - [ipv6]:port - // As net.SplitHostPort returns an error if the host does not contain a port, we should only attempt - // to call it when we know that the address contains a port - if strings.Count(host, ":") == 1 || (strings.Count(host, ":") >= 2 && strings.Contains(host, "]:")) { - hostname, port, err := net.SplitHostPort(host) - if err != nil { - return host - } - if port == "" { - port = portMap[scheme] - } - - return net.JoinHostPort(hostname, port) - } - - return net.JoinHostPort(host, portMap[scheme]) -} - -// https://docs.docker.com/registry/spec/auth/oauth/ -func (bt *bearerTransport) refreshOauth(ctx context.Context) ([]byte, error) { - auth, err := bt.basic.Authorization() - if err != nil { - return nil, err - } - - u, err := url.Parse(bt.realm) - if err != nil { - return nil, err - } - - v := url.Values{} - v.Set("scope", strings.Join(bt.scopes, " ")) - if bt.service != "" { - v.Set("service", bt.service) - } - v.Set("client_id", defaultUserAgent) - if auth.IdentityToken != "" { - v.Set("grant_type", "refresh_token") - v.Set("refresh_token", auth.IdentityToken) - } else if auth.Username != "" && auth.Password != "" { - // TODO(#629): This is unreachable. - v.Set("grant_type", "password") - v.Set("username", auth.Username) - v.Set("password", auth.Password) - v.Set("access_type", "offline") - } - - client := http.Client{Transport: bt.inner} - req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(v.Encode())) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - - // We don't want to log credentials. - ctx = redact.NewContext(ctx, "oauth token response contains credentials") - - resp, err := client.Do(req.WithContext(ctx)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if err := CheckError(resp, http.StatusOK); err != nil { - if bt.basic == authn.Anonymous { - logs.Warn.Printf("No matching credentials were found for %q", bt.registry) - } - return nil, err - } - - return io.ReadAll(resp.Body) -} - -// https://docs.docker.com/registry/spec/auth/token/ -func (bt *bearerTransport) refreshBasic(ctx context.Context) ([]byte, error) { - u, err := url.Parse(bt.realm) - if err != nil { - return nil, err - } - b := &basicTransport{ - inner: bt.inner, - auth: bt.basic, - target: u.Host, - } - client := http.Client{Transport: b} - - v := u.Query() - v["scope"] = bt.scopes - v.Set("service", bt.service) - u.RawQuery = v.Encode() - - req, err := http.NewRequest(http.MethodGet, u.String(), nil) - if err != nil { - return nil, err - } - - // We don't want to log credentials. - ctx = redact.NewContext(ctx, "basic token response contains credentials") - - resp, err := client.Do(req.WithContext(ctx)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if err := CheckError(resp, http.StatusOK); err != nil { - if bt.basic == authn.Anonymous { - logs.Warn.Printf("No matching credentials were found for %q", bt.registry) - } - return nil, err - } - - return io.ReadAll(resp.Body) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/doc.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/doc.go deleted file mode 100644 index ff7025b5c..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2018 Google LLC 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 transport provides facilities for setting up an authenticated -// http.RoundTripper given an Authenticator and base RoundTripper. See -// transport.New for more information. -package transport diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/error.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/error.go deleted file mode 100644 index 482a4adee..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/error.go +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright 2018 Google LLC 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 transport - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "strings" - - "github.com/google/go-containerregistry/internal/redact" -) - -// Error implements error to support the following error specification: -// https://github.com/docker/distribution/blob/master/docs/spec/api.md#errors -type Error struct { - Errors []Diagnostic `json:"errors,omitempty"` - // The http status code returned. - StatusCode int - // The request that failed. - Request *http.Request - // The raw body if we couldn't understand it. - rawBody string - - // Bit of a hack to make it easier to force a retry. - temporary bool -} - -// Check that Error implements error -var _ error = (*Error)(nil) - -// Error implements error -func (e *Error) Error() string { - prefix := "" - if e.Request != nil { - prefix = fmt.Sprintf("%s %s: ", e.Request.Method, redact.URL(e.Request.URL)) - } - return prefix + e.responseErr() -} - -func (e *Error) responseErr() string { - switch len(e.Errors) { - case 0: - if len(e.rawBody) == 0 { - if e.Request != nil && e.Request.Method == http.MethodHead { - return fmt.Sprintf("unexpected status code %d %s (HEAD responses have no body, use GET for details)", e.StatusCode, http.StatusText(e.StatusCode)) - } - return fmt.Sprintf("unexpected status code %d %s", e.StatusCode, http.StatusText(e.StatusCode)) - } - return fmt.Sprintf("unexpected status code %d %s: %s", e.StatusCode, http.StatusText(e.StatusCode), e.rawBody) - case 1: - return e.Errors[0].String() - default: - var errors []string - for _, d := range e.Errors { - errors = append(errors, d.String()) - } - return fmt.Sprintf("multiple errors returned: %s", - strings.Join(errors, "; ")) - } -} - -// Temporary returns whether the request that preceded the error is temporary. -func (e *Error) Temporary() bool { - if e.temporary { - return true - } - - if len(e.Errors) == 0 { - _, ok := temporaryStatusCodes[e.StatusCode] - return ok - } - for _, d := range e.Errors { - if _, ok := temporaryErrorCodes[d.Code]; !ok { - return false - } - } - return true -} - -// Diagnostic represents a single error returned by a Docker registry interaction. -type Diagnostic struct { - Code ErrorCode `json:"code"` - Message string `json:"message,omitempty"` - Detail any `json:"detail,omitempty"` -} - -// String stringifies the Diagnostic in the form: $Code: $Message[; $Detail] -func (d Diagnostic) String() string { - msg := fmt.Sprintf("%s: %s", d.Code, d.Message) - if d.Detail != nil { - msg = fmt.Sprintf("%s; %v", msg, d.Detail) - } - return msg -} - -// ErrorCode is an enumeration of supported error codes. -type ErrorCode string - -// The set of error conditions a registry may return: -// https://github.com/docker/distribution/blob/master/docs/spec/api.md#errors-2 -const ( - BlobUnknownErrorCode ErrorCode = "BLOB_UNKNOWN" - BlobUploadInvalidErrorCode ErrorCode = "BLOB_UPLOAD_INVALID" - BlobUploadUnknownErrorCode ErrorCode = "BLOB_UPLOAD_UNKNOWN" - DigestInvalidErrorCode ErrorCode = "DIGEST_INVALID" - ManifestBlobUnknownErrorCode ErrorCode = "MANIFEST_BLOB_UNKNOWN" - ManifestInvalidErrorCode ErrorCode = "MANIFEST_INVALID" - ManifestUnknownErrorCode ErrorCode = "MANIFEST_UNKNOWN" - ManifestUnverifiedErrorCode ErrorCode = "MANIFEST_UNVERIFIED" - NameInvalidErrorCode ErrorCode = "NAME_INVALID" - NameUnknownErrorCode ErrorCode = "NAME_UNKNOWN" - SizeInvalidErrorCode ErrorCode = "SIZE_INVALID" - TagInvalidErrorCode ErrorCode = "TAG_INVALID" - UnauthorizedErrorCode ErrorCode = "UNAUTHORIZED" - DeniedErrorCode ErrorCode = "DENIED" - UnsupportedErrorCode ErrorCode = "UNSUPPORTED" - TooManyRequestsErrorCode ErrorCode = "TOOMANYREQUESTS" - UnknownErrorCode ErrorCode = "UNKNOWN" - - // This isn't defined by either docker or OCI spec, but is defined by docker/distribution: - // https://github.com/distribution/distribution/blob/6a977a5a754baa213041443f841705888107362a/registry/api/errcode/register.go#L60 - UnavailableErrorCode ErrorCode = "UNAVAILABLE" -) - -// TODO: Include other error types. -var temporaryErrorCodes = map[ErrorCode]struct{}{ - BlobUploadInvalidErrorCode: {}, - TooManyRequestsErrorCode: {}, - UnknownErrorCode: {}, - UnavailableErrorCode: {}, -} - -var temporaryStatusCodes = map[int]struct{}{ - http.StatusRequestTimeout: {}, - http.StatusInternalServerError: {}, - http.StatusBadGateway: {}, - http.StatusServiceUnavailable: {}, - http.StatusGatewayTimeout: {}, -} - -// CheckError returns a structured error if the response status is not in codes. -func CheckError(resp *http.Response, codes ...int) error { - for _, code := range codes { - if resp.StatusCode == code { - // This is one of the supported status codes. - return nil - } - } - - b, err := io.ReadAll(resp.Body) - if err != nil { - return err - } - - return makeError(resp, b) -} - -func makeError(resp *http.Response, body []byte) *Error { - // https://github.com/docker/distribution/blob/master/docs/spec/api.md#errors - structuredError := &Error{} - - // This can fail if e.g. the response body is not valid JSON. That's fine, - // we'll construct an appropriate error string from the body and status code. - _ = json.Unmarshal(body, structuredError) - - structuredError.rawBody = string(body) - structuredError.StatusCode = resp.StatusCode - structuredError.Request = resp.Request - - return structuredError -} - -func retryError(resp *http.Response) error { - b, err := io.ReadAll(resp.Body) - if err != nil { - return err - } - - rerr := makeError(resp, b) - rerr.temporary = true - return rerr -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/logger.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/logger.go deleted file mode 100644 index c341f844e..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/logger.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2020 Google LLC 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 transport - -import ( - "fmt" - "net/http" - "net/http/httputil" - "time" - - "github.com/google/go-containerregistry/internal/redact" - "github.com/google/go-containerregistry/pkg/logs" -) - -type logTransport struct { - inner http.RoundTripper -} - -// NewLogger returns a transport that logs requests and responses to -// github.com/google/go-containerregistry/pkg/logs.Debug. -func NewLogger(inner http.RoundTripper) http.RoundTripper { - return &logTransport{inner} -} - -func (t *logTransport) RoundTrip(in *http.Request) (out *http.Response, err error) { - // Inspired by: github.com/motemen/go-loghttp - - // We redact token responses and binary blobs in response/request. - omitBody, reason := redact.FromContext(in.Context()) - if omitBody { - logs.Debug.Printf("--> %s %s [body redacted: %s]", in.Method, in.URL, reason) - } else { - logs.Debug.Printf("--> %s %s", in.Method, in.URL) - } - - // Save these headers so we can redact Authorization. - savedHeaders := in.Header.Clone() - if in.Header != nil && in.Header.Get("authorization") != "" { - in.Header.Set("authorization", "") - } - - b, err := httputil.DumpRequestOut(in, !omitBody) - if err == nil { - logs.Debug.Println(string(b)) - } else { - logs.Debug.Printf("Failed to dump request %s %s: %v", in.Method, in.URL, err) - } - - // Restore the non-redacted headers. - in.Header = savedHeaders - - start := time.Now() - out, err = t.inner.RoundTrip(in) - duration := time.Since(start) - if err != nil { - logs.Debug.Printf("<-- %v %s %s (%s)", err, in.Method, in.URL, duration) - } - if out != nil { - msg := fmt.Sprintf("<-- %d", out.StatusCode) - if out.Request != nil { - msg = fmt.Sprintf("%s %s", msg, out.Request.URL) - } - msg = fmt.Sprintf("%s (%s)", msg, duration) - - if omitBody { - msg = fmt.Sprintf("%s [body redacted: %s]", msg, reason) - } - - logs.Debug.Print(msg) - - b, err := httputil.DumpResponse(out, !omitBody) - if err == nil { - logs.Debug.Println(string(b)) - } else { - logs.Debug.Printf("Failed to dump response %s %s: %v", in.Method, in.URL, err) - } - } - return -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/ping.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/ping.go deleted file mode 100644 index 799c7ea08..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/ping.go +++ /dev/null @@ -1,217 +0,0 @@ -// Copyright 2018 Google LLC 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 transport - -import ( - "context" - "errors" - "fmt" - "io" - "net/http" - "strings" - "time" - - authchallenge "github.com/docker/distribution/registry/client/auth/challenge" - "github.com/google/go-containerregistry/pkg/logs" - "github.com/google/go-containerregistry/pkg/name" -) - -// 300ms is the default fallback period for go's DNS dialer but we could make this configurable. -var fallbackDelay = 300 * time.Millisecond - -type Challenge struct { - Scheme string - - // Following the challenge there are often key/value pairs - // e.g. Bearer service="gcr.io",realm="https://auth.gcr.io/v36/tokenz" - Parameters map[string]string - - // Whether we had to use http to complete the Ping. - Insecure bool -} - -// Ping does a GET /v2/ against the registry and returns the response. -func Ping(ctx context.Context, reg name.Registry, t http.RoundTripper) (*Challenge, error) { - // This first attempts to use "https" for every request, falling back to http - // if the registry matches our localhost heuristic or if it is intentionally - // set to insecure via name.NewInsecureRegistry. - schemes := []string{"https"} - if reg.Scheme() == "http" { - schemes = append(schemes, "http") - } - if len(schemes) == 1 { - return pingSingle(ctx, reg, t, schemes[0]) - } - return pingParallel(ctx, reg, t, schemes) -} - -func pingSingle(ctx context.Context, reg name.Registry, t http.RoundTripper, scheme string) (*Challenge, error) { - client := http.Client{Transport: t} - url := fmt.Sprintf("%s://%s/v2/", scheme, reg.RegistryStr()) - req, err := http.NewRequest(http.MethodGet, url, nil) - if err != nil { - return nil, err - } - resp, err := client.Do(req.WithContext(ctx)) - if err != nil { - return nil, err - } - defer func() { - // By draining the body, make sure to reuse the connection made by - // the ping for the following access to the registry - io.Copy(io.Discard, resp.Body) - resp.Body.Close() - }() - - insecure := scheme == "http" - - switch resp.StatusCode { - case http.StatusOK: - // If we get a 200, then no authentication is needed. - return &Challenge{ - Insecure: insecure, - }, nil - case http.StatusUnauthorized: - if challenges := authchallenge.ResponseChallenges(resp); len(challenges) != 0 { - // If we hit more than one, let's try to find one that we know how to handle. - wac := pickFromMultipleChallenges(challenges) - return &Challenge{ - Scheme: wac.Scheme, - Parameters: wac.Parameters, - Insecure: insecure, - }, nil - } - // Otherwise, just return the challenge without parameters. - return &Challenge{ - Scheme: resp.Header.Get("WWW-Authenticate"), - Insecure: insecure, - }, nil - default: - return nil, CheckError(resp, http.StatusOK, http.StatusUnauthorized) - } -} - -// Based on the golang happy eyeballs dialParallel impl in net/dial.go. -func pingParallel(ctx context.Context, reg name.Registry, t http.RoundTripper, schemes []string) (*Challenge, error) { - returned := make(chan struct{}) - defer close(returned) - - type pingResult struct { - *Challenge - error - primary bool - done bool - } - - results := make(chan pingResult) - - startRacer := func(ctx context.Context, scheme string) { - pr, err := pingSingle(ctx, reg, t, scheme) - select { - case results <- pingResult{Challenge: pr, error: err, primary: scheme == "https", done: true}: - case <-returned: - if pr != nil { - logs.Debug.Printf("%s lost race", scheme) - } - } - } - - var primary, fallback pingResult - - primaryCtx, primaryCancel := context.WithCancel(ctx) - defer primaryCancel() - go startRacer(primaryCtx, schemes[0]) - - fallbackTimer := time.NewTimer(fallbackDelay) - defer fallbackTimer.Stop() - - for { - select { - case <-fallbackTimer.C: - fallbackCtx, fallbackCancel := context.WithCancel(ctx) - defer fallbackCancel() - go startRacer(fallbackCtx, schemes[1]) - - case res := <-results: - if res.error == nil { - return res.Challenge, nil - } - if res.primary { - primary = res - } else { - fallback = res - } - if primary.done && fallback.done { - return nil, multierrs{primary.error, fallback.error} - } - if res.primary && fallbackTimer.Stop() { - // Primary failed and we haven't started the fallback, - // reset time to start fallback immediately. - fallbackTimer.Reset(0) - } - } - } -} - -func pickFromMultipleChallenges(challenges []authchallenge.Challenge) authchallenge.Challenge { - // It might happen there are multiple www-authenticate headers, e.g. `Negotiate` and `Basic`. - // Picking simply the first one could result eventually in `unrecognized challenge` error, - // that's why we're looping through the challenges in search for one that can be handled. - allowedSchemes := []string{"basic", "bearer"} - - for _, wac := range challenges { - currentScheme := strings.ToLower(wac.Scheme) - for _, allowed := range allowedSchemes { - if allowed == currentScheme { - return wac - } - } - } - - return challenges[0] -} - -type multierrs []error - -func (m multierrs) Error() string { - var b strings.Builder - hasWritten := false - for _, err := range m { - if hasWritten { - b.WriteString("; ") - } - hasWritten = true - b.WriteString(err.Error()) - } - return b.String() -} - -func (m multierrs) As(target any) bool { - for _, err := range m { - if errors.As(err, target) { - return true - } - } - return false -} - -func (m multierrs) Is(target error) bool { - for _, err := range m { - if errors.Is(err, target) { - return true - } - } - return false -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/retry.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/retry.go deleted file mode 100644 index 093f55d02..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/retry.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2018 Google LLC 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 transport - -import ( - "net/http" - "time" - - "github.com/google/go-containerregistry/internal/retry" -) - -// Sleep for 0.1 then 0.3 seconds. This should cover networking blips. -var defaultBackoff = retry.Backoff{ - Duration: 100 * time.Millisecond, - Factor: 3.0, - Jitter: 0.1, - Steps: 3, -} - -var _ http.RoundTripper = (*retryTransport)(nil) - -// retryTransport wraps a RoundTripper and retries temporary network errors. -type retryTransport struct { - inner http.RoundTripper - backoff retry.Backoff - predicate retry.Predicate - codes []int -} - -// Option is a functional option for retryTransport. -type Option func(*options) - -type options struct { - backoff retry.Backoff - predicate retry.Predicate - codes []int -} - -// Backoff is an alias of retry.Backoff to expose this configuration option to consumers of this lib -type Backoff = retry.Backoff - -// WithRetryBackoff sets the backoff for retry operations. -func WithRetryBackoff(backoff Backoff) Option { - return func(o *options) { - o.backoff = backoff - } -} - -// WithRetryPredicate sets the predicate for retry operations. -func WithRetryPredicate(predicate func(error) bool) Option { - return func(o *options) { - o.predicate = predicate - } -} - -// WithRetryStatusCodes sets which http response codes will be retried. -func WithRetryStatusCodes(codes ...int) Option { - return func(o *options) { - o.codes = codes - } -} - -// NewRetry returns a transport that retries errors. -func NewRetry(inner http.RoundTripper, opts ...Option) http.RoundTripper { - o := &options{ - backoff: defaultBackoff, - predicate: retry.IsTemporary, - } - - for _, opt := range opts { - opt(o) - } - - return &retryTransport{ - inner: inner, - backoff: o.backoff, - predicate: o.predicate, - codes: o.codes, - } -} - -func (t *retryTransport) RoundTrip(in *http.Request) (out *http.Response, err error) { - roundtrip := func() error { - out, err = t.inner.RoundTrip(in) - if !retry.Ever(in.Context()) { - return nil - } - if out != nil { - for _, code := range t.codes { - if out.StatusCode == code { - return retryError(out) - } - } - } - return err - } - retry.Retry(roundtrip, t.predicate, t.backoff) - return -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/schemer.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/schemer.go deleted file mode 100644 index 05844db13..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/schemer.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2019 Google LLC 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 transport - -import ( - "net/http" - - "github.com/google/go-containerregistry/pkg/name" -) - -type schemeTransport struct { - // Scheme we should use, determined by ping response. - scheme string - - // Registry we're talking to. - registry name.Registry - - // Wrapped by schemeTransport. - inner http.RoundTripper -} - -// RoundTrip implements http.RoundTripper -func (st *schemeTransport) RoundTrip(in *http.Request) (*http.Response, error) { - // When we ping() the registry, we determine whether to use http or https - // based on which scheme was successful. That is only valid for the - // registry server and not e.g. a separate token server or blob storage, - // so we should only override the scheme if the host is the registry. - if matchesHost(st.registry.String(), in, st.scheme) { - in.URL.Scheme = st.scheme - } - return st.inner.RoundTrip(in) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/scope.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/scope.go deleted file mode 100644 index c3b56f7a4..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/scope.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2018 Google LLC 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 transport - -// Scopes suitable to qualify each Repository -const ( - PullScope string = "pull" - PushScope string = "push,pull" - // For now DELETE is PUSH, which is the read/write ACL. - DeleteScope string = PushScope - CatalogScope string = "catalog" -) diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/transport.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/transport.go deleted file mode 100644 index bd539b44f..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/transport.go +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright 2018 Google LLC 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 transport - -import ( - "context" - "net/http" - "strings" - - "github.com/google/go-containerregistry/pkg/authn" - "github.com/google/go-containerregistry/pkg/name" -) - -// New returns a new RoundTripper based on the provided RoundTripper that has been -// setup to authenticate with the remote registry "reg", in the capacity -// laid out by the specified scopes. -// -// Deprecated: Use NewWithContext. -func New(reg name.Registry, auth authn.Authenticator, t http.RoundTripper, scopes []string) (http.RoundTripper, error) { - return NewWithContext(context.Background(), reg, auth, t, scopes) -} - -// NewWithContext returns a new RoundTripper based on the provided RoundTripper that has been -// set up to authenticate with the remote registry "reg", in the capacity -// laid out by the specified scopes. -// In case the RoundTripper is already of the type Wrapper it assumes -// authentication was already done prior to this call, so it just returns -// the provided RoundTripper without further action -func NewWithContext(ctx context.Context, reg name.Registry, auth authn.Authenticator, t http.RoundTripper, scopes []string) (http.RoundTripper, error) { - // When the transport provided is of the type Wrapper this function assumes that the caller already - // executed the necessary login and check. - switch t.(type) { - case *Wrapper: - return t, nil - } - // The handshake: - // 1. Use "t" to ping() the registry for the authentication challenge. - // - // 2a. If we get back a 200, then simply use "t". - // - // 2b. If we get back a 401 with a Basic challenge, then use a transport - // that just attachs auth each roundtrip. - // - // 2c. If we get back a 401 with a Bearer challenge, then use a transport - // that attaches a bearer token to each request, and refreshes is on 401s. - // Perform an initial refresh to seed the bearer token. - - // First we ping the registry to determine the parameters of the authentication handshake - // (if one is even necessary). - pr, err := Ping(ctx, reg, t) - if err != nil { - return nil, err - } - - // Wrap t with a useragent transport unless we already have one. - if _, ok := t.(*userAgentTransport); !ok { - t = NewUserAgent(t, "") - } - - scheme := "https" - if pr.Insecure { - scheme = "http" - } - - // Wrap t in a transport that selects the appropriate scheme based on the ping response. - t = &schemeTransport{ - scheme: scheme, - registry: reg, - inner: t, - } - - if strings.ToLower(pr.Scheme) != "bearer" { - return &Wrapper{&basicTransport{inner: t, auth: auth, target: reg.RegistryStr()}}, nil - } - - bt, err := fromChallenge(reg, auth, t, pr) - if err != nil { - return nil, err - } - bt.scopes = scopes - - if err := bt.refresh(ctx); err != nil { - return nil, err - } - return &Wrapper{bt}, nil -} - -// Wrapper results in *not* wrapping supplied transport with additional logic such as retries, useragent and debug logging -// Consumers are opt-ing into providing their own transport without any additional wrapping. -type Wrapper struct { - inner http.RoundTripper -} - -// RoundTrip delegates to the inner RoundTripper -func (w *Wrapper) RoundTrip(in *http.Request) (*http.Response, error) { - return w.inner.RoundTrip(in) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/useragent.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/useragent.go deleted file mode 100644 index 74a9e71bd..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/transport/useragent.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2019 Google LLC 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 transport - -import ( - "fmt" - "net/http" - "runtime/debug" -) - -var ( - // Version can be set via: - // -ldflags="-X 'github.com/google/go-containerregistry/pkg/v1/remote/transport.Version=$TAG'" - Version string - - ggcrVersion = defaultUserAgent -) - -const ( - defaultUserAgent = "go-containerregistry" - moduleName = "github.com/google/go-containerregistry" -) - -type userAgentTransport struct { - inner http.RoundTripper - ua string -} - -func init() { - if v := version(); v != "" { - ggcrVersion = fmt.Sprintf("%s/%s", defaultUserAgent, v) - } -} - -func version() string { - if Version != "" { - // Version was set via ldflags, just return it. - return Version - } - - info, ok := debug.ReadBuildInfo() - if !ok { - return "" - } - - // Happens for crane and gcrane. - if info.Main.Path == moduleName { - return info.Main.Version - } - - // Anything else. - for _, dep := range info.Deps { - if dep.Path == moduleName { - return dep.Version - } - } - - return "" -} - -// NewUserAgent returns an http.Roundtripper that sets the user agent to -// The provided string plus additional go-containerregistry information, -// e.g. if provided "crane/v0.1.4" and this modules was built at v0.1.4: -// -// User-Agent: crane/v0.1.4 go-containerregistry/v0.1.4 -func NewUserAgent(inner http.RoundTripper, ua string) http.RoundTripper { - if ua == "" { - ua = ggcrVersion - } else { - ua = fmt.Sprintf("%s %s", ua, ggcrVersion) - } - return &userAgentTransport{ - inner: inner, - ua: ua, - } -} - -// RoundTrip implements http.RoundTripper -func (ut *userAgentTransport) RoundTrip(in *http.Request) (*http.Response, error) { - in.Header.Set("User-Agent", ut.ua) - return ut.inner.RoundTrip(in) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/write.go b/vendor/github.com/google/go-containerregistry/pkg/v1/remote/write.go deleted file mode 100644 index 04a3989a6..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/remote/write.go +++ /dev/null @@ -1,713 +0,0 @@ -// Copyright 2018 Google LLC 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 remote - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "net/url" - "sort" - "strings" - "sync" - - "github.com/google/go-containerregistry/internal/redact" - "github.com/google/go-containerregistry/internal/retry" - "github.com/google/go-containerregistry/pkg/authn" - "github.com/google/go-containerregistry/pkg/logs" - "github.com/google/go-containerregistry/pkg/name" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/remote/transport" - "github.com/google/go-containerregistry/pkg/v1/stream" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -// Taggable is an interface that enables a manifest PUT (e.g. for tagging). -type Taggable interface { - RawManifest() ([]byte, error) -} - -// Write pushes the provided img to the specified image reference. -func Write(ref name.Reference, img v1.Image, options ...Option) (rerr error) { - o, err := makeOptions(options...) - if err != nil { - return err - } - if o.progress != nil { - defer func() { o.progress.Close(rerr) }() - } - return newPusher(o).Push(o.context, ref, img) -} - -// writer writes the elements of an image to a remote image reference. -type writer struct { - repo name.Repository - auth authn.Authenticator - transport http.RoundTripper - - client *http.Client - - progress *progress - backoff Backoff - predicate retry.Predicate - - scopeLock sync.Mutex - // Keep track of scopes that we have already requested. - scopeSet map[string]struct{} - scopes []string -} - -func makeWriter(ctx context.Context, repo name.Repository, ls []v1.Layer, o *options) (*writer, error) { - auth := o.auth - if o.keychain != nil { - kauth, err := o.keychain.Resolve(repo) - if err != nil { - return nil, err - } - auth = kauth - } - scopes := scopesForUploadingImage(repo, ls) - tr, err := transport.NewWithContext(ctx, repo.Registry, auth, o.transport, scopes) - if err != nil { - return nil, err - } - - scopeSet := map[string]struct{}{} - for _, scope := range scopes { - scopeSet[scope] = struct{}{} - } - return &writer{ - repo: repo, - client: &http.Client{Transport: tr}, - auth: auth, - transport: o.transport, - progress: o.progress, - backoff: o.retryBackoff, - predicate: o.retryPredicate, - scopes: scopes, - scopeSet: scopeSet, - }, nil -} - -// url returns a url.Url for the specified path in the context of this remote image reference. -func (w *writer) url(path string) url.URL { - return url.URL{ - Scheme: w.repo.Registry.Scheme(), - Host: w.repo.RegistryStr(), - Path: path, - } -} - -func (w *writer) maybeUpdateScopes(ctx context.Context, ml *MountableLayer) error { - if ml.Reference.Context().String() == w.repo.String() { - return nil - } - if ml.Reference.Context().Registry.String() != w.repo.Registry.String() { - return nil - } - - scope := ml.Reference.Scope(transport.PullScope) - - w.scopeLock.Lock() - defer w.scopeLock.Unlock() - - if _, ok := w.scopeSet[scope]; !ok { - w.scopeSet[scope] = struct{}{} - w.scopes = append(w.scopes, scope) - - logs.Debug.Printf("Refreshing token to add scope %q", scope) - wt, err := transport.NewWithContext(ctx, w.repo.Registry, w.auth, w.transport, w.scopes) - if err != nil { - return err - } - w.client = &http.Client{Transport: wt} - } - - return nil -} - -// nextLocation extracts the fully-qualified URL to which we should send the next request in an upload sequence. -func (w *writer) nextLocation(resp *http.Response) (string, error) { - loc := resp.Header.Get("Location") - if len(loc) == 0 { - return "", errors.New("missing Location header") - } - u, err := url.Parse(loc) - if err != nil { - return "", err - } - - // If the location header returned is just a url path, then fully qualify it. - // We cannot simply call w.url, since there might be an embedded query string. - return resp.Request.URL.ResolveReference(u).String(), nil -} - -// checkExistingBlob checks if a blob exists already in the repository by making a -// HEAD request to the blob store API. GCR performs an existence check on the -// initiation if "mount" is specified, even if no "from" sources are specified. -// However, this is not broadly applicable to all registries, e.g. ECR. -func (w *writer) checkExistingBlob(ctx context.Context, h v1.Hash) (bool, error) { - u := w.url(fmt.Sprintf("/v2/%s/blobs/%s", w.repo.RepositoryStr(), h.String())) - - req, err := http.NewRequest(http.MethodHead, u.String(), nil) - if err != nil { - return false, err - } - - resp, err := w.client.Do(req.WithContext(ctx)) - if err != nil { - return false, err - } - defer resp.Body.Close() - - if err := transport.CheckError(resp, http.StatusOK, http.StatusNotFound); err != nil { - return false, err - } - - return resp.StatusCode == http.StatusOK, nil -} - -// initiateUpload initiates the blob upload, which starts with a POST that can -// optionally include the hash of the layer and a list of repositories from -// which that layer might be read. On failure, an error is returned. -// On success, the layer was either mounted (nothing more to do) or a blob -// upload was initiated and the body of that blob should be sent to the returned -// location. -func (w *writer) initiateUpload(ctx context.Context, from, mount, origin string) (location string, mounted bool, err error) { - u := w.url(fmt.Sprintf("/v2/%s/blobs/uploads/", w.repo.RepositoryStr())) - uv := url.Values{} - if mount != "" && from != "" { - // Quay will fail if we specify a "mount" without a "from". - uv.Set("mount", mount) - uv.Set("from", from) - if origin != "" { - uv.Set("origin", origin) - } - } - u.RawQuery = uv.Encode() - - // Make the request to initiate the blob upload. - req, err := http.NewRequest(http.MethodPost, u.String(), nil) - if err != nil { - return "", false, err - } - req.Header.Set("Content-Type", "application/json") - resp, err := w.client.Do(req.WithContext(ctx)) - if err != nil { - if from != "" { - // https://github.com/google/go-containerregistry/issues/1679 - logs.Warn.Printf("retrying without mount: %v", err) - return w.initiateUpload(ctx, "", "", "") - } - return "", false, err - } - defer resp.Body.Close() - - if err := transport.CheckError(resp, http.StatusCreated, http.StatusAccepted); err != nil { - if from != "" { - // https://github.com/google/go-containerregistry/issues/1404 - logs.Warn.Printf("retrying without mount: %v", err) - return w.initiateUpload(ctx, "", "", "") - } - return "", false, err - } - - // Check the response code to determine the result. - switch resp.StatusCode { - case http.StatusCreated: - // We're done, we were able to fast-path. - return "", true, nil - case http.StatusAccepted: - // Proceed to PATCH, upload has begun. - loc, err := w.nextLocation(resp) - return loc, false, err - default: - panic("Unreachable: initiateUpload") - } -} - -// streamBlob streams the contents of the blob to the specified location. -// On failure, this will return an error. On success, this will return the location -// header indicating how to commit the streamed blob. -func (w *writer) streamBlob(ctx context.Context, layer v1.Layer, streamLocation string) (commitLocation string, rerr error) { - reset := func() {} - defer func() { - if rerr != nil { - reset() - } - }() - blob, err := layer.Compressed() - if err != nil { - return "", err - } - - getBody := layer.Compressed - if w.progress != nil { - var count int64 - blob = &progressReader{rc: blob, progress: w.progress, count: &count} - getBody = func() (io.ReadCloser, error) { - blob, err := layer.Compressed() - if err != nil { - return nil, err - } - return &progressReader{rc: blob, progress: w.progress, count: &count}, nil - } - reset = func() { - w.progress.complete(-count) - } - } - - req, err := http.NewRequest(http.MethodPatch, streamLocation, blob) - if err != nil { - return "", err - } - if _, ok := layer.(*stream.Layer); !ok { - // We can't retry streaming layers. - req.GetBody = getBody - - // If we know the size, set it. - if size, err := layer.Size(); err == nil { - req.ContentLength = size - } - } - req.Header.Set("Content-Type", "application/octet-stream") - - resp, err := w.client.Do(req.WithContext(ctx)) - if err != nil { - return "", err - } - defer resp.Body.Close() - - if err := transport.CheckError(resp, http.StatusNoContent, http.StatusAccepted, http.StatusCreated); err != nil { - return "", err - } - - // The blob has been uploaded, return the location header indicating - // how to commit this layer. - return w.nextLocation(resp) -} - -// commitBlob commits this blob by sending a PUT to the location returned from -// streaming the blob. -func (w *writer) commitBlob(ctx context.Context, location, digest string) error { - u, err := url.Parse(location) - if err != nil { - return err - } - v := u.Query() - v.Set("digest", digest) - u.RawQuery = v.Encode() - - req, err := http.NewRequest(http.MethodPut, u.String(), nil) - if err != nil { - return err - } - req.Header.Set("Content-Type", "application/octet-stream") - - resp, err := w.client.Do(req.WithContext(ctx)) - if err != nil { - return err - } - defer resp.Body.Close() - - return transport.CheckError(resp, http.StatusCreated) -} - -// incrProgress increments and sends a progress update, if WithProgress is used. -func (w *writer) incrProgress(written int64) { - if w.progress == nil { - return - } - w.progress.complete(written) -} - -// uploadOne performs a complete upload of a single layer. -func (w *writer) uploadOne(ctx context.Context, l v1.Layer) error { - tryUpload := func() error { - ctx := retry.Never(ctx) - var from, mount, origin string - if h, err := l.Digest(); err == nil { - // If we know the digest, this isn't a streaming layer. Do an existence - // check so we can skip uploading the layer if possible. - existing, err := w.checkExistingBlob(ctx, h) - if err != nil { - return err - } - if existing { - size, err := l.Size() - if err != nil { - return err - } - w.incrProgress(size) - logs.Progress.Printf("existing blob: %v", h) - return nil - } - - mount = h.String() - } - if ml, ok := l.(*MountableLayer); ok { - if err := w.maybeUpdateScopes(ctx, ml); err != nil { - return err - } - - from = ml.Reference.Context().RepositoryStr() - origin = ml.Reference.Context().RegistryStr() - - // This keeps breaking with DockerHub. - // https://github.com/google/go-containerregistry/issues/1741 - if w.repo.RegistryStr() == name.DefaultRegistry && origin != w.repo.RegistryStr() { - from = "" - origin = "" - } - } - - location, mounted, err := w.initiateUpload(ctx, from, mount, origin) - if err != nil { - return err - } else if mounted { - size, err := l.Size() - if err != nil { - return err - } - w.incrProgress(size) - h, err := l.Digest() - if err != nil { - return err - } - logs.Progress.Printf("mounted blob: %s", h.String()) - return nil - } - - // Only log layers with +json or +yaml. We can let through other stuff if it becomes popular. - // TODO(opencontainers/image-spec#791): Would be great to have an actual parser. - mt, err := l.MediaType() - if err != nil { - return err - } - smt := string(mt) - if !(strings.HasSuffix(smt, "+json") || strings.HasSuffix(smt, "+yaml")) { - ctx = redact.NewContext(ctx, "omitting binary blobs from logs") - } - - location, err = w.streamBlob(ctx, l, location) - if err != nil { - return err - } - - h, err := l.Digest() - if err != nil { - return err - } - digest := h.String() - - if err := w.commitBlob(ctx, location, digest); err != nil { - return err - } - logs.Progress.Printf("pushed blob: %s", digest) - return nil - } - - return retry.Retry(tryUpload, w.predicate, w.backoff) -} - -type withMediaType interface { - MediaType() (types.MediaType, error) -} - -// This is really silly, but go interfaces don't let me satisfy remote.Taggable -// with remote.Descriptor because of name collisions between method names and -// struct fields. -// -// Use reflection to either pull the v1.Descriptor out of remote.Descriptor or -// create a descriptor based on the RawManifest and (optionally) MediaType. -func unpackTaggable(t Taggable) ([]byte, *v1.Descriptor, error) { - if d, ok := t.(*Descriptor); ok { - return d.Manifest, &d.Descriptor, nil - } - b, err := t.RawManifest() - if err != nil { - return nil, nil, err - } - - // A reasonable default if Taggable doesn't implement MediaType. - mt := types.DockerManifestSchema2 - - if wmt, ok := t.(withMediaType); ok { - m, err := wmt.MediaType() - if err != nil { - return nil, nil, err - } - mt = m - } - - h, sz, err := v1.SHA256(bytes.NewReader(b)) - if err != nil { - return nil, nil, err - } - - return b, &v1.Descriptor{ - MediaType: mt, - Size: sz, - Digest: h, - }, nil -} - -// commitSubjectReferrers is responsible for updating the fallback tag manifest to track descriptors referring to a subject for registries that don't yet support the Referrers API. -// TODO: use conditional requests to avoid race conditions -func (w *writer) commitSubjectReferrers(ctx context.Context, sub name.Digest, add v1.Descriptor) error { - // Check if the registry supports Referrers API. - // TODO: This should be done once per registry, not once per subject. - u := w.url(fmt.Sprintf("/v2/%s/referrers/%s", w.repo.RepositoryStr(), sub.DigestStr())) - req, err := http.NewRequest(http.MethodGet, u.String(), nil) - if err != nil { - return err - } - req.Header.Set("Accept", string(types.OCIImageIndex)) - resp, err := w.client.Do(req.WithContext(ctx)) - if err != nil { - return err - } - defer resp.Body.Close() - - if err := transport.CheckError(resp, http.StatusOK, http.StatusNotFound, http.StatusBadRequest); err != nil { - return err - } - if resp.StatusCode == http.StatusOK { - // The registry supports Referrers API. The registry is responsible for updating the referrers list. - return nil - } - - // The registry doesn't support Referrers API, we need to update the manifest tagged with the fallback tag. - // Make the request to GET the current manifest. - t := fallbackTag(sub) - u = w.url(fmt.Sprintf("/v2/%s/manifests/%s", w.repo.RepositoryStr(), t.Identifier())) - req, err = http.NewRequest(http.MethodGet, u.String(), nil) - if err != nil { - return err - } - req.Header.Set("Accept", string(types.OCIImageIndex)) - resp, err = w.client.Do(req.WithContext(ctx)) - if err != nil { - return err - } - defer resp.Body.Close() - - var im v1.IndexManifest - if err := transport.CheckError(resp, http.StatusOK, http.StatusNotFound); err != nil { - return err - } else if resp.StatusCode == http.StatusNotFound { - // Not found just means there are no attachments. Start with an empty index. - im = v1.IndexManifest{ - SchemaVersion: 2, - MediaType: types.OCIImageIndex, - Manifests: []v1.Descriptor{add}, - } - } else { - if err := json.NewDecoder(resp.Body).Decode(&im); err != nil { - return err - } - if im.SchemaVersion != 2 { - return fmt.Errorf("fallback tag manifest is not a schema version 2: %d", im.SchemaVersion) - } - if im.MediaType != types.OCIImageIndex { - return fmt.Errorf("fallback tag manifest is not an OCI image index: %s", im.MediaType) - } - for _, desc := range im.Manifests { - if desc.Digest == add.Digest { - // The digest is already attached, nothing to do. - logs.Progress.Printf("fallback tag %s already had referrer", t.Identifier()) - return nil - } - } - // Append the new descriptor to the index. - im.Manifests = append(im.Manifests, add) - } - - // Sort the manifests for reproducibility. - sort.Slice(im.Manifests, func(i, j int) bool { - return im.Manifests[i].Digest.String() < im.Manifests[j].Digest.String() - }) - logs.Progress.Printf("updating fallback tag %s with new referrer", t.Identifier()) - return w.commitManifest(ctx, fallbackTaggable{im}, t) -} - -type fallbackTaggable struct { - im v1.IndexManifest -} - -func (f fallbackTaggable) RawManifest() ([]byte, error) { return json.Marshal(f.im) } -func (f fallbackTaggable) MediaType() (types.MediaType, error) { return types.OCIImageIndex, nil } - -// commitManifest does a PUT of the image's manifest. -func (w *writer) commitManifest(ctx context.Context, t Taggable, ref name.Reference) error { - // If the manifest refers to a subject, we need to check whether we need to update the fallback tag manifest. - raw, err := t.RawManifest() - if err != nil { - return err - } - var mf struct { - MediaType types.MediaType `json:"mediaType"` - Subject *v1.Descriptor `json:"subject,omitempty"` - Config struct { - MediaType types.MediaType `json:"mediaType"` - } `json:"config"` - } - if err := json.Unmarshal(raw, &mf); err != nil { - return err - } - - tryUpload := func() error { - ctx := retry.Never(ctx) - raw, desc, err := unpackTaggable(t) - if err != nil { - return err - } - - u := w.url(fmt.Sprintf("/v2/%s/manifests/%s", w.repo.RepositoryStr(), ref.Identifier())) - - // Make the request to PUT the serialized manifest - req, err := http.NewRequest(http.MethodPut, u.String(), bytes.NewBuffer(raw)) - if err != nil { - return err - } - req.Header.Set("Content-Type", string(desc.MediaType)) - - resp, err := w.client.Do(req.WithContext(ctx)) - if err != nil { - return err - } - defer resp.Body.Close() - - if err := transport.CheckError(resp, http.StatusOK, http.StatusCreated, http.StatusAccepted); err != nil { - return err - } - - // If the manifest referred to a subject, we may need to update the fallback tag manifest. - // TODO: If this fails, we'll retry the whole upload. We should retry just this part. - if mf.Subject != nil { - h, size, err := v1.SHA256(bytes.NewReader(raw)) - if err != nil { - return err - } - desc := v1.Descriptor{ - ArtifactType: string(mf.Config.MediaType), - MediaType: mf.MediaType, - Digest: h, - Size: size, - } - if err := w.commitSubjectReferrers(ctx, - ref.Context().Digest(mf.Subject.Digest.String()), - desc); err != nil { - return err - } - } - - // The image was successfully pushed! - logs.Progress.Printf("%v: digest: %v size: %d", ref, desc.Digest, desc.Size) - w.incrProgress(int64(len(raw))) - return nil - } - - return retry.Retry(tryUpload, w.predicate, w.backoff) -} - -func scopesForUploadingImage(repo name.Repository, layers []v1.Layer) []string { - // use a map as set to remove duplicates scope strings - scopeSet := map[string]struct{}{} - - for _, l := range layers { - if ml, ok := l.(*MountableLayer); ok { - // we will add push scope for ref.Context() after the loop. - // for now we ask pull scope for references of the same registry - if ml.Reference.Context().String() != repo.String() && ml.Reference.Context().Registry.String() == repo.Registry.String() { - scopeSet[ml.Reference.Scope(transport.PullScope)] = struct{}{} - } - } - } - - scopes := make([]string, 0) - // Push scope should be the first element because a few registries just look at the first scope to determine access. - scopes = append(scopes, repo.Scope(transport.PushScope)) - - for scope := range scopeSet { - scopes = append(scopes, scope) - } - - return scopes -} - -// WriteIndex pushes the provided ImageIndex to the specified image reference. -// WriteIndex will attempt to push all of the referenced manifests before -// attempting to push the ImageIndex, to retain referential integrity. -func WriteIndex(ref name.Reference, ii v1.ImageIndex, options ...Option) (rerr error) { - o, err := makeOptions(options...) - if err != nil { - return err - } - if o.progress != nil { - defer func() { o.progress.Close(rerr) }() - } - return newPusher(o).Push(o.context, ref, ii) -} - -// WriteLayer uploads the provided Layer to the specified repo. -func WriteLayer(repo name.Repository, layer v1.Layer, options ...Option) (rerr error) { - o, err := makeOptions(options...) - if err != nil { - return err - } - if o.progress != nil { - defer func() { o.progress.Close(rerr) }() - } - return newPusher(o).Upload(o.context, repo, layer) -} - -// Tag adds a tag to the given Taggable via PUT /v2/.../manifests/ -// -// Notable implementations of Taggable are v1.Image, v1.ImageIndex, and -// remote.Descriptor. -// -// If t implements MediaType, we will use that for the Content-Type, otherwise -// we will default to types.DockerManifestSchema2. -// -// Tag does not attempt to write anything other than the manifest, so callers -// should ensure that all blobs or manifests that are referenced by t exist -// in the target registry. -func Tag(tag name.Tag, t Taggable, options ...Option) error { - return Put(tag, t, options...) -} - -// Put adds a manifest from the given Taggable via PUT /v1/.../manifest/ -// -// Notable implementations of Taggable are v1.Image, v1.ImageIndex, and -// remote.Descriptor. -// -// If t implements MediaType, we will use that for the Content-Type, otherwise -// we will default to types.DockerManifestSchema2. -// -// Put does not attempt to write anything other than the manifest, so callers -// should ensure that all blobs or manifests that are referenced by t exist -// in the target registry. -func Put(ref name.Reference, t Taggable, options ...Option) error { - o, err := makeOptions(options...) - if err != nil { - return err - } - return newPusher(o).Push(o.context, ref, t) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/stream/README.md b/vendor/github.com/google/go-containerregistry/pkg/v1/stream/README.md deleted file mode 100644 index da0dda48d..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/stream/README.md +++ /dev/null @@ -1,68 +0,0 @@ -# `stream` - -[![GoDoc](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/stream?status.svg)](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/stream) - -The `stream` package contains an implementation of -[`v1.Layer`](https://godoc.org/github.com/google/go-containerregistry/pkg/v1#Layer) -that supports _streaming_ access, i.e. the layer contents are read once and not -buffered. - -## Usage - -```go -package main - -import ( - "os" - - "github.com/google/go-containerregistry/pkg/name" - "github.com/google/go-containerregistry/pkg/v1/remote" - "github.com/google/go-containerregistry/pkg/v1/stream" -) - -// upload the contents of stdin as a layer to a local registry -func main() { - repo, err := name.NewRepository("localhost:5000/stream") - if err != nil { - panic(err) - } - - layer := stream.NewLayer(os.Stdin) - - if err := remote.WriteLayer(repo, layer); err != nil { - panic(err) - } -} -``` - -## Structure - -This implements the layer portion of an [image -upload](/pkg/v1/remote#anatomy-of-an-image-upload). We launch a goroutine that -is responsible for hashing the uncompressed contents to compute the `DiffID`, -gzipping them to produce the `Compressed` contents, and hashing/counting the -bytes to produce the `Digest`/`Size`. This goroutine writes to an -`io.PipeWriter`, which blocks until `Compressed` reads the gzipped contents from -the corresponding `io.PipeReader`. - -

- -

- -## Caveats - -This assumes that you have an uncompressed layer (i.e. a tarball) and would like -to compress it. Calling `Uncompressed` is always an error. Likewise, other -methods are invalid until the contents of `Compressed` have been completely -consumed and `Close`d. - -Using a `stream.Layer` will likely not work without careful consideration. For -example, in the `mutate` package, we defer computing the manifest and config -file until they are actually called. This allows you to `mutate.Append` a -streaming layer to an image without accidentally consuming it. Similarly, in -`remote.Write`, if calling `Digest` on a layer fails, we attempt to upload the -layer anyway, understanding that we may be dealing with a `stream.Layer` whose -contents need to be uploaded before we can upload the config file. - -Given the [structure](#structure) of how this is implemented, forgetting to -`Close` a `stream.Layer` will leak a goroutine. diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/stream/layer.go b/vendor/github.com/google/go-containerregistry/pkg/v1/stream/layer.go deleted file mode 100644 index 2b0354479..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/stream/layer.go +++ /dev/null @@ -1,275 +0,0 @@ -// Copyright 2018 Google LLC 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 stream implements a single-pass streaming v1.Layer. -package stream - -import ( - "bufio" - "compress/gzip" - "crypto" - "encoding/hex" - "errors" - "hash" - "io" - "os" - "sync" - - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -var ( - // ErrNotComputed is returned when the requested value is not yet - // computed because the stream has not been consumed yet. - ErrNotComputed = errors.New("value not computed until stream is consumed") - - // ErrConsumed is returned by Compressed when the underlying stream has - // already been consumed and closed. - ErrConsumed = errors.New("stream was already consumed") -) - -// Layer is a streaming implementation of v1.Layer. -type Layer struct { - blob io.ReadCloser - consumed bool - compression int - - mu sync.Mutex - digest, diffID *v1.Hash - size int64 - mediaType types.MediaType -} - -var _ v1.Layer = (*Layer)(nil) - -// LayerOption applies options to layer -type LayerOption func(*Layer) - -// WithCompressionLevel sets the gzip compression. See `gzip.NewWriterLevel` for possible values. -func WithCompressionLevel(level int) LayerOption { - return func(l *Layer) { - l.compression = level - } -} - -// WithMediaType is a functional option for overriding the layer's media type. -func WithMediaType(mt types.MediaType) LayerOption { - return func(l *Layer) { - l.mediaType = mt - } -} - -// NewLayer creates a Layer from an io.ReadCloser. -func NewLayer(rc io.ReadCloser, opts ...LayerOption) *Layer { - layer := &Layer{ - blob: rc, - compression: gzip.BestSpeed, - // We use DockerLayer for now as uncompressed layers - // are unimplemented - mediaType: types.DockerLayer, - } - - for _, opt := range opts { - opt(layer) - } - - return layer -} - -// Digest implements v1.Layer. -func (l *Layer) Digest() (v1.Hash, error) { - l.mu.Lock() - defer l.mu.Unlock() - if l.digest == nil { - return v1.Hash{}, ErrNotComputed - } - return *l.digest, nil -} - -// DiffID implements v1.Layer. -func (l *Layer) DiffID() (v1.Hash, error) { - l.mu.Lock() - defer l.mu.Unlock() - if l.diffID == nil { - return v1.Hash{}, ErrNotComputed - } - return *l.diffID, nil -} - -// Size implements v1.Layer. -func (l *Layer) Size() (int64, error) { - l.mu.Lock() - defer l.mu.Unlock() - if l.size == 0 { - return 0, ErrNotComputed - } - return l.size, nil -} - -// MediaType implements v1.Layer -func (l *Layer) MediaType() (types.MediaType, error) { - return l.mediaType, nil -} - -// Uncompressed implements v1.Layer. -func (l *Layer) Uncompressed() (io.ReadCloser, error) { - return nil, errors.New("NYI: stream.Layer.Uncompressed is not implemented") -} - -// Compressed implements v1.Layer. -func (l *Layer) Compressed() (io.ReadCloser, error) { - l.mu.Lock() - defer l.mu.Unlock() - if l.consumed { - return nil, ErrConsumed - } - return newCompressedReader(l) -} - -// finalize sets the layer to consumed and computes all hash and size values. -func (l *Layer) finalize(uncompressed, compressed hash.Hash, size int64) error { - l.mu.Lock() - defer l.mu.Unlock() - - diffID, err := v1.NewHash("sha256:" + hex.EncodeToString(uncompressed.Sum(nil))) - if err != nil { - return err - } - l.diffID = &diffID - - digest, err := v1.NewHash("sha256:" + hex.EncodeToString(compressed.Sum(nil))) - if err != nil { - return err - } - l.digest = &digest - - l.size = size - l.consumed = true - return nil -} - -type compressedReader struct { - pr io.Reader - closer func() error -} - -func newCompressedReader(l *Layer) (*compressedReader, error) { - // Collect digests of compressed and uncompressed stream and size of - // compressed stream. - h := crypto.SHA256.New() - zh := crypto.SHA256.New() - count := &countWriter{} - - // gzip.Writer writes to the output stream via pipe, a hasher to - // capture compressed digest, and a countWriter to capture compressed - // size. - pr, pw := io.Pipe() - - // Write compressed bytes to be read by the pipe.Reader, hashed by zh, and counted by count. - mw := io.MultiWriter(pw, zh, count) - - // Buffer the output of the gzip writer so we don't have to wait on pr to keep writing. - // 64K ought to be small enough for anybody. - bw := bufio.NewWriterSize(mw, 2<<16) - zw, err := gzip.NewWriterLevel(bw, l.compression) - if err != nil { - return nil, err - } - - doneDigesting := make(chan struct{}) - - cr := &compressedReader{ - pr: pr, - closer: func() error { - // Immediately close pw without error. There are three ways to get - // here. - // - // 1. There was a copy error due from the underlying reader, in which - // case the error will not be overwritten. - // 2. Copying from the underlying reader completed successfully. - // 3. Close has been called before the underlying reader has been - // fully consumed. In this case pw must be closed in order to - // keep the flush of bw from blocking indefinitely. - // - // NOTE: pw.Close never returns an error. The signature is only to - // implement io.Closer. - _ = pw.Close() - - // Close the inner ReadCloser. - // - // NOTE: net/http will call close on success, so if we've already - // closed the inner rc, it's not an error. - if err := l.blob.Close(); err != nil && !errors.Is(err, os.ErrClosed) { - return err - } - - // Finalize layer with its digest and size values. - <-doneDigesting - return l.finalize(h, zh, count.n) - }, - } - go func() { - // Copy blob into the gzip writer, which also hashes and counts the - // size of the compressed output, and hasher of the raw contents. - _, copyErr := io.Copy(io.MultiWriter(h, zw), l.blob) - - // Close the gzip writer once copying is done. If this is done in the - // Close method of compressedReader instead, then it can cause a panic - // when the compressedReader is closed before the blob is fully - // consumed and io.Copy in this goroutine is still blocking. - closeErr := zw.Close() - - // Check errors from writing and closing streams. - if copyErr != nil { - close(doneDigesting) - pw.CloseWithError(copyErr) - return - } - if closeErr != nil { - close(doneDigesting) - pw.CloseWithError(closeErr) - return - } - - // Flush the buffer once all writes are complete to the gzip writer. - if err := bw.Flush(); err != nil { - close(doneDigesting) - pw.CloseWithError(err) - return - } - - // Notify closer that digests are done being written. - close(doneDigesting) - - // Close the compressed reader to calculate digest/diffID/size. This - // will cause pr to return EOF which will cause readers of the - // Compressed stream to finish reading. - pw.CloseWithError(cr.Close()) - }() - - return cr, nil -} - -func (cr *compressedReader) Read(b []byte) (int, error) { return cr.pr.Read(b) } - -func (cr *compressedReader) Close() error { return cr.closer() } - -// countWriter counts bytes written to it. -type countWriter struct{ n int64 } - -func (c *countWriter) Write(p []byte) (int, error) { - c.n += int64(len(p)) - return len(p), nil -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/tarball/README.md b/vendor/github.com/google/go-containerregistry/pkg/v1/tarball/README.md deleted file mode 100644 index 03f339b06..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/tarball/README.md +++ /dev/null @@ -1,280 +0,0 @@ -# `tarball` - -[![GoDoc](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/tarball?status.svg)](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/tarball) - -This package produces tarballs that can consumed via `docker load`. Note -that this is a _different_ format from the [`legacy`](/pkg/legacy/tarball) -tarballs that are produced by `docker save`, but this package is still able to -read the legacy tarballs produced by `docker save`. - -## Usage - -```go -package main - -import ( - "os" - - "github.com/google/go-containerregistry/pkg/name" - "github.com/google/go-containerregistry/pkg/v1/tarball" -) - -func main() { - // Read a tarball from os.Args[1] that contains ubuntu. - tag, err := name.NewTag("ubuntu") - if err != nil { - panic(err) - } - img, err := tarball.ImageFromPath(os.Args[1], &tag) - if err != nil { - panic(err) - } - - // Write that tarball to os.Args[2] with a different tag. - newTag, err := name.NewTag("ubuntu:newest") - if err != nil { - panic(err) - } - f, err := os.Create(os.Args[2]) - if err != nil { - panic(err) - } - defer f.Close() - - if err := tarball.Write(newTag, img, f); err != nil { - panic(err) - } -} -``` - -## Structure - -

- -

- -Let's look at what happens when we write out a tarball: - - -### `ubuntu:latest` - -``` -$ crane pull ubuntu ubuntu.tar && mkdir ubuntu && tar xf ubuntu.tar -C ubuntu && rm ubuntu.tar -$ tree ubuntu/ -ubuntu/ -├── 423ae2b273f4c17ceee9e8482fa8d071d90c7d052ae208e1fe4963fceb3d6954.tar.gz -├── b6b53be908de2c0c78070fff0a9f04835211b3156c4e73785747af365e71a0d7.tar.gz -├── de83a2304fa1f7c4a13708a0d15b9704f5945c2be5cbb2b3ed9b2ccb718d0b3d.tar.gz -├── f9a83bce3af0648efaa60b9bb28225b09136d2d35d0bed25ac764297076dec1b.tar.gz -├── manifest.json -└── sha256:72300a873c2ca11c70d0c8642177ce76ff69ae04d61a5813ef58d40ff66e3e7c - -0 directories, 6 files -``` - -There are a couple interesting files here. - -`manifest.json` is the entrypoint: a list of [`tarball.Descriptor`s](https://godoc.org/github.com/google/go-containerregistry/pkg/v1/tarball#Descriptor) -that describe the images contained in this tarball. - -For each image, this has the `RepoTags` (how it was pulled), a `Config` file -that points to the image's config file, a list of `Layers`, and (optionally) -`LayerSources`. - -``` -$ jq < ubuntu/manifest.json -[ - { - "Config": "sha256:72300a873c2ca11c70d0c8642177ce76ff69ae04d61a5813ef58d40ff66e3e7c", - "RepoTags": [ - "ubuntu" - ], - "Layers": [ - "423ae2b273f4c17ceee9e8482fa8d071d90c7d052ae208e1fe4963fceb3d6954.tar.gz", - "de83a2304fa1f7c4a13708a0d15b9704f5945c2be5cbb2b3ed9b2ccb718d0b3d.tar.gz", - "f9a83bce3af0648efaa60b9bb28225b09136d2d35d0bed25ac764297076dec1b.tar.gz", - "b6b53be908de2c0c78070fff0a9f04835211b3156c4e73785747af365e71a0d7.tar.gz" - ] - } -] -``` - -The config file and layers are exactly what you would expect, and match the -registry representations of the same artifacts. You'll notice that the -`manifest.json` contains similar information as the registry manifest, but isn't -quite the same: - -``` -$ crane manifest ubuntu@sha256:0925d086715714114c1988f7c947db94064fd385e171a63c07730f1fa014e6f9 -{ - "schemaVersion": 2, - "mediaType": "application/vnd.docker.distribution.manifest.v2+json", - "config": { - "mediaType": "application/vnd.docker.container.image.v1+json", - "size": 3408, - "digest": "sha256:72300a873c2ca11c70d0c8642177ce76ff69ae04d61a5813ef58d40ff66e3e7c" - }, - "layers": [ - { - "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip", - "size": 26692096, - "digest": "sha256:423ae2b273f4c17ceee9e8482fa8d071d90c7d052ae208e1fe4963fceb3d6954" - }, - { - "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip", - "size": 35365, - "digest": "sha256:de83a2304fa1f7c4a13708a0d15b9704f5945c2be5cbb2b3ed9b2ccb718d0b3d" - }, - { - "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip", - "size": 852, - "digest": "sha256:f9a83bce3af0648efaa60b9bb28225b09136d2d35d0bed25ac764297076dec1b" - }, - { - "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip", - "size": 163, - "digest": "sha256:b6b53be908de2c0c78070fff0a9f04835211b3156c4e73785747af365e71a0d7" - } - ] -} -``` - -This makes it difficult to maintain image digests when roundtripping images -through the tarball format, so it's not a great format if you care about -provenance. - -The ubuntu example didn't have any `LayerSources` -- let's look at another image -that does. - -### `hello-world:nanoserver` - -``` -$ crane pull hello-world:nanoserver@sha256:63c287625c2b0b72900e562de73c0e381472a83b1b39217aef3856cd398eca0b nanoserver.tar -$ mkdir nanoserver && tar xf nanoserver.tar -C nanoserver && rm nanoserver.tar -$ tree nanoserver/ -nanoserver/ -├── 10d1439be4eb8819987ec2e9c140d44d74d6b42a823d57fe1953bd99948e1bc0.tar.gz -├── a35da61c356213336e646756218539950461ff2bf096badf307a23add6e70053.tar.gz -├── be21f08f670160cbae227e3053205b91d6bfa3de750b90c7e00bd2c511ccb63a.tar.gz -├── manifest.json -└── sha256:bc5d255ea81f83c8c38a982a6d29a6f2198427d258aea5f166e49856896b2da6 - -0 directories, 5 files - -$ jq < nanoserver/manifest.json -[ - { - "Config": "sha256:bc5d255ea81f83c8c38a982a6d29a6f2198427d258aea5f166e49856896b2da6", - "RepoTags": [ - "index.docker.io/library/hello-world:i-was-a-digest" - ], - "Layers": [ - "a35da61c356213336e646756218539950461ff2bf096badf307a23add6e70053.tar.gz", - "be21f08f670160cbae227e3053205b91d6bfa3de750b90c7e00bd2c511ccb63a.tar.gz", - "10d1439be4eb8819987ec2e9c140d44d74d6b42a823d57fe1953bd99948e1bc0.tar.gz" - ], - "LayerSources": { - "sha256:26fd2d9d4c64a4f965bbc77939a454a31b607470f430b5d69fc21ded301fa55e": { - "mediaType": "application/vnd.docker.image.rootfs.foreign.diff.tar.gzip", - "size": 101145811, - "digest": "sha256:a35da61c356213336e646756218539950461ff2bf096badf307a23add6e70053", - "urls": [ - "https://mcr.microsoft.com/v2/windows/nanoserver/blobs/sha256:a35da61c356213336e646756218539950461ff2bf096badf307a23add6e70053" - ] - } - } - } -] -``` - -A couple things to note about this `manifest.json` versus the other: -* The `RepoTags` field is a bit weird here. `hello-world` is a multi-platform - image, so We had to pull this image by digest, since we're (I'm) on - amd64/linux and wanted to grab a windows image. Since the tarball format - expects a tag under `RepoTags`, and we didn't pull by tag, we replace the - digest with a sentinel `i-was-a-digest` "tag" to appease docker. -* The `LayerSources` has enough information to reconstruct the foreign layers - pointer when pushing/pulling from the registry. For legal reasons, microsoft - doesn't want anyone but them to serve windows base images, so the mediaType - here indicates a "foreign" or "non-distributable" layer with an URL for where - you can download it from microsoft (see the [OCI - image-spec](https://github.com/opencontainers/image-spec/blob/master/layer.md#non-distributable-layers)). - -We can look at what's in the registry to explain both of these things: -``` -$ crane manifest hello-world:nanoserver | jq . -{ - "manifests": [ - { - "digest": "sha256:63c287625c2b0b72900e562de73c0e381472a83b1b39217aef3856cd398eca0b", - "mediaType": "application/vnd.docker.distribution.manifest.v2+json", - "platform": { - "architecture": "amd64", - "os": "windows", - "os.version": "10.0.17763.1040" - }, - "size": 1124 - } - ], - "mediaType": "application/vnd.docker.distribution.manifest.list.v2+json", - "schemaVersion": 2 -} - - -# Note the media type and "urls" field. -$ crane manifest hello-world:nanoserver@sha256:63c287625c2b0b72900e562de73c0e381472a83b1b39217aef3856cd398eca0b | jq . -{ - "schemaVersion": 2, - "mediaType": "application/vnd.docker.distribution.manifest.v2+json", - "config": { - "mediaType": "application/vnd.docker.container.image.v1+json", - "size": 1721, - "digest": "sha256:bc5d255ea81f83c8c38a982a6d29a6f2198427d258aea5f166e49856896b2da6" - }, - "layers": [ - { - "mediaType": "application/vnd.docker.image.rootfs.foreign.diff.tar.gzip", - "size": 101145811, - "digest": "sha256:a35da61c356213336e646756218539950461ff2bf096badf307a23add6e70053", - "urls": [ - "https://mcr.microsoft.com/v2/windows/nanoserver/blobs/sha256:a35da61c356213336e646756218539950461ff2bf096badf307a23add6e70053" - ] - }, - { - "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip", - "size": 1669, - "digest": "sha256:be21f08f670160cbae227e3053205b91d6bfa3de750b90c7e00bd2c511ccb63a" - }, - { - "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip", - "size": 949, - "digest": "sha256:10d1439be4eb8819987ec2e9c140d44d74d6b42a823d57fe1953bd99948e1bc0" - } - ] -} -``` - -The `LayerSources` map is keyed by the diffid. Note that `sha256:26fd2d9d4c64a4f965bbc77939a454a31b607470f430b5d69fc21ded301fa55e` matches the first layer in the config file: -``` -$ jq '.[0].LayerSources' < nanoserver/manifest.json -{ - "sha256:26fd2d9d4c64a4f965bbc77939a454a31b607470f430b5d69fc21ded301fa55e": { - "mediaType": "application/vnd.docker.image.rootfs.foreign.diff.tar.gzip", - "size": 101145811, - "digest": "sha256:a35da61c356213336e646756218539950461ff2bf096badf307a23add6e70053", - "urls": [ - "https://mcr.microsoft.com/v2/windows/nanoserver/blobs/sha256:a35da61c356213336e646756218539950461ff2bf096badf307a23add6e70053" - ] - } -} - -$ jq < nanoserver/sha256\:bc5d255ea81f83c8c38a982a6d29a6f2198427d258aea5f166e49856896b2da6 | jq .rootfs -{ - "type": "layers", - "diff_ids": [ - "sha256:26fd2d9d4c64a4f965bbc77939a454a31b607470f430b5d69fc21ded301fa55e", - "sha256:601cf7d78c62e4b4d32a7bbf96a17606a9cea5bd9d22ffa6f34aa431d056b0e8", - "sha256:a1e1a3bf6529adcce4d91dce2cad86c2604a66b507ccbc4d2239f3da0ec5aab9" - ] -} -``` diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/tarball/doc.go b/vendor/github.com/google/go-containerregistry/pkg/v1/tarball/doc.go deleted file mode 100644 index 4eb79bb4e..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/tarball/doc.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2018 Google LLC 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 tarball provides facilities for reading/writing v1.Images from/to -// a tarball on-disk. -package tarball diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/tarball/image.go b/vendor/github.com/google/go-containerregistry/pkg/v1/tarball/image.go deleted file mode 100644 index aba609dea..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/tarball/image.go +++ /dev/null @@ -1,440 +0,0 @@ -// Copyright 2018 Google LLC 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 tarball - -import ( - "archive/tar" - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "os" - "path" - "path/filepath" - "sync" - - comp "github.com/google/go-containerregistry/internal/compression" - "github.com/google/go-containerregistry/pkg/compression" - "github.com/google/go-containerregistry/pkg/name" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/partial" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -type image struct { - opener Opener - manifest *Manifest - config []byte - imgDescriptor *Descriptor - - tag *name.Tag -} - -type uncompressedImage struct { - *image -} - -type compressedImage struct { - *image - manifestLock sync.Mutex // Protects manifest - manifest *v1.Manifest -} - -var _ partial.UncompressedImageCore = (*uncompressedImage)(nil) -var _ partial.CompressedImageCore = (*compressedImage)(nil) - -// Opener is a thunk for opening a tar file. -type Opener func() (io.ReadCloser, error) - -func pathOpener(path string) Opener { - return func() (io.ReadCloser, error) { - return os.Open(path) - } -} - -// ImageFromPath returns a v1.Image from a tarball located on path. -func ImageFromPath(path string, tag *name.Tag) (v1.Image, error) { - return Image(pathOpener(path), tag) -} - -// LoadManifest load manifest -func LoadManifest(opener Opener) (Manifest, error) { - m, err := extractFileFromTar(opener, "manifest.json") - if err != nil { - return nil, err - } - defer m.Close() - - var manifest Manifest - - if err := json.NewDecoder(m).Decode(&manifest); err != nil { - return nil, err - } - return manifest, nil -} - -// Image exposes an image from the tarball at the provided path. -func Image(opener Opener, tag *name.Tag) (v1.Image, error) { - img := &image{ - opener: opener, - tag: tag, - } - if err := img.loadTarDescriptorAndConfig(); err != nil { - return nil, err - } - - // Peek at the first layer and see if it's compressed. - if len(img.imgDescriptor.Layers) > 0 { - compressed, err := img.areLayersCompressed() - if err != nil { - return nil, err - } - if compressed { - c := compressedImage{ - image: img, - } - return partial.CompressedToImage(&c) - } - } - - uc := uncompressedImage{ - image: img, - } - return partial.UncompressedToImage(&uc) -} - -func (i *image) MediaType() (types.MediaType, error) { - return types.DockerManifestSchema2, nil -} - -// Descriptor stores the manifest data for a single image inside a `docker save` tarball. -type Descriptor struct { - Config string - RepoTags []string - Layers []string - - // Tracks foreign layer info. Key is DiffID. - LayerSources map[v1.Hash]v1.Descriptor `json:",omitempty"` -} - -// Manifest represents the manifests of all images as the `manifest.json` file in a `docker save` tarball. -type Manifest []Descriptor - -func (m Manifest) findDescriptor(tag *name.Tag) (*Descriptor, error) { - if tag == nil { - if len(m) != 1 { - return nil, errors.New("tarball must contain only a single image to be used with tarball.Image") - } - return &(m)[0], nil - } - for _, img := range m { - for _, tagStr := range img.RepoTags { - repoTag, err := name.NewTag(tagStr) - if err != nil { - return nil, err - } - - // Compare the resolved names, since there are several ways to specify the same tag. - if repoTag.Name() == tag.Name() { - return &img, nil - } - } - } - return nil, fmt.Errorf("tag %s not found in tarball", tag) -} - -func (i *image) areLayersCompressed() (bool, error) { - if len(i.imgDescriptor.Layers) == 0 { - return false, errors.New("0 layers found in image") - } - layer := i.imgDescriptor.Layers[0] - blob, err := extractFileFromTar(i.opener, layer) - if err != nil { - return false, err - } - defer blob.Close() - - cp, _, err := comp.PeekCompression(blob) - if err != nil { - return false, err - } - - return cp != compression.None, nil -} - -func (i *image) loadTarDescriptorAndConfig() error { - m, err := extractFileFromTar(i.opener, "manifest.json") - if err != nil { - return err - } - defer m.Close() - - if err := json.NewDecoder(m).Decode(&i.manifest); err != nil { - return err - } - - if i.manifest == nil { - return errors.New("no valid manifest.json in tarball") - } - - i.imgDescriptor, err = i.manifest.findDescriptor(i.tag) - if err != nil { - return err - } - - cfg, err := extractFileFromTar(i.opener, i.imgDescriptor.Config) - if err != nil { - return err - } - defer cfg.Close() - - i.config, err = io.ReadAll(cfg) - if err != nil { - return err - } - return nil -} - -func (i *image) RawConfigFile() ([]byte, error) { - return i.config, nil -} - -// tarFile represents a single file inside a tar. Closing it closes the tar itself. -type tarFile struct { - io.Reader - io.Closer -} - -func extractFileFromTar(opener Opener, filePath string) (io.ReadCloser, error) { - f, err := opener() - if err != nil { - return nil, err - } - needClose := true - defer func() { - if needClose { - f.Close() - } - }() - - tf := tar.NewReader(f) - for { - hdr, err := tf.Next() - if errors.Is(err, io.EOF) { - break - } - if err != nil { - return nil, err - } - if hdr.Name == filePath { - if hdr.Typeflag == tar.TypeSymlink || hdr.Typeflag == tar.TypeLink { - currentDir := filepath.Dir(filePath) - return extractFileFromTar(opener, path.Join(currentDir, path.Clean(hdr.Linkname))) - } - needClose = false - return tarFile{ - Reader: tf, - Closer: f, - }, nil - } - } - return nil, fmt.Errorf("file %s not found in tar", filePath) -} - -// uncompressedLayerFromTarball implements partial.UncompressedLayer -type uncompressedLayerFromTarball struct { - diffID v1.Hash - mediaType types.MediaType - opener Opener - filePath string -} - -// foreignUncompressedLayer implements partial.UncompressedLayer but returns -// a custom descriptor. This allows the foreign layer URLs to be included in -// the generated image manifest for uncompressed layers. -type foreignUncompressedLayer struct { - uncompressedLayerFromTarball - desc v1.Descriptor -} - -func (fl *foreignUncompressedLayer) Descriptor() (*v1.Descriptor, error) { - return &fl.desc, nil -} - -// DiffID implements partial.UncompressedLayer -func (ulft *uncompressedLayerFromTarball) DiffID() (v1.Hash, error) { - return ulft.diffID, nil -} - -// Uncompressed implements partial.UncompressedLayer -func (ulft *uncompressedLayerFromTarball) Uncompressed() (io.ReadCloser, error) { - return extractFileFromTar(ulft.opener, ulft.filePath) -} - -func (ulft *uncompressedLayerFromTarball) MediaType() (types.MediaType, error) { - return ulft.mediaType, nil -} - -func (i *uncompressedImage) LayerByDiffID(h v1.Hash) (partial.UncompressedLayer, error) { - cfg, err := partial.ConfigFile(i) - if err != nil { - return nil, err - } - for idx, diffID := range cfg.RootFS.DiffIDs { - if diffID == h { - // Technically the media type should be 'application/tar' but given that our - // v1.Layer doesn't force consumers to care about whether the layer is compressed - // we should be fine returning the DockerLayer media type - mt := types.DockerLayer - bd, ok := i.imgDescriptor.LayerSources[h] - if ok { - // This is janky, but we don't want to implement Descriptor for - // uncompressed layers because it breaks a bunch of assumptions in partial. - // See https://github.com/google/go-containerregistry/issues/1870 - docker25workaround := bd.MediaType == types.DockerUncompressedLayer || bd.MediaType == types.OCIUncompressedLayer - - if !docker25workaround { - // Overwrite the mediaType for foreign layers. - return &foreignUncompressedLayer{ - uncompressedLayerFromTarball: uncompressedLayerFromTarball{ - diffID: diffID, - mediaType: bd.MediaType, - opener: i.opener, - filePath: i.imgDescriptor.Layers[idx], - }, - desc: bd, - }, nil - } - - // Intentional fall through. - } - - return &uncompressedLayerFromTarball{ - diffID: diffID, - mediaType: mt, - opener: i.opener, - filePath: i.imgDescriptor.Layers[idx], - }, nil - } - } - return nil, fmt.Errorf("diff id %q not found", h) -} - -func (c *compressedImage) Manifest() (*v1.Manifest, error) { - c.manifestLock.Lock() - defer c.manifestLock.Unlock() - if c.manifest != nil { - return c.manifest, nil - } - - b, err := c.RawConfigFile() - if err != nil { - return nil, err - } - - cfgHash, cfgSize, err := v1.SHA256(bytes.NewReader(b)) - if err != nil { - return nil, err - } - - c.manifest = &v1.Manifest{ - SchemaVersion: 2, - MediaType: types.DockerManifestSchema2, - Config: v1.Descriptor{ - MediaType: types.DockerConfigJSON, - Size: cfgSize, - Digest: cfgHash, - }, - } - - for i, p := range c.imgDescriptor.Layers { - cfg, err := partial.ConfigFile(c) - if err != nil { - return nil, err - } - diffid := cfg.RootFS.DiffIDs[i] - if d, ok := c.imgDescriptor.LayerSources[diffid]; ok { - // If it's a foreign layer, just append the descriptor so we can avoid - // reading the entire file. - c.manifest.Layers = append(c.manifest.Layers, d) - } else { - l, err := extractFileFromTar(c.opener, p) - if err != nil { - return nil, err - } - defer l.Close() - sha, size, err := v1.SHA256(l) - if err != nil { - return nil, err - } - c.manifest.Layers = append(c.manifest.Layers, v1.Descriptor{ - MediaType: types.DockerLayer, - Size: size, - Digest: sha, - }) - } - } - return c.manifest, nil -} - -func (c *compressedImage) RawManifest() ([]byte, error) { - return partial.RawManifest(c) -} - -// compressedLayerFromTarball implements partial.CompressedLayer -type compressedLayerFromTarball struct { - desc v1.Descriptor - opener Opener - filePath string -} - -// Digest implements partial.CompressedLayer -func (clft *compressedLayerFromTarball) Digest() (v1.Hash, error) { - return clft.desc.Digest, nil -} - -// Compressed implements partial.CompressedLayer -func (clft *compressedLayerFromTarball) Compressed() (io.ReadCloser, error) { - return extractFileFromTar(clft.opener, clft.filePath) -} - -// MediaType implements partial.CompressedLayer -func (clft *compressedLayerFromTarball) MediaType() (types.MediaType, error) { - return clft.desc.MediaType, nil -} - -// Size implements partial.CompressedLayer -func (clft *compressedLayerFromTarball) Size() (int64, error) { - return clft.desc.Size, nil -} - -func (c *compressedImage) LayerByDigest(h v1.Hash) (partial.CompressedLayer, error) { - m, err := c.Manifest() - if err != nil { - return nil, err - } - for i, l := range m.Layers { - if l.Digest == h { - fp := c.imgDescriptor.Layers[i] - return &compressedLayerFromTarball{ - desc: l, - opener: c.opener, - filePath: fp, - }, nil - } - } - return nil, fmt.Errorf("blob %v not found", h) -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/tarball/layer.go b/vendor/github.com/google/go-containerregistry/pkg/v1/tarball/layer.go deleted file mode 100644 index 8a2630961..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/tarball/layer.go +++ /dev/null @@ -1,354 +0,0 @@ -// Copyright 2018 Google LLC 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 tarball - -import ( - "bytes" - "compress/gzip" - "fmt" - "io" - "os" - "sync" - - "github.com/containerd/stargz-snapshotter/estargz" - "github.com/google/go-containerregistry/internal/and" - comp "github.com/google/go-containerregistry/internal/compression" - gestargz "github.com/google/go-containerregistry/internal/estargz" - ggzip "github.com/google/go-containerregistry/internal/gzip" - "github.com/google/go-containerregistry/internal/zstd" - "github.com/google/go-containerregistry/pkg/compression" - "github.com/google/go-containerregistry/pkg/logs" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/types" -) - -type layer struct { - digest v1.Hash - diffID v1.Hash - size int64 - compressedopener Opener - uncompressedopener Opener - compression compression.Compression - compressionLevel int - annotations map[string]string - estgzopts []estargz.Option - mediaType types.MediaType -} - -// Descriptor implements partial.withDescriptor. -func (l *layer) Descriptor() (*v1.Descriptor, error) { - digest, err := l.Digest() - if err != nil { - return nil, err - } - return &v1.Descriptor{ - Size: l.size, - Digest: digest, - Annotations: l.annotations, - MediaType: l.mediaType, - }, nil -} - -// Digest implements v1.Layer -func (l *layer) Digest() (v1.Hash, error) { - return l.digest, nil -} - -// DiffID implements v1.Layer -func (l *layer) DiffID() (v1.Hash, error) { - return l.diffID, nil -} - -// Compressed implements v1.Layer -func (l *layer) Compressed() (io.ReadCloser, error) { - return l.compressedopener() -} - -// Uncompressed implements v1.Layer -func (l *layer) Uncompressed() (io.ReadCloser, error) { - return l.uncompressedopener() -} - -// Size implements v1.Layer -func (l *layer) Size() (int64, error) { - return l.size, nil -} - -// MediaType implements v1.Layer -func (l *layer) MediaType() (types.MediaType, error) { - return l.mediaType, nil -} - -// LayerOption applies options to layer -type LayerOption func(*layer) - -// WithCompression is a functional option for overriding the default -// compression algorithm used for compressing uncompressed tarballs. -// Please note that WithCompression(compression.ZStd) should be used -// in conjunction with WithMediaType(types.OCILayerZStd) -func WithCompression(comp compression.Compression) LayerOption { - return func(l *layer) { - switch comp { - case compression.ZStd: - l.compression = compression.ZStd - case compression.GZip: - l.compression = compression.GZip - case compression.None: - logs.Warn.Printf("Compression type 'none' is not supported for tarball layers; using gzip compression.") - l.compression = compression.GZip - default: - logs.Warn.Printf("Unexpected compression type for WithCompression(): %s; using gzip compression instead.", comp) - l.compression = compression.GZip - } - } -} - -// WithCompressionLevel is a functional option for overriding the default -// compression level used for compressing uncompressed tarballs. -func WithCompressionLevel(level int) LayerOption { - return func(l *layer) { - l.compressionLevel = level - } -} - -// WithMediaType is a functional option for overriding the layer's media type. -func WithMediaType(mt types.MediaType) LayerOption { - return func(l *layer) { - l.mediaType = mt - } -} - -// WithCompressedCaching is a functional option that overrides the -// logic for accessing the compressed bytes to memoize the result -// and avoid expensive repeated gzips. -func WithCompressedCaching(l *layer) { - var once sync.Once - var err error - - buf := bytes.NewBuffer(nil) - og := l.compressedopener - - l.compressedopener = func() (io.ReadCloser, error) { - once.Do(func() { - var rc io.ReadCloser - rc, err = og() - if err == nil { - defer rc.Close() - _, err = io.Copy(buf, rc) - } - }) - if err != nil { - return nil, err - } - - return io.NopCloser(bytes.NewBuffer(buf.Bytes())), nil - } -} - -// WithEstargzOptions is a functional option that allow the caller to pass -// through estargz.Options to the underlying compression layer. This is -// only meaningful when estargz is enabled. -// -// Deprecated: WithEstargz is deprecated, and will be removed in a future release. -func WithEstargzOptions(opts ...estargz.Option) LayerOption { - return func(l *layer) { - l.estgzopts = opts - } -} - -// WithEstargz is a functional option that explicitly enables estargz support. -// -// Deprecated: WithEstargz is deprecated, and will be removed in a future release. -func WithEstargz(l *layer) { - oguncompressed := l.uncompressedopener - estargz := func() (io.ReadCloser, error) { - crc, err := oguncompressed() - if err != nil { - return nil, err - } - eopts := append(l.estgzopts, estargz.WithCompressionLevel(l.compressionLevel)) - rc, h, err := gestargz.ReadCloser(crc, eopts...) - if err != nil { - return nil, err - } - l.annotations[estargz.TOCJSONDigestAnnotation] = h.String() - return &and.ReadCloser{ - Reader: rc, - CloseFunc: func() error { - err := rc.Close() - if err != nil { - return err - } - // As an optimization, leverage the DiffID exposed by the estargz ReadCloser - l.diffID, err = v1.NewHash(rc.DiffID().String()) - return err - }, - }, nil - } - uncompressed := func() (io.ReadCloser, error) { - urc, err := estargz() - if err != nil { - return nil, err - } - return ggzip.UnzipReadCloser(urc) - } - - l.compressedopener = estargz - l.uncompressedopener = uncompressed -} - -// LayerFromFile returns a v1.Layer given a tarball -func LayerFromFile(path string, opts ...LayerOption) (v1.Layer, error) { - opener := func() (io.ReadCloser, error) { - return os.Open(path) - } - return LayerFromOpener(opener, opts...) -} - -// LayerFromOpener returns a v1.Layer given an Opener function. -// The Opener may return either an uncompressed tarball (common), -// or a compressed tarball (uncommon). -// -// When using this in conjunction with something like remote.Write -// the uncompressed path may end up gzipping things multiple times: -// 1. Compute the layer SHA256 -// 2. Upload the compressed layer. -// -// Since gzip can be expensive, we support an option to memoize the -// compression that can be passed here: tarball.WithCompressedCaching -func LayerFromOpener(opener Opener, opts ...LayerOption) (v1.Layer, error) { - comp, err := comp.GetCompression(opener) - if err != nil { - return nil, err - } - - layer := &layer{ - compression: compression.GZip, - compressionLevel: gzip.BestSpeed, - annotations: make(map[string]string, 1), - mediaType: types.DockerLayer, - } - - if estgz := os.Getenv("GGCR_EXPERIMENT_ESTARGZ"); estgz == "1" { - logs.Warn.Println("GGCR_EXPERIMENT_ESTARGZ is deprecated, and will be removed in a future release.") - opts = append([]LayerOption{WithEstargz}, opts...) - } - - switch comp { - case compression.GZip: - layer.compressedopener = opener - layer.uncompressedopener = func() (io.ReadCloser, error) { - urc, err := opener() - if err != nil { - return nil, err - } - return ggzip.UnzipReadCloser(urc) - } - case compression.ZStd: - layer.compressedopener = opener - layer.uncompressedopener = func() (io.ReadCloser, error) { - urc, err := opener() - if err != nil { - return nil, err - } - return zstd.UnzipReadCloser(urc) - } - default: - layer.uncompressedopener = opener - layer.compressedopener = func() (io.ReadCloser, error) { - crc, err := opener() - if err != nil { - return nil, err - } - - if layer.compression == compression.ZStd { - return zstd.ReadCloserLevel(crc, layer.compressionLevel), nil - } - - return ggzip.ReadCloserLevel(crc, layer.compressionLevel), nil - } - } - - for _, opt := range opts { - opt(layer) - } - - // Warn if media type does not match compression - var mediaTypeMismatch = false - switch layer.compression { - case compression.GZip: - mediaTypeMismatch = - layer.mediaType != types.OCILayer && - layer.mediaType != types.OCIRestrictedLayer && - layer.mediaType != types.DockerLayer - - case compression.ZStd: - mediaTypeMismatch = layer.mediaType != types.OCILayerZStd - } - - if mediaTypeMismatch { - logs.Warn.Printf("Unexpected mediaType (%s) for selected compression in %s in LayerFromOpener().", layer.mediaType, layer.compression) - } - - if layer.digest, layer.size, err = computeDigest(layer.compressedopener); err != nil { - return nil, err - } - - empty := v1.Hash{} - if layer.diffID == empty { - if layer.diffID, err = computeDiffID(layer.uncompressedopener); err != nil { - return nil, err - } - } - - return layer, nil -} - -// LayerFromReader returns a v1.Layer given a io.Reader. -// -// The reader's contents are read and buffered to a temp file in the process. -// -// Deprecated: Use LayerFromOpener or stream.NewLayer instead, if possible. -func LayerFromReader(reader io.Reader, opts ...LayerOption) (v1.Layer, error) { - tmp, err := os.CreateTemp("", "") - if err != nil { - return nil, fmt.Errorf("creating temp file to buffer reader: %w", err) - } - if _, err := io.Copy(tmp, reader); err != nil { - return nil, fmt.Errorf("writing temp file to buffer reader: %w", err) - } - return LayerFromFile(tmp.Name(), opts...) -} - -func computeDigest(opener Opener) (v1.Hash, int64, error) { - rc, err := opener() - if err != nil { - return v1.Hash{}, 0, err - } - defer rc.Close() - - return v1.SHA256(rc) -} - -func computeDiffID(opener Opener) (v1.Hash, error) { - rc, err := opener() - if err != nil { - return v1.Hash{}, err - } - defer rc.Close() - - digest, _, err := v1.SHA256(rc) - return digest, err -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/tarball/write.go b/vendor/github.com/google/go-containerregistry/pkg/v1/tarball/write.go deleted file mode 100644 index e607df164..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/tarball/write.go +++ /dev/null @@ -1,457 +0,0 @@ -// Copyright 2018 Google LLC 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 tarball - -import ( - "archive/tar" - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "os" - "sort" - "strings" - - "github.com/google/go-containerregistry/pkg/name" - v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/google/go-containerregistry/pkg/v1/partial" -) - -// WriteToFile writes in the compressed format to a tarball, on disk. -// This is just syntactic sugar wrapping tarball.Write with a new file. -func WriteToFile(p string, ref name.Reference, img v1.Image, opts ...WriteOption) error { - w, err := os.Create(p) - if err != nil { - return err - } - defer w.Close() - - return Write(ref, img, w, opts...) -} - -// MultiWriteToFile writes in the compressed format to a tarball, on disk. -// This is just syntactic sugar wrapping tarball.MultiWrite with a new file. -func MultiWriteToFile(p string, tagToImage map[name.Tag]v1.Image, opts ...WriteOption) error { - refToImage := make(map[name.Reference]v1.Image, len(tagToImage)) - for i, d := range tagToImage { - refToImage[i] = d - } - return MultiRefWriteToFile(p, refToImage, opts...) -} - -// MultiRefWriteToFile writes in the compressed format to a tarball, on disk. -// This is just syntactic sugar wrapping tarball.MultiRefWrite with a new file. -func MultiRefWriteToFile(p string, refToImage map[name.Reference]v1.Image, opts ...WriteOption) error { - w, err := os.Create(p) - if err != nil { - return err - } - defer w.Close() - - return MultiRefWrite(refToImage, w, opts...) -} - -// Write is a wrapper to write a single image and tag to a tarball. -func Write(ref name.Reference, img v1.Image, w io.Writer, opts ...WriteOption) error { - return MultiRefWrite(map[name.Reference]v1.Image{ref: img}, w, opts...) -} - -// MultiWrite writes the contents of each image to the provided writer, in the compressed format. -// The contents are written in the following format: -// One manifest.json file at the top level containing information about several images. -// One file for each layer, named after the layer's SHA. -// One file for the config blob, named after its SHA. -func MultiWrite(tagToImage map[name.Tag]v1.Image, w io.Writer, opts ...WriteOption) error { - refToImage := make(map[name.Reference]v1.Image, len(tagToImage)) - for i, d := range tagToImage { - refToImage[i] = d - } - return MultiRefWrite(refToImage, w, opts...) -} - -// MultiRefWrite writes the contents of each image to the provided writer, in the compressed format. -// The contents are written in the following format: -// One manifest.json file at the top level containing information about several images. -// One file for each layer, named after the layer's SHA. -// One file for the config blob, named after its SHA. -func MultiRefWrite(refToImage map[name.Reference]v1.Image, w io.Writer, opts ...WriteOption) error { - // process options - o := &writeOptions{ - updates: nil, - } - for _, option := range opts { - if err := option(o); err != nil { - return err - } - } - - imageToTags := dedupRefToImage(refToImage) - size, mBytes, err := getSizeAndManifest(imageToTags) - if err != nil { - return sendUpdateReturn(o, err) - } - - return writeImagesToTar(imageToTags, mBytes, size, w, o) -} - -// sendUpdateReturn return the passed in error message, also sending on update channel, if it exists -func sendUpdateReturn(o *writeOptions, err error) error { - if o != nil && o.updates != nil { - o.updates <- v1.Update{ - Error: err, - } - } - return err -} - -// sendProgressWriterReturn return the passed in error message, also sending on update channel, if it exists, along with downloaded information -func sendProgressWriterReturn(pw *progressWriter, err error) error { - if pw != nil { - return pw.Error(err) - } - return err -} - -// writeImagesToTar writes the images to the tarball -func writeImagesToTar(imageToTags map[v1.Image][]string, m []byte, size int64, w io.Writer, o *writeOptions) (err error) { - if w == nil { - return sendUpdateReturn(o, errors.New("must pass valid writer")) - } - - tw := w - var pw *progressWriter - - // we only calculate the sizes and use a progressWriter if we were provided - // an option with a progress channel - if o != nil && o.updates != nil { - pw = &progressWriter{ - w: w, - updates: o.updates, - size: size, - } - tw = pw - } - - tf := tar.NewWriter(tw) - defer tf.Close() - - seenLayerDigests := make(map[string]struct{}) - - for img := range imageToTags { - // Write the config. - cfgName, err := img.ConfigName() - if err != nil { - return sendProgressWriterReturn(pw, err) - } - cfgBlob, err := img.RawConfigFile() - if err != nil { - return sendProgressWriterReturn(pw, err) - } - if err := writeTarEntry(tf, cfgName.String(), bytes.NewReader(cfgBlob), int64(len(cfgBlob))); err != nil { - return sendProgressWriterReturn(pw, err) - } - - // Write the layers. - layers, err := img.Layers() - if err != nil { - return sendProgressWriterReturn(pw, err) - } - layerFiles := make([]string, len(layers)) - for i, l := range layers { - d, err := l.Digest() - if err != nil { - return sendProgressWriterReturn(pw, err) - } - // Munge the file name to appease ancient technology. - // - // tar assumes anything with a colon is a remote tape drive: - // https://www.gnu.org/software/tar/manual/html_section/tar_45.html - // Drop the algorithm prefix, e.g. "sha256:" - hex := d.Hex - - // gunzip expects certain file extensions: - // https://www.gnu.org/software/gzip/manual/html_node/Overview.html - layerFiles[i] = fmt.Sprintf("%s.tar.gz", hex) - - if _, ok := seenLayerDigests[hex]; ok { - continue - } - seenLayerDigests[hex] = struct{}{} - - r, err := l.Compressed() - if err != nil { - return sendProgressWriterReturn(pw, err) - } - blobSize, err := l.Size() - if err != nil { - return sendProgressWriterReturn(pw, err) - } - - if err := writeTarEntry(tf, layerFiles[i], r, blobSize); err != nil { - return sendProgressWriterReturn(pw, err) - } - } - } - if err := writeTarEntry(tf, "manifest.json", bytes.NewReader(m), int64(len(m))); err != nil { - return sendProgressWriterReturn(pw, err) - } - - // be sure to close the tar writer so everything is flushed out before we send our EOF - if err := tf.Close(); err != nil { - return sendProgressWriterReturn(pw, err) - } - // send an EOF to indicate finished on the channel, but nil as our return error - _ = sendProgressWriterReturn(pw, io.EOF) - return nil -} - -// calculateManifest calculates the manifest and optionally the size of the tar file -func calculateManifest(imageToTags map[v1.Image][]string) (m Manifest, err error) { - if len(imageToTags) == 0 { - return nil, errors.New("set of images is empty") - } - - for img, tags := range imageToTags { - cfgName, err := img.ConfigName() - if err != nil { - return nil, err - } - - // Store foreign layer info. - layerSources := make(map[v1.Hash]v1.Descriptor) - - // Write the layers. - layers, err := img.Layers() - if err != nil { - return nil, err - } - layerFiles := make([]string, len(layers)) - for i, l := range layers { - d, err := l.Digest() - if err != nil { - return nil, err - } - // Munge the file name to appease ancient technology. - // - // tar assumes anything with a colon is a remote tape drive: - // https://www.gnu.org/software/tar/manual/html_section/tar_45.html - // Drop the algorithm prefix, e.g. "sha256:" - hex := d.Hex - - // gunzip expects certain file extensions: - // https://www.gnu.org/software/gzip/manual/html_node/Overview.html - layerFiles[i] = fmt.Sprintf("%s.tar.gz", hex) - - // Add to LayerSources if it's a foreign layer. - desc, err := partial.BlobDescriptor(img, d) - if err != nil { - return nil, err - } - if !desc.MediaType.IsDistributable() { - diffid, err := partial.BlobToDiffID(img, d) - if err != nil { - return nil, err - } - layerSources[diffid] = *desc - } - } - - // Generate the tar descriptor and write it. - m = append(m, Descriptor{ - Config: cfgName.String(), - RepoTags: tags, - Layers: layerFiles, - LayerSources: layerSources, - }) - } - // sort by name of the repotags so it is consistent. Alternatively, we could sort by hash of the - // descriptor, but that would make it hard for humans to process - sort.Slice(m, func(i, j int) bool { - return strings.Join(m[i].RepoTags, ",") < strings.Join(m[j].RepoTags, ",") - }) - - return m, nil -} - -// CalculateSize calculates the expected complete size of the output tar file -func CalculateSize(refToImage map[name.Reference]v1.Image) (size int64, err error) { - imageToTags := dedupRefToImage(refToImage) - size, _, err = getSizeAndManifest(imageToTags) - return size, err -} - -func getSizeAndManifest(imageToTags map[v1.Image][]string) (int64, []byte, error) { - m, err := calculateManifest(imageToTags) - if err != nil { - return 0, nil, fmt.Errorf("unable to calculate manifest: %w", err) - } - mBytes, err := json.Marshal(m) - if err != nil { - return 0, nil, fmt.Errorf("could not marshall manifest to bytes: %w", err) - } - - size, err := calculateTarballSize(imageToTags, mBytes) - if err != nil { - return 0, nil, fmt.Errorf("error calculating tarball size: %w", err) - } - return size, mBytes, nil -} - -// calculateTarballSize calculates the size of the tar file -func calculateTarballSize(imageToTags map[v1.Image][]string, mBytes []byte) (size int64, err error) { - seenLayerDigests := make(map[string]struct{}) - for img, name := range imageToTags { - manifest, err := img.Manifest() - if err != nil { - return size, fmt.Errorf("unable to get manifest for img %s: %w", name, err) - } - size += calculateSingleFileInTarSize(manifest.Config.Size) - for _, l := range manifest.Layers { - hex := l.Digest.Hex - if _, ok := seenLayerDigests[hex]; ok { - continue - } - seenLayerDigests[hex] = struct{}{} - size += calculateSingleFileInTarSize(l.Size) - } - } - // add the manifest - size += calculateSingleFileInTarSize(int64(len(mBytes))) - - // add the two padding blocks that indicate end of a tar file - size += 1024 - return size, nil -} - -func dedupRefToImage(refToImage map[name.Reference]v1.Image) map[v1.Image][]string { - imageToTags := make(map[v1.Image][]string) - - for ref, img := range refToImage { - if tag, ok := ref.(name.Tag); ok { - if tags, ok := imageToTags[img]; !ok || tags == nil { - imageToTags[img] = []string{} - } - // Docker cannot load tarballs without an explicit tag: - // https://github.com/google/go-containerregistry/issues/890 - // - // We can't use the fully qualified tag.Name() because of rules_docker: - // https://github.com/google/go-containerregistry/issues/527 - // - // If the tag is "latest", but tag.String() doesn't end in ":latest", - // just append it. Kind of gross, but should work for now. - ts := tag.String() - if tag.Identifier() == name.DefaultTag && !strings.HasSuffix(ts, ":"+name.DefaultTag) { - ts = fmt.Sprintf("%s:%s", ts, name.DefaultTag) - } - imageToTags[img] = append(imageToTags[img], ts) - } else if _, ok := imageToTags[img]; !ok { - imageToTags[img] = nil - } - } - - return imageToTags -} - -// writeTarEntry writes a file to the provided writer with a corresponding tar header -func writeTarEntry(tf *tar.Writer, path string, r io.Reader, size int64) error { - hdr := &tar.Header{ - Mode: 0644, - Typeflag: tar.TypeReg, - Size: size, - Name: path, - } - if err := tf.WriteHeader(hdr); err != nil { - return err - } - _, err := io.Copy(tf, r) - return err -} - -// ComputeManifest get the manifest.json that will be written to the tarball -// for multiple references -func ComputeManifest(refToImage map[name.Reference]v1.Image) (Manifest, error) { - imageToTags := dedupRefToImage(refToImage) - return calculateManifest(imageToTags) -} - -// WriteOption a function option to pass to Write() -type WriteOption func(*writeOptions) error -type writeOptions struct { - updates chan<- v1.Update -} - -// WithProgress create a WriteOption for passing to Write() that enables -// a channel to receive updates as they are downloaded and written to disk. -func WithProgress(updates chan<- v1.Update) WriteOption { - return func(o *writeOptions) error { - o.updates = updates - return nil - } -} - -// progressWriter is a writer which will send the download progress -type progressWriter struct { - w io.Writer - updates chan<- v1.Update - size, complete int64 -} - -func (pw *progressWriter) Write(p []byte) (int, error) { - n, err := pw.w.Write(p) - if err != nil { - return n, err - } - - pw.complete += int64(n) - - pw.updates <- v1.Update{ - Total: pw.size, - Complete: pw.complete, - } - - return n, err -} - -func (pw *progressWriter) Error(err error) error { - pw.updates <- v1.Update{ - Total: pw.size, - Complete: pw.complete, - Error: err, - } - return err -} - -func (pw *progressWriter) Close() error { - pw.updates <- v1.Update{ - Total: pw.size, - Complete: pw.complete, - Error: io.EOF, - } - return io.EOF -} - -// calculateSingleFileInTarSize calculate the size a file will take up in a tar archive, -// given the input data. Provided by rounding up to nearest whole block (512) -// and adding header 512 -func calculateSingleFileInTarSize(in int64) (out int64) { - // doing this manually, because math.Round() works with float64 - out += in - if remainder := out % 512; remainder != 0 { - out += (512 - remainder) - } - out += 512 - return out -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/types/types.go b/vendor/github.com/google/go-containerregistry/pkg/v1/types/types.go deleted file mode 100644 index c86657d7b..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/types/types.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2018 Google LLC 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 types holds common OCI media types. -package types - -// MediaType is an enumeration of the supported mime types that an element of an image might have. -type MediaType string - -// The collection of known MediaType values. -const ( - OCIContentDescriptor MediaType = "application/vnd.oci.descriptor.v1+json" - OCIImageIndex MediaType = "application/vnd.oci.image.index.v1+json" - OCIManifestSchema1 MediaType = "application/vnd.oci.image.manifest.v1+json" - OCIConfigJSON MediaType = "application/vnd.oci.image.config.v1+json" - OCILayer MediaType = "application/vnd.oci.image.layer.v1.tar+gzip" - OCILayerZStd MediaType = "application/vnd.oci.image.layer.v1.tar+zstd" - OCIRestrictedLayer MediaType = "application/vnd.oci.image.layer.nondistributable.v1.tar+gzip" - OCIUncompressedLayer MediaType = "application/vnd.oci.image.layer.v1.tar" - OCIUncompressedRestrictedLayer MediaType = "application/vnd.oci.image.layer.nondistributable.v1.tar" - - DockerManifestSchema1 MediaType = "application/vnd.docker.distribution.manifest.v1+json" - DockerManifestSchema1Signed MediaType = "application/vnd.docker.distribution.manifest.v1+prettyjws" - DockerManifestSchema2 MediaType = "application/vnd.docker.distribution.manifest.v2+json" - DockerManifestList MediaType = "application/vnd.docker.distribution.manifest.list.v2+json" - DockerLayer MediaType = "application/vnd.docker.image.rootfs.diff.tar.gzip" - DockerConfigJSON MediaType = "application/vnd.docker.container.image.v1+json" - DockerPluginConfig MediaType = "application/vnd.docker.plugin.v1+json" - DockerForeignLayer MediaType = "application/vnd.docker.image.rootfs.foreign.diff.tar.gzip" - DockerUncompressedLayer MediaType = "application/vnd.docker.image.rootfs.diff.tar" - - OCIVendorPrefix = "vnd.oci" - DockerVendorPrefix = "vnd.docker" -) - -// IsDistributable returns true if a layer is distributable, see: -// https://github.com/opencontainers/image-spec/blob/master/layer.md#non-distributable-layers -func (m MediaType) IsDistributable() bool { - switch m { - case DockerForeignLayer, OCIRestrictedLayer, OCIUncompressedRestrictedLayer: - return false - } - return true -} - -// IsImage returns true if the mediaType represents an image manifest, as opposed to something else, like an index. -func (m MediaType) IsImage() bool { - switch m { - case OCIManifestSchema1, DockerManifestSchema2: - return true - } - return false -} - -// IsIndex returns true if the mediaType represents an index, as opposed to something else, like an image. -func (m MediaType) IsIndex() bool { - switch m { - case OCIImageIndex, DockerManifestList: - return true - } - return false -} - -// IsConfig returns true if the mediaType represents a config, as opposed to something else, like an image. -func (m MediaType) IsConfig() bool { - switch m { - case OCIConfigJSON, DockerConfigJSON: - return true - } - return false -} - -func (m MediaType) IsSchema1() bool { - switch m { - case DockerManifestSchema1, DockerManifestSchema1Signed: - return true - } - return false -} - -func (m MediaType) IsLayer() bool { - switch m { - case DockerLayer, DockerUncompressedLayer, OCILayer, OCILayerZStd, OCIUncompressedLayer, DockerForeignLayer, OCIRestrictedLayer, OCIUncompressedRestrictedLayer: - return true - } - return false -} diff --git a/vendor/github.com/google/go-containerregistry/pkg/v1/zz_deepcopy_generated.go b/vendor/github.com/google/go-containerregistry/pkg/v1/zz_deepcopy_generated.go deleted file mode 100644 index a47b7475e..000000000 --- a/vendor/github.com/google/go-containerregistry/pkg/v1/zz_deepcopy_generated.go +++ /dev/null @@ -1,339 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -// Copyright 2018 Google LLC 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. - -// Code generated by deepcopy-gen. DO NOT EDIT. - -package v1 - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Config) DeepCopyInto(out *Config) { - *out = *in - if in.Cmd != nil { - in, out := &in.Cmd, &out.Cmd - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Healthcheck != nil { - in, out := &in.Healthcheck, &out.Healthcheck - *out = new(HealthConfig) - (*in).DeepCopyInto(*out) - } - if in.Entrypoint != nil { - in, out := &in.Entrypoint, &out.Entrypoint - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Env != nil { - in, out := &in.Env, &out.Env - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Labels != nil { - in, out := &in.Labels, &out.Labels - *out = make(map[string]string, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - if in.OnBuild != nil { - in, out := &in.OnBuild, &out.OnBuild - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Volumes != nil { - in, out := &in.Volumes, &out.Volumes - *out = make(map[string]struct{}, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - if in.ExposedPorts != nil { - in, out := &in.ExposedPorts, &out.ExposedPorts - *out = make(map[string]struct{}, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - if in.Shell != nil { - in, out := &in.Shell, &out.Shell - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Config. -func (in *Config) DeepCopy() *Config { - if in == nil { - return nil - } - out := new(Config) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ConfigFile) DeepCopyInto(out *ConfigFile) { - *out = *in - in.Created.DeepCopyInto(&out.Created) - if in.History != nil { - in, out := &in.History, &out.History - *out = make([]History, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - in.RootFS.DeepCopyInto(&out.RootFS) - in.Config.DeepCopyInto(&out.Config) - if in.OSFeatures != nil { - in, out := &in.OSFeatures, &out.OSFeatures - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConfigFile. -func (in *ConfigFile) DeepCopy() *ConfigFile { - if in == nil { - return nil - } - out := new(ConfigFile) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Descriptor) DeepCopyInto(out *Descriptor) { - *out = *in - out.Digest = in.Digest - if in.Data != nil { - in, out := &in.Data, &out.Data - *out = make([]byte, len(*in)) - copy(*out, *in) - } - if in.URLs != nil { - in, out := &in.URLs, &out.URLs - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Annotations != nil { - in, out := &in.Annotations, &out.Annotations - *out = make(map[string]string, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - if in.Platform != nil { - in, out := &in.Platform, &out.Platform - *out = new(Platform) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Descriptor. -func (in *Descriptor) DeepCopy() *Descriptor { - if in == nil { - return nil - } - out := new(Descriptor) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Hash) DeepCopyInto(out *Hash) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Hash. -func (in *Hash) DeepCopy() *Hash { - if in == nil { - return nil - } - out := new(Hash) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *HealthConfig) DeepCopyInto(out *HealthConfig) { - *out = *in - if in.Test != nil { - in, out := &in.Test, &out.Test - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HealthConfig. -func (in *HealthConfig) DeepCopy() *HealthConfig { - if in == nil { - return nil - } - out := new(HealthConfig) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *History) DeepCopyInto(out *History) { - *out = *in - in.Created.DeepCopyInto(&out.Created) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new History. -func (in *History) DeepCopy() *History { - if in == nil { - return nil - } - out := new(History) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *IndexManifest) DeepCopyInto(out *IndexManifest) { - *out = *in - if in.Manifests != nil { - in, out := &in.Manifests, &out.Manifests - *out = make([]Descriptor, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Annotations != nil { - in, out := &in.Annotations, &out.Annotations - *out = make(map[string]string, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - if in.Subject != nil { - in, out := &in.Subject, &out.Subject - *out = new(Descriptor) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IndexManifest. -func (in *IndexManifest) DeepCopy() *IndexManifest { - if in == nil { - return nil - } - out := new(IndexManifest) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Manifest) DeepCopyInto(out *Manifest) { - *out = *in - in.Config.DeepCopyInto(&out.Config) - if in.Layers != nil { - in, out := &in.Layers, &out.Layers - *out = make([]Descriptor, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Annotations != nil { - in, out := &in.Annotations, &out.Annotations - *out = make(map[string]string, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - if in.Subject != nil { - in, out := &in.Subject, &out.Subject - *out = new(Descriptor) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Manifest. -func (in *Manifest) DeepCopy() *Manifest { - if in == nil { - return nil - } - out := new(Manifest) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Platform) DeepCopyInto(out *Platform) { - *out = *in - if in.OSFeatures != nil { - in, out := &in.OSFeatures, &out.OSFeatures - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Features != nil { - in, out := &in.Features, &out.Features - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Platform. -func (in *Platform) DeepCopy() *Platform { - if in == nil { - return nil - } - out := new(Platform) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *RootFS) DeepCopyInto(out *RootFS) { - *out = *in - if in.DiffIDs != nil { - in, out := &in.DiffIDs, &out.DiffIDs - *out = make([]Hash, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RootFS. -func (in *RootFS) DeepCopy() *RootFS { - if in == nil { - return nil - } - out := new(RootFS) - in.DeepCopyInto(out) - return out -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Time. -func (in *Time) DeepCopy() *Time { - if in == nil { - return nil - } - out := new(Time) - in.DeepCopyInto(out) - return out -} diff --git a/vendor/github.com/jonboulle/clockwork/.editorconfig b/vendor/github.com/jonboulle/clockwork/.editorconfig deleted file mode 100644 index 4492e9f9f..000000000 --- a/vendor/github.com/jonboulle/clockwork/.editorconfig +++ /dev/null @@ -1,12 +0,0 @@ -root = true - -[*] -charset = utf-8 -end_of_line = lf -indent_size = 4 -indent_style = space -insert_final_newline = true -trim_trailing_whitespace = true - -[*.go] -indent_style = tab diff --git a/vendor/github.com/jonboulle/clockwork/.gitignore b/vendor/github.com/jonboulle/clockwork/.gitignore deleted file mode 100644 index 00852bd94..000000000 --- a/vendor/github.com/jonboulle/clockwork/.gitignore +++ /dev/null @@ -1,27 +0,0 @@ -/.idea/ - -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test - -*.swp diff --git a/vendor/github.com/jonboulle/clockwork/LICENSE b/vendor/github.com/jonboulle/clockwork/LICENSE deleted file mode 100644 index 5c304d1a4..000000000 --- a/vendor/github.com/jonboulle/clockwork/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - 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 "{}" - 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 - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - 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. diff --git a/vendor/github.com/jonboulle/clockwork/README.md b/vendor/github.com/jonboulle/clockwork/README.md deleted file mode 100644 index 42970da80..000000000 --- a/vendor/github.com/jonboulle/clockwork/README.md +++ /dev/null @@ -1,80 +0,0 @@ -# clockwork - -[![Mentioned in Awesome Go](https://awesome.re/mentioned-badge-flat.svg)](https://github.com/avelino/awesome-go#utilities) - -[![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/jonboulle/clockwork/ci.yaml?style=flat-square)](https://github.com/jonboulle/clockwork/actions?query=workflow%3ACI) -[![Go Report Card](https://goreportcard.com/badge/github.com/jonboulle/clockwork?style=flat-square)](https://goreportcard.com/report/github.com/jonboulle/clockwork) -![Go Version](https://img.shields.io/badge/go%20version-%3E=1.15-61CFDD.svg?style=flat-square) -[![go.dev reference](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat-square)](https://pkg.go.dev/mod/github.com/jonboulle/clockwork) - -**A simple fake clock for Go.** - - -## Usage - -Replace uses of the `time` package with the `clockwork.Clock` interface instead. - -For example, instead of using `time.Sleep` directly: - -```go -func myFunc() { - time.Sleep(3 * time.Second) - doSomething() -} -``` - -Inject a clock and use its `Sleep` method instead: - -```go -func myFunc(clock clockwork.Clock) { - clock.Sleep(3 * time.Second) - doSomething() -} -``` - -Now you can easily test `myFunc` with a `FakeClock`: - -```go -func TestMyFunc(t *testing.T) { - c := clockwork.NewFakeClock() - - // Start our sleepy function - var wg sync.WaitGroup - wg.Add(1) - go func() { - myFunc(c) - wg.Done() - }() - - // Ensure we wait until myFunc is sleeping - c.BlockUntil(1) - - assertState() - - // Advance the FakeClock forward in time - c.Advance(3 * time.Second) - - // Wait until the function completes - wg.Wait() - - assertState() -} -``` - -and in production builds, simply inject the real clock instead: - -```go -myFunc(clockwork.NewRealClock()) -``` - -See [example_test.go](example_test.go) for a full example. - - -# Credits - -clockwork is inspired by @wickman's [threaded fake clock](https://gist.github.com/wickman/3840816), and the [Golang playground](https://blog.golang.org/playground#TOC_3.1.) - - -## License - -Apache License, Version 2.0. Please see [License File](LICENSE) for more information. diff --git a/vendor/github.com/jonboulle/clockwork/clockwork.go b/vendor/github.com/jonboulle/clockwork/clockwork.go deleted file mode 100644 index 3206b36e4..000000000 --- a/vendor/github.com/jonboulle/clockwork/clockwork.go +++ /dev/null @@ -1,349 +0,0 @@ -package clockwork - -import ( - "context" - "sort" - "sync" - "time" -) - -// Clock provides an interface that packages can use instead of directly using -// the [time] module, so that chronology-related behavior can be tested. -type Clock interface { - After(d time.Duration) <-chan time.Time - Sleep(d time.Duration) - Now() time.Time - Since(t time.Time) time.Duration - NewTicker(d time.Duration) Ticker - NewTimer(d time.Duration) Timer - AfterFunc(d time.Duration, f func()) Timer -} - -// FakeClock provides an interface for a clock which can be manually advanced -// through time. -// -// FakeClock maintains a list of "waiters," which consists of all callers -// waiting on the underlying clock (i.e. Tickers and Timers including callers of -// Sleep or After). Users can call BlockUntil to block until the clock has an -// expected number of waiters. -type FakeClock interface { - Clock - // Advance advances the FakeClock to a new point in time, ensuring any existing - // waiters are notified appropriately before returning. - Advance(d time.Duration) - // BlockUntil blocks until the FakeClock has the given number of waiters. - BlockUntil(waiters int) -} - -// NewRealClock returns a Clock which simply delegates calls to the actual time -// package; it should be used by packages in production. -func NewRealClock() Clock { - return &realClock{} -} - -// NewFakeClock returns a FakeClock implementation which can be -// manually advanced through time for testing. The initial time of the -// FakeClock will be the current system time. -// -// Tests that require a deterministic time must use NewFakeClockAt. -func NewFakeClock() FakeClock { - return NewFakeClockAt(time.Now()) -} - -// NewFakeClockAt returns a FakeClock initialised at the given time.Time. -func NewFakeClockAt(t time.Time) FakeClock { - return &fakeClock{ - time: t, - } -} - -type realClock struct{} - -func (rc *realClock) After(d time.Duration) <-chan time.Time { - return time.After(d) -} - -func (rc *realClock) Sleep(d time.Duration) { - time.Sleep(d) -} - -func (rc *realClock) Now() time.Time { - return time.Now() -} - -func (rc *realClock) Since(t time.Time) time.Duration { - return rc.Now().Sub(t) -} - -func (rc *realClock) NewTicker(d time.Duration) Ticker { - return realTicker{time.NewTicker(d)} -} - -func (rc *realClock) NewTimer(d time.Duration) Timer { - return realTimer{time.NewTimer(d)} -} - -func (rc *realClock) AfterFunc(d time.Duration, f func()) Timer { - return realTimer{time.AfterFunc(d, f)} -} - -type fakeClock struct { - // l protects all attributes of the clock, including all attributes of all - // waiters and blockers. - l sync.RWMutex - waiters []expirer - blockers []*blocker - time time.Time -} - -// blocker is a caller of BlockUntil. -type blocker struct { - count int - - // ch is closed when the underlying clock has the specificed number of blockers. - ch chan struct{} -} - -// expirer is a timer or ticker that expires at some point in the future. -type expirer interface { - // expire the expirer at the given time, returning the desired duration until - // the next expiration, if any. - expire(now time.Time) (next *time.Duration) - - // Get and set the expiration time. - expiry() time.Time - setExpiry(time.Time) -} - -// After mimics [time.After]; it waits for the given duration to elapse on the -// fakeClock, then sends the current time on the returned channel. -func (fc *fakeClock) After(d time.Duration) <-chan time.Time { - return fc.NewTimer(d).Chan() -} - -// Sleep blocks until the given duration has passed on the fakeClock. -func (fc *fakeClock) Sleep(d time.Duration) { - <-fc.After(d) -} - -// Now returns the current time of the fakeClock -func (fc *fakeClock) Now() time.Time { - fc.l.RLock() - defer fc.l.RUnlock() - return fc.time -} - -// Since returns the duration that has passed since the given time on the -// fakeClock. -func (fc *fakeClock) Since(t time.Time) time.Duration { - return fc.Now().Sub(t) -} - -// NewTicker returns a Ticker that will expire only after calls to -// fakeClock.Advance() have moved the clock past the given duration. -func (fc *fakeClock) NewTicker(d time.Duration) Ticker { - var ft *fakeTicker - ft = &fakeTicker{ - firer: newFirer(), - d: d, - reset: func(d time.Duration) { fc.set(ft, d) }, - stop: func() { fc.stop(ft) }, - } - fc.set(ft, d) - return ft -} - -// NewTimer returns a Timer that will fire only after calls to -// fakeClock.Advance() have moved the clock past the given duration. -func (fc *fakeClock) NewTimer(d time.Duration) Timer { - return fc.newTimer(d, nil) -} - -// AfterFunc mimics [time.AfterFunc]; it returns a Timer that will invoke the -// given function only after calls to fakeClock.Advance() have moved the clock -// past the given duration. -func (fc *fakeClock) AfterFunc(d time.Duration, f func()) Timer { - return fc.newTimer(d, f) -} - -// newTimer returns a new timer, using an optional afterFunc. -func (fc *fakeClock) newTimer(d time.Duration, afterfunc func()) *fakeTimer { - var ft *fakeTimer - ft = &fakeTimer{ - firer: newFirer(), - reset: func(d time.Duration) bool { - fc.l.Lock() - defer fc.l.Unlock() - // fc.l must be held across the calls to stopExpirer & setExpirer. - stopped := fc.stopExpirer(ft) - fc.setExpirer(ft, d) - return stopped - }, - stop: func() bool { return fc.stop(ft) }, - - afterFunc: afterfunc, - } - fc.set(ft, d) - return ft -} - -// Advance advances fakeClock to a new point in time, ensuring waiters and -// blockers are notified appropriately before returning. -func (fc *fakeClock) Advance(d time.Duration) { - fc.l.Lock() - defer fc.l.Unlock() - end := fc.time.Add(d) - // Expire the earliest waiter until the earliest waiter's expiration is after - // end. - // - // We don't iterate because the callback of the waiter might register a new - // waiter, so the list of waiters might change as we execute this. - for len(fc.waiters) > 0 && !end.Before(fc.waiters[0].expiry()) { - w := fc.waiters[0] - fc.waiters = fc.waiters[1:] - - // Use the waiter's expriation as the current time for this expiration. - now := w.expiry() - fc.time = now - if d := w.expire(now); d != nil { - // Set the new exipration if needed. - fc.setExpirer(w, *d) - } - } - fc.time = end -} - -// BlockUntil blocks until the fakeClock has the given number of waiters. -// -// Prefer BlockUntilContext, which offers context cancellation to prevent -// deadlock. -// -// Deprecation warning: This function might be deprecated in later versions. -func (fc *fakeClock) BlockUntil(n int) { - b := fc.newBlocker(n) - if b == nil { - return - } - <-b.ch -} - -// BlockUntilContext blocks until the fakeClock has the given number of waiters -// or the context is cancelled. -func (fc *fakeClock) BlockUntilContext(ctx context.Context, n int) error { - b := fc.newBlocker(n) - if b == nil { - return nil - } - - select { - case <-b.ch: - return nil - case <-ctx.Done(): - return ctx.Err() - } -} - -func (fc *fakeClock) newBlocker(n int) *blocker { - fc.l.Lock() - defer fc.l.Unlock() - // Fast path: we already have >= n waiters. - if len(fc.waiters) >= n { - return nil - } - // Set up a new blocker to wait for more waiters. - b := &blocker{ - count: n, - ch: make(chan struct{}), - } - fc.blockers = append(fc.blockers, b) - return b -} - -// stop stops an expirer, returning true if the expirer was stopped. -func (fc *fakeClock) stop(e expirer) bool { - fc.l.Lock() - defer fc.l.Unlock() - return fc.stopExpirer(e) -} - -// stopExpirer stops an expirer, returning true if the expirer was stopped. -// -// The caller must hold fc.l. -func (fc *fakeClock) stopExpirer(e expirer) bool { - for i, t := range fc.waiters { - if t == e { - // Remove element, maintaining order. - copy(fc.waiters[i:], fc.waiters[i+1:]) - fc.waiters[len(fc.waiters)-1] = nil - fc.waiters = fc.waiters[:len(fc.waiters)-1] - return true - } - } - return false -} - -// set sets an expirer to expire at a future point in time. -func (fc *fakeClock) set(e expirer, d time.Duration) { - fc.l.Lock() - defer fc.l.Unlock() - fc.setExpirer(e, d) -} - -// setExpirer sets an expirer to expire at a future point in time. -// -// The caller must hold fc.l. -func (fc *fakeClock) setExpirer(e expirer, d time.Duration) { - if d.Nanoseconds() <= 0 { - // special case - trigger immediately, never reset. - // - // TODO: Explain what cases this covers. - e.expire(fc.time) - return - } - // Add the expirer to the set of waiters and notify any blockers. - e.setExpiry(fc.time.Add(d)) - fc.waiters = append(fc.waiters, e) - sort.Slice(fc.waiters, func(i int, j int) bool { - return fc.waiters[i].expiry().Before(fc.waiters[j].expiry()) - }) - - // Notify blockers of our new waiter. - var blocked []*blocker - count := len(fc.waiters) - for _, b := range fc.blockers { - if b.count <= count { - close(b.ch) - continue - } - blocked = append(blocked, b) - } - fc.blockers = blocked -} - -// firer is used by fakeTimer and fakeTicker used to help implement expirer. -type firer struct { - // The channel associated with the firer, used to send expriation times. - c chan time.Time - - // The time when the firer expires. Only meaningful if the firer is currently - // one of a fakeClock's waiters. - exp time.Time -} - -func newFirer() firer { - return firer{c: make(chan time.Time, 1)} -} - -func (f *firer) Chan() <-chan time.Time { - return f.c -} - -// expiry implements expirer. -func (f *firer) expiry() time.Time { - return f.exp -} - -// setExpiry implements expirer. -func (f *firer) setExpiry(t time.Time) { - f.exp = t -} diff --git a/vendor/github.com/jonboulle/clockwork/context.go b/vendor/github.com/jonboulle/clockwork/context.go deleted file mode 100644 index edbb368f0..000000000 --- a/vendor/github.com/jonboulle/clockwork/context.go +++ /dev/null @@ -1,25 +0,0 @@ -package clockwork - -import ( - "context" -) - -// contextKey is private to this package so we can ensure uniqueness here. This -// type identifies context values provided by this package. -type contextKey string - -// keyClock provides a clock for injecting during tests. If absent, a real clock should be used. -var keyClock = contextKey("clock") // clockwork.Clock - -// AddToContext creates a derived context that references the specified clock. -func AddToContext(ctx context.Context, clock Clock) context.Context { - return context.WithValue(ctx, keyClock, clock) -} - -// FromContext extracts a clock from the context. If not present, a real clock is returned. -func FromContext(ctx context.Context) Clock { - if clock, ok := ctx.Value(keyClock).(Clock); ok { - return clock - } - return NewRealClock() -} diff --git a/vendor/github.com/jonboulle/clockwork/ticker.go b/vendor/github.com/jonboulle/clockwork/ticker.go deleted file mode 100644 index b68e4d777..000000000 --- a/vendor/github.com/jonboulle/clockwork/ticker.go +++ /dev/null @@ -1,48 +0,0 @@ -package clockwork - -import "time" - -// Ticker provides an interface which can be used instead of directly using -// [time.Ticker]. The real-time ticker t provides ticks through t.C which -// becomes t.Chan() to make this channel requirement definable in this -// interface. -type Ticker interface { - Chan() <-chan time.Time - Reset(d time.Duration) - Stop() -} - -type realTicker struct{ *time.Ticker } - -func (r realTicker) Chan() <-chan time.Time { - return r.C -} - -type fakeTicker struct { - firer - - // reset and stop provide the implementation of the respective exported - // functions. - reset func(d time.Duration) - stop func() - - // The duration of the ticker. - d time.Duration -} - -func (f *fakeTicker) Reset(d time.Duration) { - f.reset(d) -} - -func (f *fakeTicker) Stop() { - f.stop() -} - -func (f *fakeTicker) expire(now time.Time) *time.Duration { - // Never block on expiration. - select { - case f.c <- now: - default: - } - return &f.d -} diff --git a/vendor/github.com/jonboulle/clockwork/timer.go b/vendor/github.com/jonboulle/clockwork/timer.go deleted file mode 100644 index 6f928b3dd..000000000 --- a/vendor/github.com/jonboulle/clockwork/timer.go +++ /dev/null @@ -1,53 +0,0 @@ -package clockwork - -import "time" - -// Timer provides an interface which can be used instead of directly using -// [time.Timer]. The real-time timer t provides events through t.C which becomes -// t.Chan() to make this channel requirement definable in this interface. -type Timer interface { - Chan() <-chan time.Time - Reset(d time.Duration) bool - Stop() bool -} - -type realTimer struct{ *time.Timer } - -func (r realTimer) Chan() <-chan time.Time { - return r.C -} - -type fakeTimer struct { - firer - - // reset and stop provide the implmenetation of the respective exported - // functions. - reset func(d time.Duration) bool - stop func() bool - - // If present when the timer fires, the timer calls afterFunc in its own - // goroutine rather than sending the time on Chan(). - afterFunc func() -} - -func (f *fakeTimer) Reset(d time.Duration) bool { - return f.reset(d) -} - -func (f *fakeTimer) Stop() bool { - return f.stop() -} - -func (f *fakeTimer) expire(now time.Time) *time.Duration { - if f.afterFunc != nil { - go f.afterFunc() - return nil - } - - // Never block on expiration. - select { - case f.c <- now: - default: - } - return nil -} diff --git a/vendor/github.com/klauspost/compress/.gitattributes b/vendor/github.com/klauspost/compress/.gitattributes deleted file mode 100644 index 402433593..000000000 --- a/vendor/github.com/klauspost/compress/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -* -text -*.bin -text -diff diff --git a/vendor/github.com/klauspost/compress/.gitignore b/vendor/github.com/klauspost/compress/.gitignore deleted file mode 100644 index d31b37815..000000000 --- a/vendor/github.com/klauspost/compress/.gitignore +++ /dev/null @@ -1,32 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof -/s2/cmd/_s2sx/sfx-exe - -# Linux perf files -perf.data -perf.data.old - -# gdb history -.gdb_history diff --git a/vendor/github.com/klauspost/compress/.goreleaser.yml b/vendor/github.com/klauspost/compress/.goreleaser.yml deleted file mode 100644 index 4c28dff46..000000000 --- a/vendor/github.com/klauspost/compress/.goreleaser.yml +++ /dev/null @@ -1,127 +0,0 @@ -# This is an example goreleaser.yaml file with some sane defaults. -# Make sure to check the documentation at http://goreleaser.com -before: - hooks: - - ./gen.sh - - go install mvdan.cc/garble@v0.10.1 - -builds: - - - id: "s2c" - binary: s2c - main: ./s2/cmd/s2c/main.go - flags: - - -trimpath - env: - - CGO_ENABLED=0 - goos: - - aix - - linux - - freebsd - - netbsd - - windows - - darwin - goarch: - - 386 - - amd64 - - arm - - arm64 - - ppc64 - - ppc64le - - mips64 - - mips64le - goarm: - - 7 - gobinary: garble - - - id: "s2d" - binary: s2d - main: ./s2/cmd/s2d/main.go - flags: - - -trimpath - env: - - CGO_ENABLED=0 - goos: - - aix - - linux - - freebsd - - netbsd - - windows - - darwin - goarch: - - 386 - - amd64 - - arm - - arm64 - - ppc64 - - ppc64le - - mips64 - - mips64le - goarm: - - 7 - gobinary: garble - - - id: "s2sx" - binary: s2sx - main: ./s2/cmd/_s2sx/main.go - flags: - - -modfile=s2sx.mod - - -trimpath - env: - - CGO_ENABLED=0 - goos: - - aix - - linux - - freebsd - - netbsd - - windows - - darwin - goarch: - - 386 - - amd64 - - arm - - arm64 - - ppc64 - - ppc64le - - mips64 - - mips64le - goarm: - - 7 - gobinary: garble - -archives: - - - id: s2-binaries - name_template: "s2-{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}" - format_overrides: - - goos: windows - format: zip - files: - - unpack/* - - s2/LICENSE - - s2/README.md -checksum: - name_template: 'checksums.txt' -snapshot: - name_template: "{{ .Tag }}-next" -changelog: - sort: asc - filters: - exclude: - - '^doc:' - - '^docs:' - - '^test:' - - '^tests:' - - '^Update\sREADME.md' - -nfpms: - - - file_name_template: "s2_package__{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}" - vendor: Klaus Post - homepage: https://github.com/klauspost/compress - maintainer: Klaus Post - description: S2 Compression Tool - license: BSD 3-Clause - formats: - - deb - - rpm diff --git a/vendor/github.com/klauspost/compress/LICENSE b/vendor/github.com/klauspost/compress/LICENSE deleted file mode 100644 index 87d557477..000000000 --- a/vendor/github.com/klauspost/compress/LICENSE +++ /dev/null @@ -1,304 +0,0 @@ -Copyright (c) 2012 The Go Authors. All rights reserved. -Copyright (c) 2019 Klaus Post. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ------------------- - -Files: gzhttp/* - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - 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 "[]" - 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 - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2016-2017 The New York Times Company - - 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. - ------------------- - -Files: s2/cmd/internal/readahead/* - -The MIT License (MIT) - -Copyright (c) 2015 Klaus Post - -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. - ---------------------- -Files: snappy/* -Files: internal/snapref/* - -Copyright (c) 2011 The Snappy-Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ------------------ - -Files: s2/cmd/internal/filepathx/* - -Copyright 2016 The filepathx Authors - -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. diff --git a/vendor/github.com/klauspost/compress/README.md b/vendor/github.com/klauspost/compress/README.md deleted file mode 100644 index 43de48677..000000000 --- a/vendor/github.com/klauspost/compress/README.md +++ /dev/null @@ -1,661 +0,0 @@ -# compress - -This package provides various compression algorithms. - -* [zstandard](https://github.com/klauspost/compress/tree/master/zstd#zstd) compression and decompression in pure Go. -* [S2](https://github.com/klauspost/compress/tree/master/s2#s2-compression) is a high performance replacement for Snappy. -* Optimized [deflate](https://godoc.org/github.com/klauspost/compress/flate) packages which can be used as a dropin replacement for [gzip](https://godoc.org/github.com/klauspost/compress/gzip), [zip](https://godoc.org/github.com/klauspost/compress/zip) and [zlib](https://godoc.org/github.com/klauspost/compress/zlib). -* [snappy](https://github.com/klauspost/compress/tree/master/snappy) is a drop-in replacement for `github.com/golang/snappy` offering better compression and concurrent streams. -* [huff0](https://github.com/klauspost/compress/tree/master/huff0) and [FSE](https://github.com/klauspost/compress/tree/master/fse) implementations for raw entropy encoding. -* [gzhttp](https://github.com/klauspost/compress/tree/master/gzhttp) Provides client and server wrappers for handling gzipped requests efficiently. -* [pgzip](https://github.com/klauspost/pgzip) is a separate package that provides a very fast parallel gzip implementation. - -[![Go Reference](https://pkg.go.dev/badge/klauspost/compress.svg)](https://pkg.go.dev/github.com/klauspost/compress?tab=subdirectories) -[![Go](https://github.com/klauspost/compress/actions/workflows/go.yml/badge.svg)](https://github.com/klauspost/compress/actions/workflows/go.yml) -[![Sourcegraph Badge](https://sourcegraph.com/github.com/klauspost/compress/-/badge.svg)](https://sourcegraph.com/github.com/klauspost/compress?badge) - -# changelog - -* Sept 19th, 2023 - [v1.17.0](https://github.com/klauspost/compress/releases/tag/v1.17.0) - * Add experimental dictionary builder https://github.com/klauspost/compress/pull/853 - * Add xerial snappy read/writer https://github.com/klauspost/compress/pull/838 - * flate: Add limited window compression https://github.com/klauspost/compress/pull/843 - * s2: Do 2 overlapping match checks https://github.com/klauspost/compress/pull/839 - * flate: Add amd64 assembly matchlen https://github.com/klauspost/compress/pull/837 - * gzip: Copy bufio.Reader on Reset by @thatguystone in https://github.com/klauspost/compress/pull/860 - -* July 1st, 2023 - [v1.16.7](https://github.com/klauspost/compress/releases/tag/v1.16.7) - * zstd: Fix default level first dictionary encode https://github.com/klauspost/compress/pull/829 - * s2: add GetBufferCapacity() method by @GiedriusS in https://github.com/klauspost/compress/pull/832 - -* June 13, 2023 - [v1.16.6](https://github.com/klauspost/compress/releases/tag/v1.16.6) - * zstd: correctly ignore WithEncoderPadding(1) by @ianlancetaylor in https://github.com/klauspost/compress/pull/806 - * zstd: Add amd64 match length assembly https://github.com/klauspost/compress/pull/824 - * gzhttp: Handle informational headers by @rtribotte in https://github.com/klauspost/compress/pull/815 - * s2: Improve Better compression slightly https://github.com/klauspost/compress/pull/663 - -* Apr 16, 2023 - [v1.16.5](https://github.com/klauspost/compress/releases/tag/v1.16.5) - * zstd: readByte needs to use io.ReadFull by @jnoxon in https://github.com/klauspost/compress/pull/802 - * gzip: Fix WriterTo after initial read https://github.com/klauspost/compress/pull/804 - -* Apr 5, 2023 - [v1.16.4](https://github.com/klauspost/compress/releases/tag/v1.16.4) - * zstd: Improve zstd best efficiency by @greatroar and @klauspost in https://github.com/klauspost/compress/pull/784 - * zstd: Respect WithAllLitEntropyCompression https://github.com/klauspost/compress/pull/792 - * zstd: Fix amd64 not always detecting corrupt data https://github.com/klauspost/compress/pull/785 - * zstd: Various minor improvements by @greatroar in https://github.com/klauspost/compress/pull/788 https://github.com/klauspost/compress/pull/794 https://github.com/klauspost/compress/pull/795 - * s2: Fix huge block overflow https://github.com/klauspost/compress/pull/779 - * s2: Allow CustomEncoder fallback https://github.com/klauspost/compress/pull/780 - * gzhttp: Suppport ResponseWriter Unwrap() in gzhttp handler by @jgimenez in https://github.com/klauspost/compress/pull/799 - -* Mar 13, 2023 - [v1.16.1](https://github.com/klauspost/compress/releases/tag/v1.16.1) - * zstd: Speed up + improve best encoder by @greatroar in https://github.com/klauspost/compress/pull/776 - * gzhttp: Add optional [BREACH mitigation](https://github.com/klauspost/compress/tree/master/gzhttp#breach-mitigation). https://github.com/klauspost/compress/pull/762 https://github.com/klauspost/compress/pull/768 https://github.com/klauspost/compress/pull/769 https://github.com/klauspost/compress/pull/770 https://github.com/klauspost/compress/pull/767 - * s2: Add Intel LZ4s converter https://github.com/klauspost/compress/pull/766 - * zstd: Minor bug fixes https://github.com/klauspost/compress/pull/771 https://github.com/klauspost/compress/pull/772 https://github.com/klauspost/compress/pull/773 - * huff0: Speed up compress1xDo by @greatroar in https://github.com/klauspost/compress/pull/774 - -* Feb 26, 2023 - [v1.16.0](https://github.com/klauspost/compress/releases/tag/v1.16.0) - * s2: Add [Dictionary](https://github.com/klauspost/compress/tree/master/s2#dictionaries) support. https://github.com/klauspost/compress/pull/685 - * s2: Add Compression Size Estimate. https://github.com/klauspost/compress/pull/752 - * s2: Add support for custom stream encoder. https://github.com/klauspost/compress/pull/755 - * s2: Add LZ4 block converter. https://github.com/klauspost/compress/pull/748 - * s2: Support io.ReaderAt in ReadSeeker. https://github.com/klauspost/compress/pull/747 - * s2c/s2sx: Use concurrent decoding. https://github.com/klauspost/compress/pull/746 - -
- See changes to v1.15.x - -* Jan 21st, 2023 (v1.15.15) - * deflate: Improve level 7-9 by @klauspost in https://github.com/klauspost/compress/pull/739 - * zstd: Add delta encoding support by @greatroar in https://github.com/klauspost/compress/pull/728 - * zstd: Various speed improvements by @greatroar https://github.com/klauspost/compress/pull/741 https://github.com/klauspost/compress/pull/734 https://github.com/klauspost/compress/pull/736 https://github.com/klauspost/compress/pull/744 https://github.com/klauspost/compress/pull/743 https://github.com/klauspost/compress/pull/745 - * gzhttp: Add SuffixETag() and DropETag() options to prevent ETag collisions on compressed responses by @willbicks in https://github.com/klauspost/compress/pull/740 - -* Jan 3rd, 2023 (v1.15.14) - - * flate: Improve speed in big stateless blocks https://github.com/klauspost/compress/pull/718 - * zstd: Minor speed tweaks by @greatroar in https://github.com/klauspost/compress/pull/716 https://github.com/klauspost/compress/pull/720 - * export NoGzipResponseWriter for custom ResponseWriter wrappers by @harshavardhana in https://github.com/klauspost/compress/pull/722 - * s2: Add example for indexing and existing stream https://github.com/klauspost/compress/pull/723 - -* Dec 11, 2022 (v1.15.13) - * zstd: Add [MaxEncodedSize](https://pkg.go.dev/github.com/klauspost/compress@v1.15.13/zstd#Encoder.MaxEncodedSize) to encoder https://github.com/klauspost/compress/pull/691 - * zstd: Various tweaks and improvements https://github.com/klauspost/compress/pull/693 https://github.com/klauspost/compress/pull/695 https://github.com/klauspost/compress/pull/696 https://github.com/klauspost/compress/pull/701 https://github.com/klauspost/compress/pull/702 https://github.com/klauspost/compress/pull/703 https://github.com/klauspost/compress/pull/704 https://github.com/klauspost/compress/pull/705 https://github.com/klauspost/compress/pull/706 https://github.com/klauspost/compress/pull/707 https://github.com/klauspost/compress/pull/708 - -* Oct 26, 2022 (v1.15.12) - - * zstd: Tweak decoder allocs. https://github.com/klauspost/compress/pull/680 - * gzhttp: Always delete `HeaderNoCompression` https://github.com/klauspost/compress/pull/683 - -* Sept 26, 2022 (v1.15.11) - - * flate: Improve level 1-3 compression https://github.com/klauspost/compress/pull/678 - * zstd: Improve "best" compression by @nightwolfz in https://github.com/klauspost/compress/pull/677 - * zstd: Fix+reduce decompression allocations https://github.com/klauspost/compress/pull/668 - * zstd: Fix non-effective noescape tag https://github.com/klauspost/compress/pull/667 - -* Sept 16, 2022 (v1.15.10) - - * zstd: Add [WithDecodeAllCapLimit](https://pkg.go.dev/github.com/klauspost/compress@v1.15.10/zstd#WithDecodeAllCapLimit) https://github.com/klauspost/compress/pull/649 - * Add Go 1.19 - deprecate Go 1.16 https://github.com/klauspost/compress/pull/651 - * flate: Improve level 5+6 compression https://github.com/klauspost/compress/pull/656 - * zstd: Improve "better" compresssion https://github.com/klauspost/compress/pull/657 - * s2: Improve "best" compression https://github.com/klauspost/compress/pull/658 - * s2: Improve "better" compression. https://github.com/klauspost/compress/pull/635 - * s2: Slightly faster non-assembly decompression https://github.com/klauspost/compress/pull/646 - * Use arrays for constant size copies https://github.com/klauspost/compress/pull/659 - -* July 21, 2022 (v1.15.9) - - * zstd: Fix decoder crash on amd64 (no BMI) on invalid input https://github.com/klauspost/compress/pull/645 - * zstd: Disable decoder extended memory copies (amd64) due to possible crashes https://github.com/klauspost/compress/pull/644 - * zstd: Allow single segments up to "max decoded size" by @klauspost in https://github.com/klauspost/compress/pull/643 - -* July 13, 2022 (v1.15.8) - - * gzip: fix stack exhaustion bug in Reader.Read https://github.com/klauspost/compress/pull/641 - * s2: Add Index header trim/restore https://github.com/klauspost/compress/pull/638 - * zstd: Optimize seqdeq amd64 asm by @greatroar in https://github.com/klauspost/compress/pull/636 - * zstd: Improve decoder memcopy https://github.com/klauspost/compress/pull/637 - * huff0: Pass a single bitReader pointer to asm by @greatroar in https://github.com/klauspost/compress/pull/634 - * zstd: Branchless getBits for amd64 w/o BMI2 by @greatroar in https://github.com/klauspost/compress/pull/640 - * gzhttp: Remove header before writing https://github.com/klauspost/compress/pull/639 - -* June 29, 2022 (v1.15.7) - - * s2: Fix absolute forward seeks https://github.com/klauspost/compress/pull/633 - * zip: Merge upstream https://github.com/klauspost/compress/pull/631 - * zip: Re-add zip64 fix https://github.com/klauspost/compress/pull/624 - * zstd: translate fseDecoder.buildDtable into asm by @WojciechMula in https://github.com/klauspost/compress/pull/598 - * flate: Faster histograms https://github.com/klauspost/compress/pull/620 - * deflate: Use compound hcode https://github.com/klauspost/compress/pull/622 - -* June 3, 2022 (v1.15.6) - * s2: Improve coding for long, close matches https://github.com/klauspost/compress/pull/613 - * s2c: Add Snappy/S2 stream recompression https://github.com/klauspost/compress/pull/611 - * zstd: Always use configured block size https://github.com/klauspost/compress/pull/605 - * zstd: Fix incorrect hash table placement for dict encoding in default https://github.com/klauspost/compress/pull/606 - * zstd: Apply default config to ZipDecompressor without options https://github.com/klauspost/compress/pull/608 - * gzhttp: Exclude more common archive formats https://github.com/klauspost/compress/pull/612 - * s2: Add ReaderIgnoreCRC https://github.com/klauspost/compress/pull/609 - * s2: Remove sanity load on index creation https://github.com/klauspost/compress/pull/607 - * snappy: Use dedicated function for scoring https://github.com/klauspost/compress/pull/614 - * s2c+s2d: Use official snappy framed extension https://github.com/klauspost/compress/pull/610 - -* May 25, 2022 (v1.15.5) - * s2: Add concurrent stream decompression https://github.com/klauspost/compress/pull/602 - * s2: Fix final emit oob read crash on amd64 https://github.com/klauspost/compress/pull/601 - * huff0: asm implementation of Decompress1X by @WojciechMula https://github.com/klauspost/compress/pull/596 - * zstd: Use 1 less goroutine for stream decoding https://github.com/klauspost/compress/pull/588 - * zstd: Copy literal in 16 byte blocks when possible https://github.com/klauspost/compress/pull/592 - * zstd: Speed up when WithDecoderLowmem(false) https://github.com/klauspost/compress/pull/599 - * zstd: faster next state update in BMI2 version of decode by @WojciechMula in https://github.com/klauspost/compress/pull/593 - * huff0: Do not check max size when reading table. https://github.com/klauspost/compress/pull/586 - * flate: Inplace hashing for level 7-9 by @klauspost in https://github.com/klauspost/compress/pull/590 - - -* May 11, 2022 (v1.15.4) - * huff0: decompress directly into output by @WojciechMula in [#577](https://github.com/klauspost/compress/pull/577) - * inflate: Keep dict on stack [#581](https://github.com/klauspost/compress/pull/581) - * zstd: Faster decoding memcopy in asm [#583](https://github.com/klauspost/compress/pull/583) - * zstd: Fix ignored crc [#580](https://github.com/klauspost/compress/pull/580) - -* May 5, 2022 (v1.15.3) - * zstd: Allow to ignore checksum checking by @WojciechMula [#572](https://github.com/klauspost/compress/pull/572) - * s2: Fix incorrect seek for io.SeekEnd in [#575](https://github.com/klauspost/compress/pull/575) - -* Apr 26, 2022 (v1.15.2) - * zstd: Add x86-64 assembly for decompression on streams and blocks. Contributed by [@WojciechMula](https://github.com/WojciechMula). Typically 2x faster. [#528](https://github.com/klauspost/compress/pull/528) [#531](https://github.com/klauspost/compress/pull/531) [#545](https://github.com/klauspost/compress/pull/545) [#537](https://github.com/klauspost/compress/pull/537) - * zstd: Add options to ZipDecompressor and fixes [#539](https://github.com/klauspost/compress/pull/539) - * s2: Use sorted search for index [#555](https://github.com/klauspost/compress/pull/555) - * Minimum version is Go 1.16, added CI test on 1.18. - -* Mar 11, 2022 (v1.15.1) - * huff0: Add x86 assembly of Decode4X by @WojciechMula in [#512](https://github.com/klauspost/compress/pull/512) - * zstd: Reuse zip decoders in [#514](https://github.com/klauspost/compress/pull/514) - * zstd: Detect extra block data and report as corrupted in [#520](https://github.com/klauspost/compress/pull/520) - * zstd: Handle zero sized frame content size stricter in [#521](https://github.com/klauspost/compress/pull/521) - * zstd: Add stricter block size checks in [#523](https://github.com/klauspost/compress/pull/523) - -* Mar 3, 2022 (v1.15.0) - * zstd: Refactor decoder by @klauspost in [#498](https://github.com/klauspost/compress/pull/498) - * zstd: Add stream encoding without goroutines by @klauspost in [#505](https://github.com/klauspost/compress/pull/505) - * huff0: Prevent single blocks exceeding 16 bits by @klauspost in[#507](https://github.com/klauspost/compress/pull/507) - * flate: Inline literal emission by @klauspost in [#509](https://github.com/klauspost/compress/pull/509) - * gzhttp: Add zstd to transport by @klauspost in [#400](https://github.com/klauspost/compress/pull/400) - * gzhttp: Make content-type optional by @klauspost in [#510](https://github.com/klauspost/compress/pull/510) - -Both compression and decompression now supports "synchronous" stream operations. This means that whenever "concurrency" is set to 1, they will operate without spawning goroutines. - -Stream decompression is now faster on asynchronous, since the goroutine allocation much more effectively splits the workload. On typical streams this will typically use 2 cores fully for decompression. When a stream has finished decoding no goroutines will be left over, so decoders can now safely be pooled and still be garbage collected. - -While the release has been extensively tested, it is recommended to testing when upgrading. - -
- -
- See changes to v1.14.x - -* Feb 22, 2022 (v1.14.4) - * flate: Fix rare huffman only (-2) corruption. [#503](https://github.com/klauspost/compress/pull/503) - * zip: Update deprecated CreateHeaderRaw to correctly call CreateRaw by @saracen in [#502](https://github.com/klauspost/compress/pull/502) - * zip: don't read data descriptor early by @saracen in [#501](https://github.com/klauspost/compress/pull/501) #501 - * huff0: Use static decompression buffer up to 30% faster by @klauspost in [#499](https://github.com/klauspost/compress/pull/499) [#500](https://github.com/klauspost/compress/pull/500) - -* Feb 17, 2022 (v1.14.3) - * flate: Improve fastest levels compression speed ~10% more throughput. [#482](https://github.com/klauspost/compress/pull/482) [#489](https://github.com/klauspost/compress/pull/489) [#490](https://github.com/klauspost/compress/pull/490) [#491](https://github.com/klauspost/compress/pull/491) [#494](https://github.com/klauspost/compress/pull/494) [#478](https://github.com/klauspost/compress/pull/478) - * flate: Faster decompression speed, ~5-10%. [#483](https://github.com/klauspost/compress/pull/483) - * s2: Faster compression with Go v1.18 and amd64 microarch level 3+. [#484](https://github.com/klauspost/compress/pull/484) [#486](https://github.com/klauspost/compress/pull/486) - -* Jan 25, 2022 (v1.14.2) - * zstd: improve header decoder by @dsnet [#476](https://github.com/klauspost/compress/pull/476) - * zstd: Add bigger default blocks [#469](https://github.com/klauspost/compress/pull/469) - * zstd: Remove unused decompression buffer [#470](https://github.com/klauspost/compress/pull/470) - * zstd: Fix logically dead code by @ningmingxiao [#472](https://github.com/klauspost/compress/pull/472) - * flate: Improve level 7-9 [#471](https://github.com/klauspost/compress/pull/471) [#473](https://github.com/klauspost/compress/pull/473) - * zstd: Add noasm tag for xxhash [#475](https://github.com/klauspost/compress/pull/475) - -* Jan 11, 2022 (v1.14.1) - * s2: Add stream index in [#462](https://github.com/klauspost/compress/pull/462) - * flate: Speed and efficiency improvements in [#439](https://github.com/klauspost/compress/pull/439) [#461](https://github.com/klauspost/compress/pull/461) [#455](https://github.com/klauspost/compress/pull/455) [#452](https://github.com/klauspost/compress/pull/452) [#458](https://github.com/klauspost/compress/pull/458) - * zstd: Performance improvement in [#420]( https://github.com/klauspost/compress/pull/420) [#456](https://github.com/klauspost/compress/pull/456) [#437](https://github.com/klauspost/compress/pull/437) [#467](https://github.com/klauspost/compress/pull/467) [#468](https://github.com/klauspost/compress/pull/468) - * zstd: add arm64 xxhash assembly in [#464](https://github.com/klauspost/compress/pull/464) - * Add garbled for binaries for s2 in [#445](https://github.com/klauspost/compress/pull/445) -
- -
- See changes to v1.13.x - -* Aug 30, 2021 (v1.13.5) - * gz/zlib/flate: Alias stdlib errors [#425](https://github.com/klauspost/compress/pull/425) - * s2: Add block support to commandline tools [#413](https://github.com/klauspost/compress/pull/413) - * zstd: pooledZipWriter should return Writers to the same pool [#426](https://github.com/klauspost/compress/pull/426) - * Removed golang/snappy as external dependency for tests [#421](https://github.com/klauspost/compress/pull/421) - -* Aug 12, 2021 (v1.13.4) - * Add [snappy replacement package](https://github.com/klauspost/compress/tree/master/snappy). - * zstd: Fix incorrect encoding in "best" mode [#415](https://github.com/klauspost/compress/pull/415) - -* Aug 3, 2021 (v1.13.3) - * zstd: Improve Best compression [#404](https://github.com/klauspost/compress/pull/404) - * zstd: Fix WriteTo error forwarding [#411](https://github.com/klauspost/compress/pull/411) - * gzhttp: Return http.HandlerFunc instead of http.Handler. Unlikely breaking change. [#406](https://github.com/klauspost/compress/pull/406) - * s2sx: Fix max size error [#399](https://github.com/klauspost/compress/pull/399) - * zstd: Add optional stream content size on reset [#401](https://github.com/klauspost/compress/pull/401) - * zstd: use SpeedBestCompression for level >= 10 [#410](https://github.com/klauspost/compress/pull/410) - -* Jun 14, 2021 (v1.13.1) - * s2: Add full Snappy output support [#396](https://github.com/klauspost/compress/pull/396) - * zstd: Add configurable [Decoder window](https://pkg.go.dev/github.com/klauspost/compress/zstd#WithDecoderMaxWindow) size [#394](https://github.com/klauspost/compress/pull/394) - * gzhttp: Add header to skip compression [#389](https://github.com/klauspost/compress/pull/389) - * s2: Improve speed with bigger output margin [#395](https://github.com/klauspost/compress/pull/395) - -* Jun 3, 2021 (v1.13.0) - * Added [gzhttp](https://github.com/klauspost/compress/tree/master/gzhttp#gzip-handler) which allows wrapping HTTP servers and clients with GZIP compressors. - * zstd: Detect short invalid signatures [#382](https://github.com/klauspost/compress/pull/382) - * zstd: Spawn decoder goroutine only if needed. [#380](https://github.com/klauspost/compress/pull/380) -
- - -
- See changes to v1.12.x - -* May 25, 2021 (v1.12.3) - * deflate: Better/faster Huffman encoding [#374](https://github.com/klauspost/compress/pull/374) - * deflate: Allocate less for history. [#375](https://github.com/klauspost/compress/pull/375) - * zstd: Forward read errors [#373](https://github.com/klauspost/compress/pull/373) - -* Apr 27, 2021 (v1.12.2) - * zstd: Improve better/best compression [#360](https://github.com/klauspost/compress/pull/360) [#364](https://github.com/klauspost/compress/pull/364) [#365](https://github.com/klauspost/compress/pull/365) - * zstd: Add helpers to compress/decompress zstd inside zip files [#363](https://github.com/klauspost/compress/pull/363) - * deflate: Improve level 5+6 compression [#367](https://github.com/klauspost/compress/pull/367) - * s2: Improve better/best compression [#358](https://github.com/klauspost/compress/pull/358) [#359](https://github.com/klauspost/compress/pull/358) - * s2: Load after checking src limit on amd64. [#362](https://github.com/klauspost/compress/pull/362) - * s2sx: Limit max executable size [#368](https://github.com/klauspost/compress/pull/368) - -* Apr 14, 2021 (v1.12.1) - * snappy package removed. Upstream added as dependency. - * s2: Better compression in "best" mode [#353](https://github.com/klauspost/compress/pull/353) - * s2sx: Add stdin input and detect pre-compressed from signature [#352](https://github.com/klauspost/compress/pull/352) - * s2c/s2d: Add http as possible input [#348](https://github.com/klauspost/compress/pull/348) - * s2c/s2d/s2sx: Always truncate when writing files [#352](https://github.com/klauspost/compress/pull/352) - * zstd: Reduce memory usage further when using [WithLowerEncoderMem](https://pkg.go.dev/github.com/klauspost/compress/zstd#WithLowerEncoderMem) [#346](https://github.com/klauspost/compress/pull/346) - * s2: Fix potential problem with amd64 assembly and profilers [#349](https://github.com/klauspost/compress/pull/349) -
- -
- See changes to v1.11.x - -* Mar 26, 2021 (v1.11.13) - * zstd: Big speedup on small dictionary encodes [#344](https://github.com/klauspost/compress/pull/344) [#345](https://github.com/klauspost/compress/pull/345) - * zstd: Add [WithLowerEncoderMem](https://pkg.go.dev/github.com/klauspost/compress/zstd#WithLowerEncoderMem) encoder option [#336](https://github.com/klauspost/compress/pull/336) - * deflate: Improve entropy compression [#338](https://github.com/klauspost/compress/pull/338) - * s2: Clean up and minor performance improvement in best [#341](https://github.com/klauspost/compress/pull/341) - -* Mar 5, 2021 (v1.11.12) - * s2: Add `s2sx` binary that creates [self extracting archives](https://github.com/klauspost/compress/tree/master/s2#s2sx-self-extracting-archives). - * s2: Speed up decompression on non-assembly platforms [#328](https://github.com/klauspost/compress/pull/328) - -* Mar 1, 2021 (v1.11.9) - * s2: Add ARM64 decompression assembly. Around 2x output speed. [#324](https://github.com/klauspost/compress/pull/324) - * s2: Improve "better" speed and efficiency. [#325](https://github.com/klauspost/compress/pull/325) - * s2: Fix binaries. - -* Feb 25, 2021 (v1.11.8) - * s2: Fixed occational out-of-bounds write on amd64. Upgrade recommended. - * s2: Add AMD64 assembly for better mode. 25-50% faster. [#315](https://github.com/klauspost/compress/pull/315) - * s2: Less upfront decoder allocation. [#322](https://github.com/klauspost/compress/pull/322) - * zstd: Faster "compression" of incompressible data. [#314](https://github.com/klauspost/compress/pull/314) - * zip: Fix zip64 headers. [#313](https://github.com/klauspost/compress/pull/313) - -* Jan 14, 2021 (v1.11.7) - * Use Bytes() interface to get bytes across packages. [#309](https://github.com/klauspost/compress/pull/309) - * s2: Add 'best' compression option. [#310](https://github.com/klauspost/compress/pull/310) - * s2: Add ReaderMaxBlockSize, changes `s2.NewReader` signature to include varargs. [#311](https://github.com/klauspost/compress/pull/311) - * s2: Fix crash on small better buffers. [#308](https://github.com/klauspost/compress/pull/308) - * s2: Clean up decoder. [#312](https://github.com/klauspost/compress/pull/312) - -* Jan 7, 2021 (v1.11.6) - * zstd: Make decoder allocations smaller [#306](https://github.com/klauspost/compress/pull/306) - * zstd: Free Decoder resources when Reset is called with a nil io.Reader [#305](https://github.com/klauspost/compress/pull/305) - -* Dec 20, 2020 (v1.11.4) - * zstd: Add Best compression mode [#304](https://github.com/klauspost/compress/pull/304) - * Add header decoder [#299](https://github.com/klauspost/compress/pull/299) - * s2: Add uncompressed stream option [#297](https://github.com/klauspost/compress/pull/297) - * Simplify/speed up small blocks with known max size. [#300](https://github.com/klauspost/compress/pull/300) - * zstd: Always reset literal dict encoder [#303](https://github.com/klauspost/compress/pull/303) - -* Nov 15, 2020 (v1.11.3) - * inflate: 10-15% faster decompression [#293](https://github.com/klauspost/compress/pull/293) - * zstd: Tweak DecodeAll default allocation [#295](https://github.com/klauspost/compress/pull/295) - -* Oct 11, 2020 (v1.11.2) - * s2: Fix out of bounds read in "better" block compression [#291](https://github.com/klauspost/compress/pull/291) - -* Oct 1, 2020 (v1.11.1) - * zstd: Set allLitEntropy true in default configuration [#286](https://github.com/klauspost/compress/pull/286) - -* Sept 8, 2020 (v1.11.0) - * zstd: Add experimental compression [dictionaries](https://github.com/klauspost/compress/tree/master/zstd#dictionaries) [#281](https://github.com/klauspost/compress/pull/281) - * zstd: Fix mixed Write and ReadFrom calls [#282](https://github.com/klauspost/compress/pull/282) - * inflate/gz: Limit variable shifts, ~5% faster decompression [#274](https://github.com/klauspost/compress/pull/274) -
- -
- See changes to v1.10.x - -* July 8, 2020 (v1.10.11) - * zstd: Fix extra block when compressing with ReadFrom. [#278](https://github.com/klauspost/compress/pull/278) - * huff0: Also populate compression table when reading decoding table. [#275](https://github.com/klauspost/compress/pull/275) - -* June 23, 2020 (v1.10.10) - * zstd: Skip entropy compression in fastest mode when no matches. [#270](https://github.com/klauspost/compress/pull/270) - -* June 16, 2020 (v1.10.9): - * zstd: API change for specifying dictionaries. See [#268](https://github.com/klauspost/compress/pull/268) - * zip: update CreateHeaderRaw to handle zip64 fields. [#266](https://github.com/klauspost/compress/pull/266) - * Fuzzit tests removed. The service has been purchased and is no longer available. - -* June 5, 2020 (v1.10.8): - * 1.15x faster zstd block decompression. [#265](https://github.com/klauspost/compress/pull/265) - -* June 1, 2020 (v1.10.7): - * Added zstd decompression [dictionary support](https://github.com/klauspost/compress/tree/master/zstd#dictionaries) - * Increase zstd decompression speed up to 1.19x. [#259](https://github.com/klauspost/compress/pull/259) - * Remove internal reset call in zstd compression and reduce allocations. [#263](https://github.com/klauspost/compress/pull/263) - -* May 21, 2020: (v1.10.6) - * zstd: Reduce allocations while decoding. [#258](https://github.com/klauspost/compress/pull/258), [#252](https://github.com/klauspost/compress/pull/252) - * zstd: Stricter decompression checks. - -* April 12, 2020: (v1.10.5) - * s2-commands: Flush output when receiving SIGINT. [#239](https://github.com/klauspost/compress/pull/239) - -* Apr 8, 2020: (v1.10.4) - * zstd: Minor/special case optimizations. [#251](https://github.com/klauspost/compress/pull/251), [#250](https://github.com/klauspost/compress/pull/250), [#249](https://github.com/klauspost/compress/pull/249), [#247](https://github.com/klauspost/compress/pull/247) -* Mar 11, 2020: (v1.10.3) - * s2: Use S2 encoder in pure Go mode for Snappy output as well. [#245](https://github.com/klauspost/compress/pull/245) - * s2: Fix pure Go block encoder. [#244](https://github.com/klauspost/compress/pull/244) - * zstd: Added "better compression" mode. [#240](https://github.com/klauspost/compress/pull/240) - * zstd: Improve speed of fastest compression mode by 5-10% [#241](https://github.com/klauspost/compress/pull/241) - * zstd: Skip creating encoders when not needed. [#238](https://github.com/klauspost/compress/pull/238) - -* Feb 27, 2020: (v1.10.2) - * Close to 50% speedup in inflate (gzip/zip decompression). [#236](https://github.com/klauspost/compress/pull/236) [#234](https://github.com/klauspost/compress/pull/234) [#232](https://github.com/klauspost/compress/pull/232) - * Reduce deflate level 1-6 memory usage up to 59%. [#227](https://github.com/klauspost/compress/pull/227) - -* Feb 18, 2020: (v1.10.1) - * Fix zstd crash when resetting multiple times without sending data. [#226](https://github.com/klauspost/compress/pull/226) - * deflate: Fix dictionary use on level 1-6. [#224](https://github.com/klauspost/compress/pull/224) - * Remove deflate writer reference when closing. [#224](https://github.com/klauspost/compress/pull/224) - -* Feb 4, 2020: (v1.10.0) - * Add optional dictionary to [stateless deflate](https://pkg.go.dev/github.com/klauspost/compress/flate?tab=doc#StatelessDeflate). Breaking change, send `nil` for previous behaviour. [#216](https://github.com/klauspost/compress/pull/216) - * Fix buffer overflow on repeated small block deflate. [#218](https://github.com/klauspost/compress/pull/218) - * Allow copying content from an existing ZIP file without decompressing+compressing. [#214](https://github.com/klauspost/compress/pull/214) - * Added [S2](https://github.com/klauspost/compress/tree/master/s2#s2-compression) AMD64 assembler and various optimizations. Stream speed >10GB/s. [#186](https://github.com/klauspost/compress/pull/186) - -
- -
- See changes prior to v1.10.0 - -* Jan 20,2020 (v1.9.8) Optimize gzip/deflate with better size estimates and faster table generation. [#207](https://github.com/klauspost/compress/pull/207) by [luyu6056](https://github.com/luyu6056), [#206](https://github.com/klauspost/compress/pull/206). -* Jan 11, 2020: S2 Encode/Decode will use provided buffer if capacity is big enough. [#204](https://github.com/klauspost/compress/pull/204) -* Jan 5, 2020: (v1.9.7) Fix another zstd regression in v1.9.5 - v1.9.6 removed. -* Jan 4, 2020: (v1.9.6) Regression in v1.9.5 fixed causing corrupt zstd encodes in rare cases. -* Jan 4, 2020: Faster IO in [s2c + s2d commandline tools](https://github.com/klauspost/compress/tree/master/s2#commandline-tools) compression/decompression. [#192](https://github.com/klauspost/compress/pull/192) -* Dec 29, 2019: Removed v1.9.5 since fuzz tests showed a compatibility problem with the reference zstandard decoder. -* Dec 29, 2019: (v1.9.5) zstd: 10-20% faster block compression. [#199](https://github.com/klauspost/compress/pull/199) -* Dec 29, 2019: [zip](https://godoc.org/github.com/klauspost/compress/zip) package updated with latest Go features -* Dec 29, 2019: zstd: Single segment flag condintions tweaked. [#197](https://github.com/klauspost/compress/pull/197) -* Dec 18, 2019: s2: Faster compression when ReadFrom is used. [#198](https://github.com/klauspost/compress/pull/198) -* Dec 10, 2019: s2: Fix repeat length output when just above at 16MB limit. -* Dec 10, 2019: zstd: Add function to get decoder as io.ReadCloser. [#191](https://github.com/klauspost/compress/pull/191) -* Dec 3, 2019: (v1.9.4) S2: limit max repeat length. [#188](https://github.com/klauspost/compress/pull/188) -* Dec 3, 2019: Add [WithNoEntropyCompression](https://godoc.org/github.com/klauspost/compress/zstd#WithNoEntropyCompression) to zstd [#187](https://github.com/klauspost/compress/pull/187) -* Dec 3, 2019: Reduce memory use for tests. Check for leaked goroutines. -* Nov 28, 2019 (v1.9.3) Less allocations in stateless deflate. -* Nov 28, 2019: 5-20% Faster huff0 decode. Impacts zstd as well. [#184](https://github.com/klauspost/compress/pull/184) -* Nov 12, 2019 (v1.9.2) Added [Stateless Compression](#stateless-compression) for gzip/deflate. -* Nov 12, 2019: Fixed zstd decompression of large single blocks. [#180](https://github.com/klauspost/compress/pull/180) -* Nov 11, 2019: Set default [s2c](https://github.com/klauspost/compress/tree/master/s2#commandline-tools) block size to 4MB. -* Nov 11, 2019: Reduce inflate memory use by 1KB. -* Nov 10, 2019: Less allocations in deflate bit writer. -* Nov 10, 2019: Fix inconsistent error returned by zstd decoder. -* Oct 28, 2019 (v1.9.1) ztsd: Fix crash when compressing blocks. [#174](https://github.com/klauspost/compress/pull/174) -* Oct 24, 2019 (v1.9.0) zstd: Fix rare data corruption [#173](https://github.com/klauspost/compress/pull/173) -* Oct 24, 2019 zstd: Fix huff0 out of buffer write [#171](https://github.com/klauspost/compress/pull/171) and always return errors [#172](https://github.com/klauspost/compress/pull/172) -* Oct 10, 2019: Big deflate rewrite, 30-40% faster with better compression [#105](https://github.com/klauspost/compress/pull/105) - -
- -
- See changes prior to v1.9.0 - -* Oct 10, 2019: (v1.8.6) zstd: Allow partial reads to get flushed data. [#169](https://github.com/klauspost/compress/pull/169) -* Oct 3, 2019: Fix inconsistent results on broken zstd streams. -* Sep 25, 2019: Added `-rm` (remove source files) and `-q` (no output except errors) to `s2c` and `s2d` [commands](https://github.com/klauspost/compress/tree/master/s2#commandline-tools) -* Sep 16, 2019: (v1.8.4) Add `s2c` and `s2d` [commandline tools](https://github.com/klauspost/compress/tree/master/s2#commandline-tools). -* Sep 10, 2019: (v1.8.3) Fix s2 decoder [Skip](https://godoc.org/github.com/klauspost/compress/s2#Reader.Skip). -* Sep 7, 2019: zstd: Added [WithWindowSize](https://godoc.org/github.com/klauspost/compress/zstd#WithWindowSize), contributed by [ianwilkes](https://github.com/ianwilkes). -* Sep 5, 2019: (v1.8.2) Add [WithZeroFrames](https://godoc.org/github.com/klauspost/compress/zstd#WithZeroFrames) which adds full zero payload block encoding option. -* Sep 5, 2019: Lazy initialization of zstandard predefined en/decoder tables. -* Aug 26, 2019: (v1.8.1) S2: 1-2% compression increase in "better" compression mode. -* Aug 26, 2019: zstd: Check maximum size of Huffman 1X compressed literals while decoding. -* Aug 24, 2019: (v1.8.0) Added [S2 compression](https://github.com/klauspost/compress/tree/master/s2#s2-compression), a high performance replacement for Snappy. -* Aug 21, 2019: (v1.7.6) Fixed minor issues found by fuzzer. One could lead to zstd not decompressing. -* Aug 18, 2019: Add [fuzzit](https://fuzzit.dev/) continuous fuzzing. -* Aug 14, 2019: zstd: Skip incompressible data 2x faster. [#147](https://github.com/klauspost/compress/pull/147) -* Aug 4, 2019 (v1.7.5): Better literal compression. [#146](https://github.com/klauspost/compress/pull/146) -* Aug 4, 2019: Faster zstd compression. [#143](https://github.com/klauspost/compress/pull/143) [#144](https://github.com/klauspost/compress/pull/144) -* Aug 4, 2019: Faster zstd decompression. [#145](https://github.com/klauspost/compress/pull/145) [#143](https://github.com/klauspost/compress/pull/143) [#142](https://github.com/klauspost/compress/pull/142) -* July 15, 2019 (v1.7.4): Fix double EOF block in rare cases on zstd encoder. -* July 15, 2019 (v1.7.3): Minor speedup/compression increase in default zstd encoder. -* July 14, 2019: zstd decoder: Fix decompression error on multiple uses with mixed content. -* July 7, 2019 (v1.7.2): Snappy update, zstd decoder potential race fix. -* June 17, 2019: zstd decompression bugfix. -* June 17, 2019: fix 32 bit builds. -* June 17, 2019: Easier use in modules (less dependencies). -* June 9, 2019: New stronger "default" [zstd](https://github.com/klauspost/compress/tree/master/zstd#zstd) compression mode. Matches zstd default compression ratio. -* June 5, 2019: 20-40% throughput in [zstandard](https://github.com/klauspost/compress/tree/master/zstd#zstd) compression and better compression. -* June 5, 2019: deflate/gzip compression: Reduce memory usage of lower compression levels. -* June 2, 2019: Added [zstandard](https://github.com/klauspost/compress/tree/master/zstd#zstd) compression! -* May 25, 2019: deflate/gzip: 10% faster bit writer, mostly visible in lower levels. -* Apr 22, 2019: [zstd](https://github.com/klauspost/compress/tree/master/zstd#zstd) decompression added. -* Aug 1, 2018: Added [huff0 README](https://github.com/klauspost/compress/tree/master/huff0#huff0-entropy-compression). -* Jul 8, 2018: Added [Performance Update 2018](#performance-update-2018) below. -* Jun 23, 2018: Merged [Go 1.11 inflate optimizations](https://go-review.googlesource.com/c/go/+/102235). Go 1.9 is now required. Backwards compatible version tagged with [v1.3.0](https://github.com/klauspost/compress/releases/tag/v1.3.0). -* Apr 2, 2018: Added [huff0](https://godoc.org/github.com/klauspost/compress/huff0) en/decoder. Experimental for now, API may change. -* Mar 4, 2018: Added [FSE Entropy](https://godoc.org/github.com/klauspost/compress/fse) en/decoder. Experimental for now, API may change. -* Nov 3, 2017: Add compression [Estimate](https://godoc.org/github.com/klauspost/compress#Estimate) function. -* May 28, 2017: Reduce allocations when resetting decoder. -* Apr 02, 2017: Change back to official crc32, since changes were merged in Go 1.7. -* Jan 14, 2017: Reduce stack pressure due to array copies. See [Issue #18625](https://github.com/golang/go/issues/18625). -* Oct 25, 2016: Level 2-4 have been rewritten and now offers significantly better performance than before. -* Oct 20, 2016: Port zlib changes from Go 1.7 to fix zlib writer issue. Please update. -* Oct 16, 2016: Go 1.7 changes merged. Apples to apples this package is a few percent faster, but has a significantly better balance between speed and compression per level. -* Mar 24, 2016: Always attempt Huffman encoding on level 4-7. This improves base 64 encoded data compression. -* Mar 24, 2016: Small speedup for level 1-3. -* Feb 19, 2016: Faster bit writer, level -2 is 15% faster, level 1 is 4% faster. -* Feb 19, 2016: Handle small payloads faster in level 1-3. -* Feb 19, 2016: Added faster level 2 + 3 compression modes. -* Feb 19, 2016: [Rebalanced compression levels](https://blog.klauspost.com/rebalancing-deflate-compression-levels/), so there is a more even progresssion in terms of compression. New default level is 5. -* Feb 14, 2016: Snappy: Merge upstream changes. -* Feb 14, 2016: Snappy: Fix aggressive skipping. -* Feb 14, 2016: Snappy: Update benchmark. -* Feb 13, 2016: Deflate: Fixed assembler problem that could lead to sub-optimal compression. -* Feb 12, 2016: Snappy: Added AMD64 SSE 4.2 optimizations to matching, which makes easy to compress material run faster. Typical speedup is around 25%. -* Feb 9, 2016: Added Snappy package fork. This version is 5-7% faster, much more on hard to compress content. -* Jan 30, 2016: Optimize level 1 to 3 by not considering static dictionary or storing uncompressed. ~4-5% speedup. -* Jan 16, 2016: Optimization on deflate level 1,2,3 compression. -* Jan 8 2016: Merge [CL 18317](https://go-review.googlesource.com/#/c/18317): fix reading, writing of zip64 archives. -* Dec 8 2015: Make level 1 and -2 deterministic even if write size differs. -* Dec 8 2015: Split encoding functions, so hashing and matching can potentially be inlined. 1-3% faster on AMD64. 5% faster on other platforms. -* Dec 8 2015: Fixed rare [one byte out-of bounds read](https://github.com/klauspost/compress/issues/20). Please update! -* Nov 23 2015: Optimization on token writer. ~2-4% faster. Contributed by [@dsnet](https://github.com/dsnet). -* Nov 20 2015: Small optimization to bit writer on 64 bit systems. -* Nov 17 2015: Fixed out-of-bound errors if the underlying Writer returned an error. See [#15](https://github.com/klauspost/compress/issues/15). -* Nov 12 2015: Added [io.WriterTo](https://golang.org/pkg/io/#WriterTo) support to gzip/inflate. -* Nov 11 2015: Merged [CL 16669](https://go-review.googlesource.com/#/c/16669/4): archive/zip: enable overriding (de)compressors per file -* Oct 15 2015: Added skipping on uncompressible data. Random data speed up >5x. - -
- -# deflate usage - -The packages are drop-in replacements for standard libraries. Simply replace the import path to use them: - -| old import | new import | Documentation -|--------------------|-----------------------------------------|--------------------| -| `compress/gzip` | `github.com/klauspost/compress/gzip` | [gzip](https://pkg.go.dev/github.com/klauspost/compress/gzip?tab=doc) -| `compress/zlib` | `github.com/klauspost/compress/zlib` | [zlib](https://pkg.go.dev/github.com/klauspost/compress/zlib?tab=doc) -| `archive/zip` | `github.com/klauspost/compress/zip` | [zip](https://pkg.go.dev/github.com/klauspost/compress/zip?tab=doc) -| `compress/flate` | `github.com/klauspost/compress/flate` | [flate](https://pkg.go.dev/github.com/klauspost/compress/flate?tab=doc) - -* Optimized [deflate](https://godoc.org/github.com/klauspost/compress/flate) packages which can be used as a dropin replacement for [gzip](https://godoc.org/github.com/klauspost/compress/gzip), [zip](https://godoc.org/github.com/klauspost/compress/zip) and [zlib](https://godoc.org/github.com/klauspost/compress/zlib). - -You may also be interested in [pgzip](https://github.com/klauspost/pgzip), which is a drop in replacement for gzip, which support multithreaded compression on big files and the optimized [crc32](https://github.com/klauspost/crc32) package used by these packages. - -The packages contains the same as the standard library, so you can use the godoc for that: [gzip](http://golang.org/pkg/compress/gzip/), [zip](http://golang.org/pkg/archive/zip/), [zlib](http://golang.org/pkg/compress/zlib/), [flate](http://golang.org/pkg/compress/flate/). - -Currently there is only minor speedup on decompression (mostly CRC32 calculation). - -Memory usage is typically 1MB for a Writer. stdlib is in the same range. -If you expect to have a lot of concurrently allocated Writers consider using -the stateless compress described below. - -For compression performance, see: [this spreadsheet](https://docs.google.com/spreadsheets/d/1nuNE2nPfuINCZJRMt6wFWhKpToF95I47XjSsc-1rbPQ/edit?usp=sharing). - -# Stateless compression - -This package offers stateless compression as a special option for gzip/deflate. -It will do compression but without maintaining any state between Write calls. - -This means there will be no memory kept between Write calls, but compression and speed will be suboptimal. - -This is only relevant in cases where you expect to run many thousands of compressors concurrently, -but with very little activity. This is *not* intended for regular web servers serving individual requests. - -Because of this, the size of actual Write calls will affect output size. - -In gzip, specify level `-3` / `gzip.StatelessCompression` to enable. - -For direct deflate use, NewStatelessWriter and StatelessDeflate are available. See [documentation](https://godoc.org/github.com/klauspost/compress/flate#NewStatelessWriter) - -A `bufio.Writer` can of course be used to control write sizes. For example, to use a 4KB buffer: - -``` - // replace 'ioutil.Discard' with your output. - gzw, err := gzip.NewWriterLevel(ioutil.Discard, gzip.StatelessCompression) - if err != nil { - return err - } - defer gzw.Close() - - w := bufio.NewWriterSize(gzw, 4096) - defer w.Flush() - - // Write to 'w' -``` - -This will only use up to 4KB in memory when the writer is idle. - -Compression is almost always worse than the fastest compression level -and each write will allocate (a little) memory. - -# Performance Update 2018 - -It has been a while since we have been looking at the speed of this package compared to the standard library, so I thought I would re-do my tests and give some overall recommendations based on the current state. All benchmarks have been performed with Go 1.10 on my Desktop Intel(R) Core(TM) i7-2600 CPU @3.40GHz. Since I last ran the tests, I have gotten more RAM, which means tests with big files are no longer limited by my SSD. - -The raw results are in my [updated spreadsheet](https://docs.google.com/spreadsheets/d/1nuNE2nPfuINCZJRMt6wFWhKpToF95I47XjSsc-1rbPQ/edit?usp=sharing). Due to cgo changes and upstream updates i could not get the cgo version of gzip to compile. Instead I included the [zstd](https://github.com/datadog/zstd) cgo implementation. If I get cgo gzip to work again, I might replace the results in the sheet. - -The columns to take note of are: *MB/s* - the throughput. *Reduction* - the data size reduction in percent of the original. *Rel Speed* relative speed compared to the standard library at the same level. *Smaller* - how many percent smaller is the compressed output compared to stdlib. Negative means the output was bigger. *Loss* means the loss (or gain) in compression as a percentage difference of the input. - -The `gzstd` (standard library gzip) and `gzkp` (this package gzip) only uses one CPU core. [`pgzip`](https://github.com/klauspost/pgzip), [`bgzf`](https://github.com/biogo/hts/tree/master/bgzf) uses all 4 cores. [`zstd`](https://github.com/DataDog/zstd) uses one core, and is a beast (but not Go, yet). - - -## Overall differences. - -There appears to be a roughly 5-10% speed advantage over the standard library when comparing at similar compression levels. - -The biggest difference you will see is the result of [re-balancing](https://blog.klauspost.com/rebalancing-deflate-compression-levels/) the compression levels. I wanted by library to give a smoother transition between the compression levels than the standard library. - -This package attempts to provide a more smooth transition, where "1" is taking a lot of shortcuts, "5" is the reasonable trade-off and "9" is the "give me the best compression", and the values in between gives something reasonable in between. The standard library has big differences in levels 1-4, but levels 5-9 having no significant gains - often spending a lot more time than can be justified by the achieved compression. - -There are links to all the test data in the [spreadsheet](https://docs.google.com/spreadsheets/d/1nuNE2nPfuINCZJRMt6wFWhKpToF95I47XjSsc-1rbPQ/edit?usp=sharing) in the top left field on each tab. - -## Web Content - -This test set aims to emulate typical use in a web server. The test-set is 4GB data in 53k files, and is a mixture of (mostly) HTML, JS, CSS. - -Since level 1 and 9 are close to being the same code, they are quite close. But looking at the levels in-between the differences are quite big. - -Looking at level 6, this package is 88% faster, but will output about 6% more data. For a web server, this means you can serve 88% more data, but have to pay for 6% more bandwidth. You can draw your own conclusions on what would be the most expensive for your case. - -## Object files - -This test is for typical data files stored on a server. In this case it is a collection of Go precompiled objects. They are very compressible. - -The picture is similar to the web content, but with small differences since this is very compressible. Levels 2-3 offer good speed, but is sacrificing quite a bit of compression. - -The standard library seems suboptimal on level 3 and 4 - offering both worse compression and speed than level 6 & 7 of this package respectively. - -## Highly Compressible File - -This is a JSON file with very high redundancy. The reduction starts at 95% on level 1, so in real life terms we are dealing with something like a highly redundant stream of data, etc. - -It is definitely visible that we are dealing with specialized content here, so the results are very scattered. This package does not do very well at levels 1-4, but picks up significantly at level 5 and levels 7 and 8 offering great speed for the achieved compression. - -So if you know you content is extremely compressible you might want to go slightly higher than the defaults. The standard library has a huge gap between levels 3 and 4 in terms of speed (2.75x slowdown), so it offers little "middle ground". - -## Medium-High Compressible - -This is a pretty common test corpus: [enwik9](http://mattmahoney.net/dc/textdata.html). It contains the first 10^9 bytes of the English Wikipedia dump on Mar. 3, 2006. This is a very good test of typical text based compression and more data heavy streams. - -We see a similar picture here as in "Web Content". On equal levels some compression is sacrificed for more speed. Level 5 seems to be the best trade-off between speed and size, beating stdlib level 3 in both. - -## Medium Compressible - -I will combine two test sets, one [10GB file set](http://mattmahoney.net/dc/10gb.html) and a VM disk image (~8GB). Both contain different data types and represent a typical backup scenario. - -The most notable thing is how quickly the standard library drops to very low compression speeds around level 5-6 without any big gains in compression. Since this type of data is fairly common, this does not seem like good behavior. - - -## Un-compressible Content - -This is mainly a test of how good the algorithms are at detecting un-compressible input. The standard library only offers this feature with very conservative settings at level 1. Obviously there is no reason for the algorithms to try to compress input that cannot be compressed. The only downside is that it might skip some compressible data on false detections. - - -## Huffman only compression - -This compression library adds a special compression level, named `HuffmanOnly`, which allows near linear time compression. This is done by completely disabling matching of previous data, and only reduce the number of bits to represent each character. - -This means that often used characters, like 'e' and ' ' (space) in text use the fewest bits to represent, and rare characters like '¤' takes more bits to represent. For more information see [wikipedia](https://en.wikipedia.org/wiki/Huffman_coding) or this nice [video](https://youtu.be/ZdooBTdW5bM). - -Since this type of compression has much less variance, the compression speed is mostly unaffected by the input data, and is usually more than *180MB/s* for a single core. - -The downside is that the compression ratio is usually considerably worse than even the fastest conventional compression. The compression ratio can never be better than 8:1 (12.5%). - -The linear time compression can be used as a "better than nothing" mode, where you cannot risk the encoder to slow down on some content. For comparison, the size of the "Twain" text is *233460 bytes* (+29% vs. level 1) and encode speed is 144MB/s (4.5x level 1). So in this case you trade a 30% size increase for a 4 times speedup. - -For more information see my blog post on [Fast Linear Time Compression](http://blog.klauspost.com/constant-time-gzipzip-compression/). - -This is implemented on Go 1.7 as "Huffman Only" mode, though not exposed for gzip. - -# Other packages - -Here are other packages of good quality and pure Go (no cgo wrappers or autoconverted code): - -* [github.com/pierrec/lz4](https://github.com/pierrec/lz4) - strong multithreaded LZ4 compression. -* [github.com/cosnicolaou/pbzip2](https://github.com/cosnicolaou/pbzip2) - multithreaded bzip2 decompression. -* [github.com/dsnet/compress](https://github.com/dsnet/compress) - brotli decompression, bzip2 writer. -* [github.com/ronanh/intcomp](https://github.com/ronanh/intcomp) - Integer compression. -* [github.com/spenczar/fpc](https://github.com/spenczar/fpc) - Float compression. -* [github.com/minio/zipindex](https://github.com/minio/zipindex) - External ZIP directory index. -* [github.com/ybirader/pzip](https://github.com/ybirader/pzip) - Fast concurrent zip archiver and extractor. - -# license - -This code is licensed under the same conditions as the original Go code. See LICENSE file. diff --git a/vendor/github.com/klauspost/compress/SECURITY.md b/vendor/github.com/klauspost/compress/SECURITY.md deleted file mode 100644 index ca6685e2b..000000000 --- a/vendor/github.com/klauspost/compress/SECURITY.md +++ /dev/null @@ -1,25 +0,0 @@ -# Security Policy - -## Supported Versions - -Security updates are applied only to the latest release. - -## Vulnerability Definition - -A security vulnerability is a bug that with certain input triggers a crash or an infinite loop. Most calls will have varying execution time and only in rare cases will slow operation be considered a security vulnerability. - -Corrupted output generally is not considered a security vulnerability, unless independent operations are able to affect each other. Note that not all functionality is re-entrant and safe to use concurrently. - -Out-of-memory crashes only applies if the en/decoder uses an abnormal amount of memory, with appropriate options applied, to limit maximum window size, concurrency, etc. However, if you are in doubt you are welcome to file a security issue. - -It is assumed that all callers are trusted, meaning internal data exposed through reflection or inspection of returned data structures is not considered a vulnerability. - -Vulnerabilities resulting from compiler/assembler errors should be reported upstream. Depending on the severity this package may or may not implement a workaround. - -## Reporting a Vulnerability - -If you have discovered a security vulnerability in this project, please report it privately. **Do not disclose it as a public issue.** This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released. - -Please disclose it at [security advisory](https://github.com/klauspost/compress/security/advisories/new). If possible please provide a minimal reproducer. If the issue only applies to a single platform, it would be helpful to provide access to that. - -This project is maintained by a team of volunteers on a reasonable-effort basis. As such, vulnerabilities will be disclosed in a best effort base. diff --git a/vendor/github.com/klauspost/compress/compressible.go b/vendor/github.com/klauspost/compress/compressible.go deleted file mode 100644 index ea5a692d5..000000000 --- a/vendor/github.com/klauspost/compress/compressible.go +++ /dev/null @@ -1,85 +0,0 @@ -package compress - -import "math" - -// Estimate returns a normalized compressibility estimate of block b. -// Values close to zero are likely uncompressible. -// Values above 0.1 are likely to be compressible. -// Values above 0.5 are very compressible. -// Very small lengths will return 0. -func Estimate(b []byte) float64 { - if len(b) < 16 { - return 0 - } - - // Correctly predicted order 1 - hits := 0 - lastMatch := false - var o1 [256]byte - var hist [256]int - c1 := byte(0) - for _, c := range b { - if c == o1[c1] { - // We only count a hit if there was two correct predictions in a row. - if lastMatch { - hits++ - } - lastMatch = true - } else { - lastMatch = false - } - o1[c1] = c - c1 = c - hist[c]++ - } - - // Use x^0.6 to give better spread - prediction := math.Pow(float64(hits)/float64(len(b)), 0.6) - - // Calculate histogram distribution - variance := float64(0) - avg := float64(len(b)) / 256 - - for _, v := range hist { - Δ := float64(v) - avg - variance += Δ * Δ - } - - stddev := math.Sqrt(float64(variance)) / float64(len(b)) - exp := math.Sqrt(1 / float64(len(b))) - - // Subtract expected stddev - stddev -= exp - if stddev < 0 { - stddev = 0 - } - stddev *= 1 + exp - - // Use x^0.4 to give better spread - entropy := math.Pow(stddev, 0.4) - - // 50/50 weight between prediction and histogram distribution - return math.Pow((prediction+entropy)/2, 0.9) -} - -// ShannonEntropyBits returns the number of bits minimum required to represent -// an entropy encoding of the input bytes. -// https://en.wiktionary.org/wiki/Shannon_entropy -func ShannonEntropyBits(b []byte) int { - if len(b) == 0 { - return 0 - } - var hist [256]int - for _, c := range b { - hist[c]++ - } - shannon := float64(0) - invTotal := 1.0 / float64(len(b)) - for _, v := range hist[:] { - if v > 0 { - n := float64(v) - shannon += math.Ceil(-math.Log2(n*invTotal) * n) - } - } - return int(math.Ceil(shannon)) -} diff --git a/vendor/github.com/klauspost/compress/flate/deflate.go b/vendor/github.com/klauspost/compress/flate/deflate.go deleted file mode 100644 index de912e187..000000000 --- a/vendor/github.com/klauspost/compress/flate/deflate.go +++ /dev/null @@ -1,1017 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Copyright (c) 2015 Klaus Post -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flate - -import ( - "encoding/binary" - "errors" - "fmt" - "io" - "math" -) - -const ( - NoCompression = 0 - BestSpeed = 1 - BestCompression = 9 - DefaultCompression = -1 - - // HuffmanOnly disables Lempel-Ziv match searching and only performs Huffman - // entropy encoding. This mode is useful in compressing data that has - // already been compressed with an LZ style algorithm (e.g. Snappy or LZ4) - // that lacks an entropy encoder. Compression gains are achieved when - // certain bytes in the input stream occur more frequently than others. - // - // Note that HuffmanOnly produces a compressed output that is - // RFC 1951 compliant. That is, any valid DEFLATE decompressor will - // continue to be able to decompress this output. - HuffmanOnly = -2 - ConstantCompression = HuffmanOnly // compatibility alias. - - logWindowSize = 15 - windowSize = 1 << logWindowSize - windowMask = windowSize - 1 - logMaxOffsetSize = 15 // Standard DEFLATE - minMatchLength = 4 // The smallest match that the compressor looks for - maxMatchLength = 258 // The longest match for the compressor - minOffsetSize = 1 // The shortest offset that makes any sense - - // The maximum number of tokens we will encode at the time. - // Smaller sizes usually creates less optimal blocks. - // Bigger can make context switching slow. - // We use this for levels 7-9, so we make it big. - maxFlateBlockTokens = 1 << 15 - maxStoreBlockSize = 65535 - hashBits = 17 // After 17 performance degrades - hashSize = 1 << hashBits - hashMask = (1 << hashBits) - 1 - hashShift = (hashBits + minMatchLength - 1) / minMatchLength - maxHashOffset = 1 << 28 - - skipNever = math.MaxInt32 - - debugDeflate = false -) - -type compressionLevel struct { - good, lazy, nice, chain, fastSkipHashing, level int -} - -// Compression levels have been rebalanced from zlib deflate defaults -// to give a bigger spread in speed and compression. -// See https://blog.klauspost.com/rebalancing-deflate-compression-levels/ -var levels = []compressionLevel{ - {}, // 0 - // Level 1-6 uses specialized algorithm - values not used - {0, 0, 0, 0, 0, 1}, - {0, 0, 0, 0, 0, 2}, - {0, 0, 0, 0, 0, 3}, - {0, 0, 0, 0, 0, 4}, - {0, 0, 0, 0, 0, 5}, - {0, 0, 0, 0, 0, 6}, - // Levels 7-9 use increasingly more lazy matching - // and increasingly stringent conditions for "good enough". - {8, 12, 16, 24, skipNever, 7}, - {16, 30, 40, 64, skipNever, 8}, - {32, 258, 258, 1024, skipNever, 9}, -} - -// advancedState contains state for the advanced levels, with bigger hash tables, etc. -type advancedState struct { - // deflate state - length int - offset int - maxInsertIndex int - chainHead int - hashOffset int - - ii uint16 // position of last match, intended to overflow to reset. - - // input window: unprocessed data is window[index:windowEnd] - index int - hashMatch [maxMatchLength + minMatchLength]uint32 - - // Input hash chains - // hashHead[hashValue] contains the largest inputIndex with the specified hash value - // If hashHead[hashValue] is within the current window, then - // hashPrev[hashHead[hashValue] & windowMask] contains the previous index - // with the same hash value. - hashHead [hashSize]uint32 - hashPrev [windowSize]uint32 -} - -type compressor struct { - compressionLevel - - h *huffmanEncoder - w *huffmanBitWriter - - // compression algorithm - fill func(*compressor, []byte) int // copy data to window - step func(*compressor) // process window - - window []byte - windowEnd int - blockStart int // window index where current tokens start - err error - - // queued output tokens - tokens tokens - fast fastEnc - state *advancedState - - sync bool // requesting flush - byteAvailable bool // if true, still need to process window[index-1]. -} - -func (d *compressor) fillDeflate(b []byte) int { - s := d.state - if s.index >= 2*windowSize-(minMatchLength+maxMatchLength) { - // shift the window by windowSize - //copy(d.window[:], d.window[windowSize:2*windowSize]) - *(*[windowSize]byte)(d.window) = *(*[windowSize]byte)(d.window[windowSize:]) - s.index -= windowSize - d.windowEnd -= windowSize - if d.blockStart >= windowSize { - d.blockStart -= windowSize - } else { - d.blockStart = math.MaxInt32 - } - s.hashOffset += windowSize - if s.hashOffset > maxHashOffset { - delta := s.hashOffset - 1 - s.hashOffset -= delta - s.chainHead -= delta - // Iterate over slices instead of arrays to avoid copying - // the entire table onto the stack (Issue #18625). - for i, v := range s.hashPrev[:] { - if int(v) > delta { - s.hashPrev[i] = uint32(int(v) - delta) - } else { - s.hashPrev[i] = 0 - } - } - for i, v := range s.hashHead[:] { - if int(v) > delta { - s.hashHead[i] = uint32(int(v) - delta) - } else { - s.hashHead[i] = 0 - } - } - } - } - n := copy(d.window[d.windowEnd:], b) - d.windowEnd += n - return n -} - -func (d *compressor) writeBlock(tok *tokens, index int, eof bool) error { - if index > 0 || eof { - var window []byte - if d.blockStart <= index { - window = d.window[d.blockStart:index] - } - d.blockStart = index - //d.w.writeBlock(tok, eof, window) - d.w.writeBlockDynamic(tok, eof, window, d.sync) - return d.w.err - } - return nil -} - -// writeBlockSkip writes the current block and uses the number of tokens -// to determine if the block should be stored on no matches, or -// only huffman encoded. -func (d *compressor) writeBlockSkip(tok *tokens, index int, eof bool) error { - if index > 0 || eof { - if d.blockStart <= index { - window := d.window[d.blockStart:index] - // If we removed less than a 64th of all literals - // we huffman compress the block. - if int(tok.n) > len(window)-int(tok.n>>6) { - d.w.writeBlockHuff(eof, window, d.sync) - } else { - // Write a dynamic huffman block. - d.w.writeBlockDynamic(tok, eof, window, d.sync) - } - } else { - d.w.writeBlock(tok, eof, nil) - } - d.blockStart = index - return d.w.err - } - return nil -} - -// fillWindow will fill the current window with the supplied -// dictionary and calculate all hashes. -// This is much faster than doing a full encode. -// Should only be used after a start/reset. -func (d *compressor) fillWindow(b []byte) { - // Do not fill window if we are in store-only or huffman mode. - if d.level <= 0 { - return - } - if d.fast != nil { - // encode the last data, but discard the result - if len(b) > maxMatchOffset { - b = b[len(b)-maxMatchOffset:] - } - d.fast.Encode(&d.tokens, b) - d.tokens.Reset() - return - } - s := d.state - // If we are given too much, cut it. - if len(b) > windowSize { - b = b[len(b)-windowSize:] - } - // Add all to window. - n := copy(d.window[d.windowEnd:], b) - - // Calculate 256 hashes at the time (more L1 cache hits) - loops := (n + 256 - minMatchLength) / 256 - for j := 0; j < loops; j++ { - startindex := j * 256 - end := startindex + 256 + minMatchLength - 1 - if end > n { - end = n - } - tocheck := d.window[startindex:end] - dstSize := len(tocheck) - minMatchLength + 1 - - if dstSize <= 0 { - continue - } - - dst := s.hashMatch[:dstSize] - bulkHash4(tocheck, dst) - var newH uint32 - for i, val := range dst { - di := i + startindex - newH = val & hashMask - // Get previous value with the same hash. - // Our chain should point to the previous value. - s.hashPrev[di&windowMask] = s.hashHead[newH] - // Set the head of the hash chain to us. - s.hashHead[newH] = uint32(di + s.hashOffset) - } - } - // Update window information. - d.windowEnd += n - s.index = n -} - -// Try to find a match starting at index whose length is greater than prevSize. -// We only look at chainCount possibilities before giving up. -// pos = s.index, prevHead = s.chainHead-s.hashOffset, prevLength=minMatchLength-1, lookahead -func (d *compressor) findMatch(pos int, prevHead int, lookahead int) (length, offset int, ok bool) { - minMatchLook := maxMatchLength - if lookahead < minMatchLook { - minMatchLook = lookahead - } - - win := d.window[0 : pos+minMatchLook] - - // We quit when we get a match that's at least nice long - nice := len(win) - pos - if d.nice < nice { - nice = d.nice - } - - // If we've got a match that's good enough, only look in 1/4 the chain. - tries := d.chain - length = minMatchLength - 1 - - wEnd := win[pos+length] - wPos := win[pos:] - minIndex := pos - windowSize - if minIndex < 0 { - minIndex = 0 - } - offset = 0 - - if d.chain < 100 { - for i := prevHead; tries > 0; tries-- { - if wEnd == win[i+length] { - n := matchLen(win[i:i+minMatchLook], wPos) - if n > length { - length = n - offset = pos - i - ok = true - if n >= nice { - // The match is good enough that we don't try to find a better one. - break - } - wEnd = win[pos+n] - } - } - if i <= minIndex { - // hashPrev[i & windowMask] has already been overwritten, so stop now. - break - } - i = int(d.state.hashPrev[i&windowMask]) - d.state.hashOffset - if i < minIndex { - break - } - } - return - } - - // Minimum gain to accept a match. - cGain := 4 - - // Some like it higher (CSV), some like it lower (JSON) - const baseCost = 3 - // Base is 4 bytes at with an additional cost. - // Matches must be better than this. - - for i := prevHead; tries > 0; tries-- { - if wEnd == win[i+length] { - n := matchLen(win[i:i+minMatchLook], wPos) - if n > length { - // Calculate gain. Estimate - newGain := d.h.bitLengthRaw(wPos[:n]) - int(offsetExtraBits[offsetCode(uint32(pos-i))]) - baseCost - int(lengthExtraBits[lengthCodes[(n-3)&255]]) - - //fmt.Println("gain:", newGain, "prev:", cGain, "raw:", d.h.bitLengthRaw(wPos[:n]), "this-len:", n, "prev-len:", length) - if newGain > cGain { - length = n - offset = pos - i - cGain = newGain - ok = true - if n >= nice { - // The match is good enough that we don't try to find a better one. - break - } - wEnd = win[pos+n] - } - } - } - if i <= minIndex { - // hashPrev[i & windowMask] has already been overwritten, so stop now. - break - } - i = int(d.state.hashPrev[i&windowMask]) - d.state.hashOffset - if i < minIndex { - break - } - } - return -} - -func (d *compressor) writeStoredBlock(buf []byte) error { - if d.w.writeStoredHeader(len(buf), false); d.w.err != nil { - return d.w.err - } - d.w.writeBytes(buf) - return d.w.err -} - -// hash4 returns a hash representation of the first 4 bytes -// of the supplied slice. -// The caller must ensure that len(b) >= 4. -func hash4(b []byte) uint32 { - return hash4u(binary.LittleEndian.Uint32(b), hashBits) -} - -// hash4 returns the hash of u to fit in a hash table with h bits. -// Preferably h should be a constant and should always be <32. -func hash4u(u uint32, h uint8) uint32 { - return (u * prime4bytes) >> (32 - h) -} - -// bulkHash4 will compute hashes using the same -// algorithm as hash4 -func bulkHash4(b []byte, dst []uint32) { - if len(b) < 4 { - return - } - hb := binary.LittleEndian.Uint32(b) - - dst[0] = hash4u(hb, hashBits) - end := len(b) - 4 + 1 - for i := 1; i < end; i++ { - hb = (hb >> 8) | uint32(b[i+3])<<24 - dst[i] = hash4u(hb, hashBits) - } -} - -func (d *compressor) initDeflate() { - d.window = make([]byte, 2*windowSize) - d.byteAvailable = false - d.err = nil - if d.state == nil { - return - } - s := d.state - s.index = 0 - s.hashOffset = 1 - s.length = minMatchLength - 1 - s.offset = 0 - s.chainHead = -1 -} - -// deflateLazy is the same as deflate, but with d.fastSkipHashing == skipNever, -// meaning it always has lazy matching on. -func (d *compressor) deflateLazy() { - s := d.state - // Sanity enables additional runtime tests. - // It's intended to be used during development - // to supplement the currently ad-hoc unit tests. - const sanity = debugDeflate - - if d.windowEnd-s.index < minMatchLength+maxMatchLength && !d.sync { - return - } - if d.windowEnd != s.index && d.chain > 100 { - // Get literal huffman coder. - if d.h == nil { - d.h = newHuffmanEncoder(maxFlateBlockTokens) - } - var tmp [256]uint16 - for _, v := range d.window[s.index:d.windowEnd] { - tmp[v]++ - } - d.h.generate(tmp[:], 15) - } - - s.maxInsertIndex = d.windowEnd - (minMatchLength - 1) - - for { - if sanity && s.index > d.windowEnd { - panic("index > windowEnd") - } - lookahead := d.windowEnd - s.index - if lookahead < minMatchLength+maxMatchLength { - if !d.sync { - return - } - if sanity && s.index > d.windowEnd { - panic("index > windowEnd") - } - if lookahead == 0 { - // Flush current output block if any. - if d.byteAvailable { - // There is still one pending token that needs to be flushed - d.tokens.AddLiteral(d.window[s.index-1]) - d.byteAvailable = false - } - if d.tokens.n > 0 { - if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil { - return - } - d.tokens.Reset() - } - return - } - } - if s.index < s.maxInsertIndex { - // Update the hash - hash := hash4(d.window[s.index:]) - ch := s.hashHead[hash] - s.chainHead = int(ch) - s.hashPrev[s.index&windowMask] = ch - s.hashHead[hash] = uint32(s.index + s.hashOffset) - } - prevLength := s.length - prevOffset := s.offset - s.length = minMatchLength - 1 - s.offset = 0 - minIndex := s.index - windowSize - if minIndex < 0 { - minIndex = 0 - } - - if s.chainHead-s.hashOffset >= minIndex && lookahead > prevLength && prevLength < d.lazy { - if newLength, newOffset, ok := d.findMatch(s.index, s.chainHead-s.hashOffset, lookahead); ok { - s.length = newLength - s.offset = newOffset - } - } - - if prevLength >= minMatchLength && s.length <= prevLength { - // No better match, but check for better match at end... - // - // Skip forward a number of bytes. - // Offset of 2 seems to yield best results. 3 is sometimes better. - const checkOff = 2 - - // Check all, except full length - if prevLength < maxMatchLength-checkOff { - prevIndex := s.index - 1 - if prevIndex+prevLength < s.maxInsertIndex { - end := lookahead - if lookahead > maxMatchLength+checkOff { - end = maxMatchLength + checkOff - } - end += prevIndex - - // Hash at match end. - h := hash4(d.window[prevIndex+prevLength:]) - ch2 := int(s.hashHead[h]) - s.hashOffset - prevLength - if prevIndex-ch2 != prevOffset && ch2 > minIndex+checkOff { - length := matchLen(d.window[prevIndex+checkOff:end], d.window[ch2+checkOff:]) - // It seems like a pure length metric is best. - if length > prevLength { - prevLength = length - prevOffset = prevIndex - ch2 - - // Extend back... - for i := checkOff - 1; i >= 0; i-- { - if prevLength >= maxMatchLength || d.window[prevIndex+i] != d.window[ch2+i] { - // Emit tokens we "owe" - for j := 0; j <= i; j++ { - d.tokens.AddLiteral(d.window[prevIndex+j]) - if d.tokens.n == maxFlateBlockTokens { - // The block includes the current character - if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil { - return - } - d.tokens.Reset() - } - s.index++ - if s.index < s.maxInsertIndex { - h := hash4(d.window[s.index:]) - ch := s.hashHead[h] - s.chainHead = int(ch) - s.hashPrev[s.index&windowMask] = ch - s.hashHead[h] = uint32(s.index + s.hashOffset) - } - } - break - } else { - prevLength++ - } - } - } else if false { - // Check one further ahead. - // Only rarely better, disabled for now. - prevIndex++ - h := hash4(d.window[prevIndex+prevLength:]) - ch2 := int(s.hashHead[h]) - s.hashOffset - prevLength - if prevIndex-ch2 != prevOffset && ch2 > minIndex+checkOff { - length := matchLen(d.window[prevIndex+checkOff:end], d.window[ch2+checkOff:]) - // It seems like a pure length metric is best. - if length > prevLength+checkOff { - prevLength = length - prevOffset = prevIndex - ch2 - prevIndex-- - - // Extend back... - for i := checkOff; i >= 0; i-- { - if prevLength >= maxMatchLength || d.window[prevIndex+i] != d.window[ch2+i-1] { - // Emit tokens we "owe" - for j := 0; j <= i; j++ { - d.tokens.AddLiteral(d.window[prevIndex+j]) - if d.tokens.n == maxFlateBlockTokens { - // The block includes the current character - if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil { - return - } - d.tokens.Reset() - } - s.index++ - if s.index < s.maxInsertIndex { - h := hash4(d.window[s.index:]) - ch := s.hashHead[h] - s.chainHead = int(ch) - s.hashPrev[s.index&windowMask] = ch - s.hashHead[h] = uint32(s.index + s.hashOffset) - } - } - break - } else { - prevLength++ - } - } - } - } - } - } - } - } - // There was a match at the previous step, and the current match is - // not better. Output the previous match. - d.tokens.AddMatch(uint32(prevLength-3), uint32(prevOffset-minOffsetSize)) - - // Insert in the hash table all strings up to the end of the match. - // index and index-1 are already inserted. If there is not enough - // lookahead, the last two strings are not inserted into the hash - // table. - newIndex := s.index + prevLength - 1 - // Calculate missing hashes - end := newIndex - if end > s.maxInsertIndex { - end = s.maxInsertIndex - } - end += minMatchLength - 1 - startindex := s.index + 1 - if startindex > s.maxInsertIndex { - startindex = s.maxInsertIndex - } - tocheck := d.window[startindex:end] - dstSize := len(tocheck) - minMatchLength + 1 - if dstSize > 0 { - dst := s.hashMatch[:dstSize] - bulkHash4(tocheck, dst) - var newH uint32 - for i, val := range dst { - di := i + startindex - newH = val & hashMask - // Get previous value with the same hash. - // Our chain should point to the previous value. - s.hashPrev[di&windowMask] = s.hashHead[newH] - // Set the head of the hash chain to us. - s.hashHead[newH] = uint32(di + s.hashOffset) - } - } - - s.index = newIndex - d.byteAvailable = false - s.length = minMatchLength - 1 - if d.tokens.n == maxFlateBlockTokens { - // The block includes the current character - if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil { - return - } - d.tokens.Reset() - } - s.ii = 0 - } else { - // Reset, if we got a match this run. - if s.length >= minMatchLength { - s.ii = 0 - } - // We have a byte waiting. Emit it. - if d.byteAvailable { - s.ii++ - d.tokens.AddLiteral(d.window[s.index-1]) - if d.tokens.n == maxFlateBlockTokens { - if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil { - return - } - d.tokens.Reset() - } - s.index++ - - // If we have a long run of no matches, skip additional bytes - // Resets when s.ii overflows after 64KB. - if n := int(s.ii) - d.chain; n > 0 { - n = 1 + int(n>>6) - for j := 0; j < n; j++ { - if s.index >= d.windowEnd-1 { - break - } - d.tokens.AddLiteral(d.window[s.index-1]) - if d.tokens.n == maxFlateBlockTokens { - if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil { - return - } - d.tokens.Reset() - } - // Index... - if s.index < s.maxInsertIndex { - h := hash4(d.window[s.index:]) - ch := s.hashHead[h] - s.chainHead = int(ch) - s.hashPrev[s.index&windowMask] = ch - s.hashHead[h] = uint32(s.index + s.hashOffset) - } - s.index++ - } - // Flush last byte - d.tokens.AddLiteral(d.window[s.index-1]) - d.byteAvailable = false - // s.length = minMatchLength - 1 // not needed, since s.ii is reset above, so it should never be > minMatchLength - if d.tokens.n == maxFlateBlockTokens { - if d.err = d.writeBlock(&d.tokens, s.index, false); d.err != nil { - return - } - d.tokens.Reset() - } - } - } else { - s.index++ - d.byteAvailable = true - } - } - } -} - -func (d *compressor) store() { - if d.windowEnd > 0 && (d.windowEnd == maxStoreBlockSize || d.sync) { - d.err = d.writeStoredBlock(d.window[:d.windowEnd]) - d.windowEnd = 0 - } -} - -// fillWindow will fill the buffer with data for huffman-only compression. -// The number of bytes copied is returned. -func (d *compressor) fillBlock(b []byte) int { - n := copy(d.window[d.windowEnd:], b) - d.windowEnd += n - return n -} - -// storeHuff will compress and store the currently added data, -// if enough has been accumulated or we at the end of the stream. -// Any error that occurred will be in d.err -func (d *compressor) storeHuff() { - if d.windowEnd < len(d.window) && !d.sync || d.windowEnd == 0 { - return - } - d.w.writeBlockHuff(false, d.window[:d.windowEnd], d.sync) - d.err = d.w.err - d.windowEnd = 0 -} - -// storeFast will compress and store the currently added data, -// if enough has been accumulated or we at the end of the stream. -// Any error that occurred will be in d.err -func (d *compressor) storeFast() { - // We only compress if we have maxStoreBlockSize. - if d.windowEnd < len(d.window) { - if !d.sync { - return - } - // Handle extremely small sizes. - if d.windowEnd < 128 { - if d.windowEnd == 0 { - return - } - if d.windowEnd <= 32 { - d.err = d.writeStoredBlock(d.window[:d.windowEnd]) - } else { - d.w.writeBlockHuff(false, d.window[:d.windowEnd], true) - d.err = d.w.err - } - d.tokens.Reset() - d.windowEnd = 0 - d.fast.Reset() - return - } - } - - d.fast.Encode(&d.tokens, d.window[:d.windowEnd]) - // If we made zero matches, store the block as is. - if d.tokens.n == 0 { - d.err = d.writeStoredBlock(d.window[:d.windowEnd]) - // If we removed less than 1/16th, huffman compress the block. - } else if int(d.tokens.n) > d.windowEnd-(d.windowEnd>>4) { - d.w.writeBlockHuff(false, d.window[:d.windowEnd], d.sync) - d.err = d.w.err - } else { - d.w.writeBlockDynamic(&d.tokens, false, d.window[:d.windowEnd], d.sync) - d.err = d.w.err - } - d.tokens.Reset() - d.windowEnd = 0 -} - -// write will add input byte to the stream. -// Unless an error occurs all bytes will be consumed. -func (d *compressor) write(b []byte) (n int, err error) { - if d.err != nil { - return 0, d.err - } - n = len(b) - for len(b) > 0 { - if d.windowEnd == len(d.window) || d.sync { - d.step(d) - } - b = b[d.fill(d, b):] - if d.err != nil { - return 0, d.err - } - } - return n, d.err -} - -func (d *compressor) syncFlush() error { - d.sync = true - if d.err != nil { - return d.err - } - d.step(d) - if d.err == nil { - d.w.writeStoredHeader(0, false) - d.w.flush() - d.err = d.w.err - } - d.sync = false - return d.err -} - -func (d *compressor) init(w io.Writer, level int) (err error) { - d.w = newHuffmanBitWriter(w) - - switch { - case level == NoCompression: - d.window = make([]byte, maxStoreBlockSize) - d.fill = (*compressor).fillBlock - d.step = (*compressor).store - case level == ConstantCompression: - d.w.logNewTablePenalty = 10 - d.window = make([]byte, 32<<10) - d.fill = (*compressor).fillBlock - d.step = (*compressor).storeHuff - case level == DefaultCompression: - level = 5 - fallthrough - case level >= 1 && level <= 6: - d.w.logNewTablePenalty = 7 - d.fast = newFastEnc(level) - d.window = make([]byte, maxStoreBlockSize) - d.fill = (*compressor).fillBlock - d.step = (*compressor).storeFast - case 7 <= level && level <= 9: - d.w.logNewTablePenalty = 8 - d.state = &advancedState{} - d.compressionLevel = levels[level] - d.initDeflate() - d.fill = (*compressor).fillDeflate - d.step = (*compressor).deflateLazy - case -level >= MinCustomWindowSize && -level <= MaxCustomWindowSize: - d.w.logNewTablePenalty = 7 - d.fast = &fastEncL5Window{maxOffset: int32(-level), cur: maxStoreBlockSize} - d.window = make([]byte, maxStoreBlockSize) - d.fill = (*compressor).fillBlock - d.step = (*compressor).storeFast - default: - return fmt.Errorf("flate: invalid compression level %d: want value in range [-2, 9]", level) - } - d.level = level - return nil -} - -// reset the state of the compressor. -func (d *compressor) reset(w io.Writer) { - d.w.reset(w) - d.sync = false - d.err = nil - // We only need to reset a few things for Snappy. - if d.fast != nil { - d.fast.Reset() - d.windowEnd = 0 - d.tokens.Reset() - return - } - switch d.compressionLevel.chain { - case 0: - // level was NoCompression or ConstantCompresssion. - d.windowEnd = 0 - default: - s := d.state - s.chainHead = -1 - for i := range s.hashHead { - s.hashHead[i] = 0 - } - for i := range s.hashPrev { - s.hashPrev[i] = 0 - } - s.hashOffset = 1 - s.index, d.windowEnd = 0, 0 - d.blockStart, d.byteAvailable = 0, false - d.tokens.Reset() - s.length = minMatchLength - 1 - s.offset = 0 - s.ii = 0 - s.maxInsertIndex = 0 - } -} - -func (d *compressor) close() error { - if d.err != nil { - return d.err - } - d.sync = true - d.step(d) - if d.err != nil { - return d.err - } - if d.w.writeStoredHeader(0, true); d.w.err != nil { - return d.w.err - } - d.w.flush() - d.w.reset(nil) - return d.w.err -} - -// NewWriter returns a new Writer compressing data at the given level. -// Following zlib, levels range from 1 (BestSpeed) to 9 (BestCompression); -// higher levels typically run slower but compress more. -// Level 0 (NoCompression) does not attempt any compression; it only adds the -// necessary DEFLATE framing. -// Level -1 (DefaultCompression) uses the default compression level. -// Level -2 (ConstantCompression) will use Huffman compression only, giving -// a very fast compression for all types of input, but sacrificing considerable -// compression efficiency. -// -// If level is in the range [-2, 9] then the error returned will be nil. -// Otherwise the error returned will be non-nil. -func NewWriter(w io.Writer, level int) (*Writer, error) { - var dw Writer - if err := dw.d.init(w, level); err != nil { - return nil, err - } - return &dw, nil -} - -// NewWriterDict is like NewWriter but initializes the new -// Writer with a preset dictionary. The returned Writer behaves -// as if the dictionary had been written to it without producing -// any compressed output. The compressed data written to w -// can only be decompressed by a Reader initialized with the -// same dictionary. -func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, error) { - zw, err := NewWriter(w, level) - if err != nil { - return nil, err - } - zw.d.fillWindow(dict) - zw.dict = append(zw.dict, dict...) // duplicate dictionary for Reset method. - return zw, err -} - -// MinCustomWindowSize is the minimum window size that can be sent to NewWriterWindow. -const MinCustomWindowSize = 32 - -// MaxCustomWindowSize is the maximum custom window that can be sent to NewWriterWindow. -const MaxCustomWindowSize = windowSize - -// NewWriterWindow returns a new Writer compressing data with a custom window size. -// windowSize must be from MinCustomWindowSize to MaxCustomWindowSize. -func NewWriterWindow(w io.Writer, windowSize int) (*Writer, error) { - if windowSize < MinCustomWindowSize { - return nil, errors.New("flate: requested window size less than MinWindowSize") - } - if windowSize > MaxCustomWindowSize { - return nil, errors.New("flate: requested window size bigger than MaxCustomWindowSize") - } - var dw Writer - if err := dw.d.init(w, -windowSize); err != nil { - return nil, err - } - return &dw, nil -} - -// A Writer takes data written to it and writes the compressed -// form of that data to an underlying writer (see NewWriter). -type Writer struct { - d compressor - dict []byte -} - -// Write writes data to w, which will eventually write the -// compressed form of data to its underlying writer. -func (w *Writer) Write(data []byte) (n int, err error) { - return w.d.write(data) -} - -// Flush flushes any pending data to the underlying writer. -// It is useful mainly in compressed network protocols, to ensure that -// a remote reader has enough data to reconstruct a packet. -// Flush does not return until the data has been written. -// Calling Flush when there is no pending data still causes the Writer -// to emit a sync marker of at least 4 bytes. -// If the underlying writer returns an error, Flush returns that error. -// -// In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH. -func (w *Writer) Flush() error { - // For more about flushing: - // http://www.bolet.org/~pornin/deflate-flush.html - return w.d.syncFlush() -} - -// Close flushes and closes the writer. -func (w *Writer) Close() error { - return w.d.close() -} - -// Reset discards the writer's state and makes it equivalent to -// the result of NewWriter or NewWriterDict called with dst -// and w's level and dictionary. -func (w *Writer) Reset(dst io.Writer) { - if len(w.dict) > 0 { - // w was created with NewWriterDict - w.d.reset(dst) - if dst != nil { - w.d.fillWindow(w.dict) - } - } else { - // w was created with NewWriter - w.d.reset(dst) - } -} - -// ResetDict discards the writer's state and makes it equivalent to -// the result of NewWriter or NewWriterDict called with dst -// and w's level, but sets a specific dictionary. -func (w *Writer) ResetDict(dst io.Writer, dict []byte) { - w.dict = dict - w.d.reset(dst) - w.d.fillWindow(w.dict) -} diff --git a/vendor/github.com/klauspost/compress/flate/dict_decoder.go b/vendor/github.com/klauspost/compress/flate/dict_decoder.go deleted file mode 100644 index bb36351a5..000000000 --- a/vendor/github.com/klauspost/compress/flate/dict_decoder.go +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flate - -// dictDecoder implements the LZ77 sliding dictionary as used in decompression. -// LZ77 decompresses data through sequences of two forms of commands: -// -// - Literal insertions: Runs of one or more symbols are inserted into the data -// stream as is. This is accomplished through the writeByte method for a -// single symbol, or combinations of writeSlice/writeMark for multiple symbols. -// Any valid stream must start with a literal insertion if no preset dictionary -// is used. -// -// - Backward copies: Runs of one or more symbols are copied from previously -// emitted data. Backward copies come as the tuple (dist, length) where dist -// determines how far back in the stream to copy from and length determines how -// many bytes to copy. Note that it is valid for the length to be greater than -// the distance. Since LZ77 uses forward copies, that situation is used to -// perform a form of run-length encoding on repeated runs of symbols. -// The writeCopy and tryWriteCopy are used to implement this command. -// -// For performance reasons, this implementation performs little to no sanity -// checks about the arguments. As such, the invariants documented for each -// method call must be respected. -type dictDecoder struct { - hist []byte // Sliding window history - - // Invariant: 0 <= rdPos <= wrPos <= len(hist) - wrPos int // Current output position in buffer - rdPos int // Have emitted hist[:rdPos] already - full bool // Has a full window length been written yet? -} - -// init initializes dictDecoder to have a sliding window dictionary of the given -// size. If a preset dict is provided, it will initialize the dictionary with -// the contents of dict. -func (dd *dictDecoder) init(size int, dict []byte) { - *dd = dictDecoder{hist: dd.hist} - - if cap(dd.hist) < size { - dd.hist = make([]byte, size) - } - dd.hist = dd.hist[:size] - - if len(dict) > len(dd.hist) { - dict = dict[len(dict)-len(dd.hist):] - } - dd.wrPos = copy(dd.hist, dict) - if dd.wrPos == len(dd.hist) { - dd.wrPos = 0 - dd.full = true - } - dd.rdPos = dd.wrPos -} - -// histSize reports the total amount of historical data in the dictionary. -func (dd *dictDecoder) histSize() int { - if dd.full { - return len(dd.hist) - } - return dd.wrPos -} - -// availRead reports the number of bytes that can be flushed by readFlush. -func (dd *dictDecoder) availRead() int { - return dd.wrPos - dd.rdPos -} - -// availWrite reports the available amount of output buffer space. -func (dd *dictDecoder) availWrite() int { - return len(dd.hist) - dd.wrPos -} - -// writeSlice returns a slice of the available buffer to write data to. -// -// This invariant will be kept: len(s) <= availWrite() -func (dd *dictDecoder) writeSlice() []byte { - return dd.hist[dd.wrPos:] -} - -// writeMark advances the writer pointer by cnt. -// -// This invariant must be kept: 0 <= cnt <= availWrite() -func (dd *dictDecoder) writeMark(cnt int) { - dd.wrPos += cnt -} - -// writeByte writes a single byte to the dictionary. -// -// This invariant must be kept: 0 < availWrite() -func (dd *dictDecoder) writeByte(c byte) { - dd.hist[dd.wrPos] = c - dd.wrPos++ -} - -// writeCopy copies a string at a given (dist, length) to the output. -// This returns the number of bytes copied and may be less than the requested -// length if the available space in the output buffer is too small. -// -// This invariant must be kept: 0 < dist <= histSize() -func (dd *dictDecoder) writeCopy(dist, length int) int { - dstBase := dd.wrPos - dstPos := dstBase - srcPos := dstPos - dist - endPos := dstPos + length - if endPos > len(dd.hist) { - endPos = len(dd.hist) - } - - // Copy non-overlapping section after destination position. - // - // This section is non-overlapping in that the copy length for this section - // is always less than or equal to the backwards distance. This can occur - // if a distance refers to data that wraps-around in the buffer. - // Thus, a backwards copy is performed here; that is, the exact bytes in - // the source prior to the copy is placed in the destination. - if srcPos < 0 { - srcPos += len(dd.hist) - dstPos += copy(dd.hist[dstPos:endPos], dd.hist[srcPos:]) - srcPos = 0 - } - - // Copy possibly overlapping section before destination position. - // - // This section can overlap if the copy length for this section is larger - // than the backwards distance. This is allowed by LZ77 so that repeated - // strings can be succinctly represented using (dist, length) pairs. - // Thus, a forwards copy is performed here; that is, the bytes copied is - // possibly dependent on the resulting bytes in the destination as the copy - // progresses along. This is functionally equivalent to the following: - // - // for i := 0; i < endPos-dstPos; i++ { - // dd.hist[dstPos+i] = dd.hist[srcPos+i] - // } - // dstPos = endPos - // - for dstPos < endPos { - dstPos += copy(dd.hist[dstPos:endPos], dd.hist[srcPos:dstPos]) - } - - dd.wrPos = dstPos - return dstPos - dstBase -} - -// tryWriteCopy tries to copy a string at a given (distance, length) to the -// output. This specialized version is optimized for short distances. -// -// This method is designed to be inlined for performance reasons. -// -// This invariant must be kept: 0 < dist <= histSize() -func (dd *dictDecoder) tryWriteCopy(dist, length int) int { - dstPos := dd.wrPos - endPos := dstPos + length - if dstPos < dist || endPos > len(dd.hist) { - return 0 - } - dstBase := dstPos - srcPos := dstPos - dist - - // Copy possibly overlapping section before destination position. -loop: - dstPos += copy(dd.hist[dstPos:endPos], dd.hist[srcPos:dstPos]) - if dstPos < endPos { - goto loop // Avoid for-loop so that this function can be inlined - } - - dd.wrPos = dstPos - return dstPos - dstBase -} - -// readFlush returns a slice of the historical buffer that is ready to be -// emitted to the user. The data returned by readFlush must be fully consumed -// before calling any other dictDecoder methods. -func (dd *dictDecoder) readFlush() []byte { - toRead := dd.hist[dd.rdPos:dd.wrPos] - dd.rdPos = dd.wrPos - if dd.wrPos == len(dd.hist) { - dd.wrPos, dd.rdPos = 0, 0 - dd.full = true - } - return toRead -} diff --git a/vendor/github.com/klauspost/compress/flate/fast_encoder.go b/vendor/github.com/klauspost/compress/flate/fast_encoder.go deleted file mode 100644 index c8124b5c4..000000000 --- a/vendor/github.com/klauspost/compress/flate/fast_encoder.go +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright 2011 The Snappy-Go Authors. All rights reserved. -// Modified for deflate by Klaus Post (c) 2015. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flate - -import ( - "encoding/binary" - "fmt" -) - -type fastEnc interface { - Encode(dst *tokens, src []byte) - Reset() -} - -func newFastEnc(level int) fastEnc { - switch level { - case 1: - return &fastEncL1{fastGen: fastGen{cur: maxStoreBlockSize}} - case 2: - return &fastEncL2{fastGen: fastGen{cur: maxStoreBlockSize}} - case 3: - return &fastEncL3{fastGen: fastGen{cur: maxStoreBlockSize}} - case 4: - return &fastEncL4{fastGen: fastGen{cur: maxStoreBlockSize}} - case 5: - return &fastEncL5{fastGen: fastGen{cur: maxStoreBlockSize}} - case 6: - return &fastEncL6{fastGen: fastGen{cur: maxStoreBlockSize}} - default: - panic("invalid level specified") - } -} - -const ( - tableBits = 15 // Bits used in the table - tableSize = 1 << tableBits // Size of the table - tableShift = 32 - tableBits // Right-shift to get the tableBits most significant bits of a uint32. - baseMatchOffset = 1 // The smallest match offset - baseMatchLength = 3 // The smallest match length per the RFC section 3.2.5 - maxMatchOffset = 1 << 15 // The largest match offset - - bTableBits = 17 // Bits used in the big tables - bTableSize = 1 << bTableBits // Size of the table - allocHistory = maxStoreBlockSize * 5 // Size to preallocate for history. - bufferReset = (1 << 31) - allocHistory - maxStoreBlockSize - 1 // Reset the buffer offset when reaching this. -) - -const ( - prime3bytes = 506832829 - prime4bytes = 2654435761 - prime5bytes = 889523592379 - prime6bytes = 227718039650203 - prime7bytes = 58295818150454627 - prime8bytes = 0xcf1bbcdcb7a56463 -) - -func load3232(b []byte, i int32) uint32 { - return binary.LittleEndian.Uint32(b[i:]) -} - -func load6432(b []byte, i int32) uint64 { - return binary.LittleEndian.Uint64(b[i:]) -} - -type tableEntry struct { - offset int32 -} - -// fastGen maintains the table for matches, -// and the previous byte block for level 2. -// This is the generic implementation. -type fastGen struct { - hist []byte - cur int32 -} - -func (e *fastGen) addBlock(src []byte) int32 { - // check if we have space already - if len(e.hist)+len(src) > cap(e.hist) { - if cap(e.hist) == 0 { - e.hist = make([]byte, 0, allocHistory) - } else { - if cap(e.hist) < maxMatchOffset*2 { - panic("unexpected buffer size") - } - // Move down - offset := int32(len(e.hist)) - maxMatchOffset - // copy(e.hist[0:maxMatchOffset], e.hist[offset:]) - *(*[maxMatchOffset]byte)(e.hist) = *(*[maxMatchOffset]byte)(e.hist[offset:]) - e.cur += offset - e.hist = e.hist[:maxMatchOffset] - } - } - s := int32(len(e.hist)) - e.hist = append(e.hist, src...) - return s -} - -type tableEntryPrev struct { - Cur tableEntry - Prev tableEntry -} - -// hash7 returns the hash of the lowest 7 bytes of u to fit in a hash table with h bits. -// Preferably h should be a constant and should always be <64. -func hash7(u uint64, h uint8) uint32 { - return uint32(((u << (64 - 56)) * prime7bytes) >> ((64 - h) & reg8SizeMask64)) -} - -// hashLen returns a hash of the lowest mls bytes of with length output bits. -// mls must be >=3 and <=8. Any other value will return hash for 4 bytes. -// length should always be < 32. -// Preferably length and mls should be a constant for inlining. -func hashLen(u uint64, length, mls uint8) uint32 { - switch mls { - case 3: - return (uint32(u<<8) * prime3bytes) >> (32 - length) - case 5: - return uint32(((u << (64 - 40)) * prime5bytes) >> (64 - length)) - case 6: - return uint32(((u << (64 - 48)) * prime6bytes) >> (64 - length)) - case 7: - return uint32(((u << (64 - 56)) * prime7bytes) >> (64 - length)) - case 8: - return uint32((u * prime8bytes) >> (64 - length)) - default: - return (uint32(u) * prime4bytes) >> (32 - length) - } -} - -// matchlen will return the match length between offsets and t in src. -// The maximum length returned is maxMatchLength - 4. -// It is assumed that s > t, that t >=0 and s < len(src). -func (e *fastGen) matchlen(s, t int32, src []byte) int32 { - if debugDecode { - if t >= s { - panic(fmt.Sprint("t >=s:", t, s)) - } - if int(s) >= len(src) { - panic(fmt.Sprint("s >= len(src):", s, len(src))) - } - if t < 0 { - panic(fmt.Sprint("t < 0:", t)) - } - if s-t > maxMatchOffset { - panic(fmt.Sprint(s, "-", t, "(", s-t, ") > maxMatchLength (", maxMatchOffset, ")")) - } - } - s1 := int(s) + maxMatchLength - 4 - if s1 > len(src) { - s1 = len(src) - } - - // Extend the match to be as long as possible. - return int32(matchLen(src[s:s1], src[t:])) -} - -// matchlenLong will return the match length between offsets and t in src. -// It is assumed that s > t, that t >=0 and s < len(src). -func (e *fastGen) matchlenLong(s, t int32, src []byte) int32 { - if debugDeflate { - if t >= s { - panic(fmt.Sprint("t >=s:", t, s)) - } - if int(s) >= len(src) { - panic(fmt.Sprint("s >= len(src):", s, len(src))) - } - if t < 0 { - panic(fmt.Sprint("t < 0:", t)) - } - if s-t > maxMatchOffset { - panic(fmt.Sprint(s, "-", t, "(", s-t, ") > maxMatchLength (", maxMatchOffset, ")")) - } - } - // Extend the match to be as long as possible. - return int32(matchLen(src[s:], src[t:])) -} - -// Reset the encoding table. -func (e *fastGen) Reset() { - if cap(e.hist) < allocHistory { - e.hist = make([]byte, 0, allocHistory) - } - // We offset current position so everything will be out of reach. - // If we are above the buffer reset it will be cleared anyway since len(hist) == 0. - if e.cur <= bufferReset { - e.cur += maxMatchOffset + int32(len(e.hist)) - } - e.hist = e.hist[:0] -} diff --git a/vendor/github.com/klauspost/compress/flate/huffman_bit_writer.go b/vendor/github.com/klauspost/compress/flate/huffman_bit_writer.go deleted file mode 100644 index f70594c34..000000000 --- a/vendor/github.com/klauspost/compress/flate/huffman_bit_writer.go +++ /dev/null @@ -1,1182 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flate - -import ( - "encoding/binary" - "fmt" - "io" - "math" -) - -const ( - // The largest offset code. - offsetCodeCount = 30 - - // The special code used to mark the end of a block. - endBlockMarker = 256 - - // The first length code. - lengthCodesStart = 257 - - // The number of codegen codes. - codegenCodeCount = 19 - badCode = 255 - - // maxPredefinedTokens is the maximum number of tokens - // where we check if fixed size is smaller. - maxPredefinedTokens = 250 - - // bufferFlushSize indicates the buffer size - // after which bytes are flushed to the writer. - // Should preferably be a multiple of 6, since - // we accumulate 6 bytes between writes to the buffer. - bufferFlushSize = 246 -) - -// Minimum length code that emits bits. -const lengthExtraBitsMinCode = 8 - -// The number of extra bits needed by length code X - LENGTH_CODES_START. -var lengthExtraBits = [32]uint8{ - /* 257 */ 0, 0, 0, - /* 260 */ 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, - /* 270 */ 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, - /* 280 */ 4, 5, 5, 5, 5, 0, -} - -// The length indicated by length code X - LENGTH_CODES_START. -var lengthBase = [32]uint8{ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, - 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, - 64, 80, 96, 112, 128, 160, 192, 224, 255, -} - -// Minimum offset code that emits bits. -const offsetExtraBitsMinCode = 4 - -// offset code word extra bits. -var offsetExtraBits = [32]int8{ - 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, - 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, - 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, - /* extended window */ - 14, 14, -} - -var offsetCombined = [32]uint32{} - -func init() { - var offsetBase = [32]uint32{ - /* normal deflate */ - 0x000000, 0x000001, 0x000002, 0x000003, 0x000004, - 0x000006, 0x000008, 0x00000c, 0x000010, 0x000018, - 0x000020, 0x000030, 0x000040, 0x000060, 0x000080, - 0x0000c0, 0x000100, 0x000180, 0x000200, 0x000300, - 0x000400, 0x000600, 0x000800, 0x000c00, 0x001000, - 0x001800, 0x002000, 0x003000, 0x004000, 0x006000, - - /* extended window */ - 0x008000, 0x00c000, - } - - for i := range offsetCombined[:] { - // Don't use extended window values... - if offsetExtraBits[i] == 0 || offsetBase[i] > 0x006000 { - continue - } - offsetCombined[i] = uint32(offsetExtraBits[i]) | (offsetBase[i] << 8) - } -} - -// The odd order in which the codegen code sizes are written. -var codegenOrder = []uint32{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15} - -type huffmanBitWriter struct { - // writer is the underlying writer. - // Do not use it directly; use the write method, which ensures - // that Write errors are sticky. - writer io.Writer - - // Data waiting to be written is bytes[0:nbytes] - // and then the low nbits of bits. - bits uint64 - nbits uint8 - nbytes uint8 - lastHuffMan bool - literalEncoding *huffmanEncoder - tmpLitEncoding *huffmanEncoder - offsetEncoding *huffmanEncoder - codegenEncoding *huffmanEncoder - err error - lastHeader int - // Set between 0 (reused block can be up to 2x the size) - logNewTablePenalty uint - bytes [256 + 8]byte - literalFreq [lengthCodesStart + 32]uint16 - offsetFreq [32]uint16 - codegenFreq [codegenCodeCount]uint16 - - // codegen must have an extra space for the final symbol. - codegen [literalCount + offsetCodeCount + 1]uint8 -} - -// Huffman reuse. -// -// The huffmanBitWriter supports reusing huffman tables and thereby combining block sections. -// -// This is controlled by several variables: -// -// If lastHeader is non-zero the Huffman table can be reused. -// This also indicates that a Huffman table has been generated that can output all -// possible symbols. -// It also indicates that an EOB has not yet been emitted, so if a new tabel is generated -// an EOB with the previous table must be written. -// -// If lastHuffMan is set, a table for outputting literals has been generated and offsets are invalid. -// -// An incoming block estimates the output size of a new table using a 'fresh' by calculating the -// optimal size and adding a penalty in 'logNewTablePenalty'. -// A Huffman table is not optimal, which is why we add a penalty, and generating a new table -// is slower both for compression and decompression. - -func newHuffmanBitWriter(w io.Writer) *huffmanBitWriter { - return &huffmanBitWriter{ - writer: w, - literalEncoding: newHuffmanEncoder(literalCount), - tmpLitEncoding: newHuffmanEncoder(literalCount), - codegenEncoding: newHuffmanEncoder(codegenCodeCount), - offsetEncoding: newHuffmanEncoder(offsetCodeCount), - } -} - -func (w *huffmanBitWriter) reset(writer io.Writer) { - w.writer = writer - w.bits, w.nbits, w.nbytes, w.err = 0, 0, 0, nil - w.lastHeader = 0 - w.lastHuffMan = false -} - -func (w *huffmanBitWriter) canReuse(t *tokens) (ok bool) { - a := t.offHist[:offsetCodeCount] - b := w.offsetEncoding.codes - b = b[:len(a)] - for i, v := range a { - if v != 0 && b[i].zero() { - return false - } - } - - a = t.extraHist[:literalCount-256] - b = w.literalEncoding.codes[256:literalCount] - b = b[:len(a)] - for i, v := range a { - if v != 0 && b[i].zero() { - return false - } - } - - a = t.litHist[:256] - b = w.literalEncoding.codes[:len(a)] - for i, v := range a { - if v != 0 && b[i].zero() { - return false - } - } - return true -} - -func (w *huffmanBitWriter) flush() { - if w.err != nil { - w.nbits = 0 - return - } - if w.lastHeader > 0 { - // We owe an EOB - w.writeCode(w.literalEncoding.codes[endBlockMarker]) - w.lastHeader = 0 - } - n := w.nbytes - for w.nbits != 0 { - w.bytes[n] = byte(w.bits) - w.bits >>= 8 - if w.nbits > 8 { // Avoid underflow - w.nbits -= 8 - } else { - w.nbits = 0 - } - n++ - } - w.bits = 0 - w.write(w.bytes[:n]) - w.nbytes = 0 -} - -func (w *huffmanBitWriter) write(b []byte) { - if w.err != nil { - return - } - _, w.err = w.writer.Write(b) -} - -func (w *huffmanBitWriter) writeBits(b int32, nb uint8) { - w.bits |= uint64(b) << (w.nbits & 63) - w.nbits += nb - if w.nbits >= 48 { - w.writeOutBits() - } -} - -func (w *huffmanBitWriter) writeBytes(bytes []byte) { - if w.err != nil { - return - } - n := w.nbytes - if w.nbits&7 != 0 { - w.err = InternalError("writeBytes with unfinished bits") - return - } - for w.nbits != 0 { - w.bytes[n] = byte(w.bits) - w.bits >>= 8 - w.nbits -= 8 - n++ - } - if n != 0 { - w.write(w.bytes[:n]) - } - w.nbytes = 0 - w.write(bytes) -} - -// RFC 1951 3.2.7 specifies a special run-length encoding for specifying -// the literal and offset lengths arrays (which are concatenated into a single -// array). This method generates that run-length encoding. -// -// The result is written into the codegen array, and the frequencies -// of each code is written into the codegenFreq array. -// Codes 0-15 are single byte codes. Codes 16-18 are followed by additional -// information. Code badCode is an end marker -// -// numLiterals The number of literals in literalEncoding -// numOffsets The number of offsets in offsetEncoding -// litenc, offenc The literal and offset encoder to use -func (w *huffmanBitWriter) generateCodegen(numLiterals int, numOffsets int, litEnc, offEnc *huffmanEncoder) { - for i := range w.codegenFreq { - w.codegenFreq[i] = 0 - } - // Note that we are using codegen both as a temporary variable for holding - // a copy of the frequencies, and as the place where we put the result. - // This is fine because the output is always shorter than the input used - // so far. - codegen := w.codegen[:] // cache - // Copy the concatenated code sizes to codegen. Put a marker at the end. - cgnl := codegen[:numLiterals] - for i := range cgnl { - cgnl[i] = litEnc.codes[i].len() - } - - cgnl = codegen[numLiterals : numLiterals+numOffsets] - for i := range cgnl { - cgnl[i] = offEnc.codes[i].len() - } - codegen[numLiterals+numOffsets] = badCode - - size := codegen[0] - count := 1 - outIndex := 0 - for inIndex := 1; size != badCode; inIndex++ { - // INVARIANT: We have seen "count" copies of size that have not yet - // had output generated for them. - nextSize := codegen[inIndex] - if nextSize == size { - count++ - continue - } - // We need to generate codegen indicating "count" of size. - if size != 0 { - codegen[outIndex] = size - outIndex++ - w.codegenFreq[size]++ - count-- - for count >= 3 { - n := 6 - if n > count { - n = count - } - codegen[outIndex] = 16 - outIndex++ - codegen[outIndex] = uint8(n - 3) - outIndex++ - w.codegenFreq[16]++ - count -= n - } - } else { - for count >= 11 { - n := 138 - if n > count { - n = count - } - codegen[outIndex] = 18 - outIndex++ - codegen[outIndex] = uint8(n - 11) - outIndex++ - w.codegenFreq[18]++ - count -= n - } - if count >= 3 { - // count >= 3 && count <= 10 - codegen[outIndex] = 17 - outIndex++ - codegen[outIndex] = uint8(count - 3) - outIndex++ - w.codegenFreq[17]++ - count = 0 - } - } - count-- - for ; count >= 0; count-- { - codegen[outIndex] = size - outIndex++ - w.codegenFreq[size]++ - } - // Set up invariant for next time through the loop. - size = nextSize - count = 1 - } - // Marker indicating the end of the codegen. - codegen[outIndex] = badCode -} - -func (w *huffmanBitWriter) codegens() int { - numCodegens := len(w.codegenFreq) - for numCodegens > 4 && w.codegenFreq[codegenOrder[numCodegens-1]] == 0 { - numCodegens-- - } - return numCodegens -} - -func (w *huffmanBitWriter) headerSize() (size, numCodegens int) { - numCodegens = len(w.codegenFreq) - for numCodegens > 4 && w.codegenFreq[codegenOrder[numCodegens-1]] == 0 { - numCodegens-- - } - return 3 + 5 + 5 + 4 + (3 * numCodegens) + - w.codegenEncoding.bitLength(w.codegenFreq[:]) + - int(w.codegenFreq[16])*2 + - int(w.codegenFreq[17])*3 + - int(w.codegenFreq[18])*7, numCodegens -} - -// dynamicSize returns the size of dynamically encoded data in bits. -func (w *huffmanBitWriter) dynamicReuseSize(litEnc, offEnc *huffmanEncoder) (size int) { - size = litEnc.bitLength(w.literalFreq[:]) + - offEnc.bitLength(w.offsetFreq[:]) - return size -} - -// dynamicSize returns the size of dynamically encoded data in bits. -func (w *huffmanBitWriter) dynamicSize(litEnc, offEnc *huffmanEncoder, extraBits int) (size, numCodegens int) { - header, numCodegens := w.headerSize() - size = header + - litEnc.bitLength(w.literalFreq[:]) + - offEnc.bitLength(w.offsetFreq[:]) + - extraBits - return size, numCodegens -} - -// extraBitSize will return the number of bits that will be written -// as "extra" bits on matches. -func (w *huffmanBitWriter) extraBitSize() int { - total := 0 - for i, n := range w.literalFreq[257:literalCount] { - total += int(n) * int(lengthExtraBits[i&31]) - } - for i, n := range w.offsetFreq[:offsetCodeCount] { - total += int(n) * int(offsetExtraBits[i&31]) - } - return total -} - -// fixedSize returns the size of dynamically encoded data in bits. -func (w *huffmanBitWriter) fixedSize(extraBits int) int { - return 3 + - fixedLiteralEncoding.bitLength(w.literalFreq[:]) + - fixedOffsetEncoding.bitLength(w.offsetFreq[:]) + - extraBits -} - -// storedSize calculates the stored size, including header. -// The function returns the size in bits and whether the block -// fits inside a single block. -func (w *huffmanBitWriter) storedSize(in []byte) (int, bool) { - if in == nil { - return 0, false - } - if len(in) <= maxStoreBlockSize { - return (len(in) + 5) * 8, true - } - return 0, false -} - -func (w *huffmanBitWriter) writeCode(c hcode) { - // The function does not get inlined if we "& 63" the shift. - w.bits |= c.code64() << (w.nbits & 63) - w.nbits += c.len() - if w.nbits >= 48 { - w.writeOutBits() - } -} - -// writeOutBits will write bits to the buffer. -func (w *huffmanBitWriter) writeOutBits() { - bits := w.bits - w.bits >>= 48 - w.nbits -= 48 - n := w.nbytes - - // We over-write, but faster... - binary.LittleEndian.PutUint64(w.bytes[n:], bits) - n += 6 - - if n >= bufferFlushSize { - if w.err != nil { - n = 0 - return - } - w.write(w.bytes[:n]) - n = 0 - } - - w.nbytes = n -} - -// Write the header of a dynamic Huffman block to the output stream. -// -// numLiterals The number of literals specified in codegen -// numOffsets The number of offsets specified in codegen -// numCodegens The number of codegens used in codegen -func (w *huffmanBitWriter) writeDynamicHeader(numLiterals int, numOffsets int, numCodegens int, isEof bool) { - if w.err != nil { - return - } - var firstBits int32 = 4 - if isEof { - firstBits = 5 - } - w.writeBits(firstBits, 3) - w.writeBits(int32(numLiterals-257), 5) - w.writeBits(int32(numOffsets-1), 5) - w.writeBits(int32(numCodegens-4), 4) - - for i := 0; i < numCodegens; i++ { - value := uint(w.codegenEncoding.codes[codegenOrder[i]].len()) - w.writeBits(int32(value), 3) - } - - i := 0 - for { - var codeWord = uint32(w.codegen[i]) - i++ - if codeWord == badCode { - break - } - w.writeCode(w.codegenEncoding.codes[codeWord]) - - switch codeWord { - case 16: - w.writeBits(int32(w.codegen[i]), 2) - i++ - case 17: - w.writeBits(int32(w.codegen[i]), 3) - i++ - case 18: - w.writeBits(int32(w.codegen[i]), 7) - i++ - } - } -} - -// writeStoredHeader will write a stored header. -// If the stored block is only used for EOF, -// it is replaced with a fixed huffman block. -func (w *huffmanBitWriter) writeStoredHeader(length int, isEof bool) { - if w.err != nil { - return - } - if w.lastHeader > 0 { - // We owe an EOB - w.writeCode(w.literalEncoding.codes[endBlockMarker]) - w.lastHeader = 0 - } - - // To write EOF, use a fixed encoding block. 10 bits instead of 5 bytes. - if length == 0 && isEof { - w.writeFixedHeader(isEof) - // EOB: 7 bits, value: 0 - w.writeBits(0, 7) - w.flush() - return - } - - var flag int32 - if isEof { - flag = 1 - } - w.writeBits(flag, 3) - w.flush() - w.writeBits(int32(length), 16) - w.writeBits(int32(^uint16(length)), 16) -} - -func (w *huffmanBitWriter) writeFixedHeader(isEof bool) { - if w.err != nil { - return - } - if w.lastHeader > 0 { - // We owe an EOB - w.writeCode(w.literalEncoding.codes[endBlockMarker]) - w.lastHeader = 0 - } - - // Indicate that we are a fixed Huffman block - var value int32 = 2 - if isEof { - value = 3 - } - w.writeBits(value, 3) -} - -// writeBlock will write a block of tokens with the smallest encoding. -// The original input can be supplied, and if the huffman encoded data -// is larger than the original bytes, the data will be written as a -// stored block. -// If the input is nil, the tokens will always be Huffman encoded. -func (w *huffmanBitWriter) writeBlock(tokens *tokens, eof bool, input []byte) { - if w.err != nil { - return - } - - tokens.AddEOB() - if w.lastHeader > 0 { - // We owe an EOB - w.writeCode(w.literalEncoding.codes[endBlockMarker]) - w.lastHeader = 0 - } - numLiterals, numOffsets := w.indexTokens(tokens, false) - w.generate() - var extraBits int - storedSize, storable := w.storedSize(input) - if storable { - extraBits = w.extraBitSize() - } - - // Figure out smallest code. - // Fixed Huffman baseline. - var literalEncoding = fixedLiteralEncoding - var offsetEncoding = fixedOffsetEncoding - var size = math.MaxInt32 - if tokens.n < maxPredefinedTokens { - size = w.fixedSize(extraBits) - } - - // Dynamic Huffman? - var numCodegens int - - // Generate codegen and codegenFrequencies, which indicates how to encode - // the literalEncoding and the offsetEncoding. - w.generateCodegen(numLiterals, numOffsets, w.literalEncoding, w.offsetEncoding) - w.codegenEncoding.generate(w.codegenFreq[:], 7) - dynamicSize, numCodegens := w.dynamicSize(w.literalEncoding, w.offsetEncoding, extraBits) - - if dynamicSize < size { - size = dynamicSize - literalEncoding = w.literalEncoding - offsetEncoding = w.offsetEncoding - } - - // Stored bytes? - if storable && storedSize <= size { - w.writeStoredHeader(len(input), eof) - w.writeBytes(input) - return - } - - // Huffman. - if literalEncoding == fixedLiteralEncoding { - w.writeFixedHeader(eof) - } else { - w.writeDynamicHeader(numLiterals, numOffsets, numCodegens, eof) - } - - // Write the tokens. - w.writeTokens(tokens.Slice(), literalEncoding.codes, offsetEncoding.codes) -} - -// writeBlockDynamic encodes a block using a dynamic Huffman table. -// This should be used if the symbols used have a disproportionate -// histogram distribution. -// If input is supplied and the compression savings are below 1/16th of the -// input size the block is stored. -func (w *huffmanBitWriter) writeBlockDynamic(tokens *tokens, eof bool, input []byte, sync bool) { - if w.err != nil { - return - } - - sync = sync || eof - if sync { - tokens.AddEOB() - } - - // We cannot reuse pure huffman table, and must mark as EOF. - if (w.lastHuffMan || eof) && w.lastHeader > 0 { - // We will not try to reuse. - w.writeCode(w.literalEncoding.codes[endBlockMarker]) - w.lastHeader = 0 - w.lastHuffMan = false - } - - // fillReuse enables filling of empty values. - // This will make encodings always reusable without testing. - // However, this does not appear to benefit on most cases. - const fillReuse = false - - // Check if we can reuse... - if !fillReuse && w.lastHeader > 0 && !w.canReuse(tokens) { - w.writeCode(w.literalEncoding.codes[endBlockMarker]) - w.lastHeader = 0 - } - - numLiterals, numOffsets := w.indexTokens(tokens, !sync) - extraBits := 0 - ssize, storable := w.storedSize(input) - - const usePrefs = true - if storable || w.lastHeader > 0 { - extraBits = w.extraBitSize() - } - - var size int - - // Check if we should reuse. - if w.lastHeader > 0 { - // Estimate size for using a new table. - // Use the previous header size as the best estimate. - newSize := w.lastHeader + tokens.EstimatedBits() - newSize += int(w.literalEncoding.codes[endBlockMarker].len()) + newSize>>w.logNewTablePenalty - - // The estimated size is calculated as an optimal table. - // We add a penalty to make it more realistic and re-use a bit more. - reuseSize := w.dynamicReuseSize(w.literalEncoding, w.offsetEncoding) + extraBits - - // Check if a new table is better. - if newSize < reuseSize { - // Write the EOB we owe. - w.writeCode(w.literalEncoding.codes[endBlockMarker]) - size = newSize - w.lastHeader = 0 - } else { - size = reuseSize - } - - if tokens.n < maxPredefinedTokens { - if preSize := w.fixedSize(extraBits) + 7; usePrefs && preSize < size { - // Check if we get a reasonable size decrease. - if storable && ssize <= size { - w.writeStoredHeader(len(input), eof) - w.writeBytes(input) - return - } - w.writeFixedHeader(eof) - if !sync { - tokens.AddEOB() - } - w.writeTokens(tokens.Slice(), fixedLiteralEncoding.codes, fixedOffsetEncoding.codes) - return - } - } - // Check if we get a reasonable size decrease. - if storable && ssize <= size { - w.writeStoredHeader(len(input), eof) - w.writeBytes(input) - return - } - } - - // We want a new block/table - if w.lastHeader == 0 { - if fillReuse && !sync { - w.fillTokens() - numLiterals, numOffsets = maxNumLit, maxNumDist - } else { - w.literalFreq[endBlockMarker] = 1 - } - - w.generate() - // Generate codegen and codegenFrequencies, which indicates how to encode - // the literalEncoding and the offsetEncoding. - w.generateCodegen(numLiterals, numOffsets, w.literalEncoding, w.offsetEncoding) - w.codegenEncoding.generate(w.codegenFreq[:], 7) - - var numCodegens int - if fillReuse && !sync { - // Reindex for accurate size... - w.indexTokens(tokens, true) - } - size, numCodegens = w.dynamicSize(w.literalEncoding, w.offsetEncoding, extraBits) - - // Store predefined, if we don't get a reasonable improvement. - if tokens.n < maxPredefinedTokens { - if preSize := w.fixedSize(extraBits); usePrefs && preSize <= size { - // Store bytes, if we don't get an improvement. - if storable && ssize <= preSize { - w.writeStoredHeader(len(input), eof) - w.writeBytes(input) - return - } - w.writeFixedHeader(eof) - if !sync { - tokens.AddEOB() - } - w.writeTokens(tokens.Slice(), fixedLiteralEncoding.codes, fixedOffsetEncoding.codes) - return - } - } - - if storable && ssize <= size { - // Store bytes, if we don't get an improvement. - w.writeStoredHeader(len(input), eof) - w.writeBytes(input) - return - } - - // Write Huffman table. - w.writeDynamicHeader(numLiterals, numOffsets, numCodegens, eof) - if !sync { - w.lastHeader, _ = w.headerSize() - } - w.lastHuffMan = false - } - - if sync { - w.lastHeader = 0 - } - // Write the tokens. - w.writeTokens(tokens.Slice(), w.literalEncoding.codes, w.offsetEncoding.codes) -} - -func (w *huffmanBitWriter) fillTokens() { - for i, v := range w.literalFreq[:literalCount] { - if v == 0 { - w.literalFreq[i] = 1 - } - } - for i, v := range w.offsetFreq[:offsetCodeCount] { - if v == 0 { - w.offsetFreq[i] = 1 - } - } -} - -// indexTokens indexes a slice of tokens, and updates -// literalFreq and offsetFreq, and generates literalEncoding -// and offsetEncoding. -// The number of literal and offset tokens is returned. -func (w *huffmanBitWriter) indexTokens(t *tokens, filled bool) (numLiterals, numOffsets int) { - //copy(w.literalFreq[:], t.litHist[:]) - *(*[256]uint16)(w.literalFreq[:]) = t.litHist - //copy(w.literalFreq[256:], t.extraHist[:]) - *(*[32]uint16)(w.literalFreq[256:]) = t.extraHist - w.offsetFreq = t.offHist - - if t.n == 0 { - return - } - if filled { - return maxNumLit, maxNumDist - } - // get the number of literals - numLiterals = len(w.literalFreq) - for w.literalFreq[numLiterals-1] == 0 { - numLiterals-- - } - // get the number of offsets - numOffsets = len(w.offsetFreq) - for numOffsets > 0 && w.offsetFreq[numOffsets-1] == 0 { - numOffsets-- - } - if numOffsets == 0 { - // We haven't found a single match. If we want to go with the dynamic encoding, - // we should count at least one offset to be sure that the offset huffman tree could be encoded. - w.offsetFreq[0] = 1 - numOffsets = 1 - } - return -} - -func (w *huffmanBitWriter) generate() { - w.literalEncoding.generate(w.literalFreq[:literalCount], 15) - w.offsetEncoding.generate(w.offsetFreq[:offsetCodeCount], 15) -} - -// writeTokens writes a slice of tokens to the output. -// codes for literal and offset encoding must be supplied. -func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode) { - if w.err != nil { - return - } - if len(tokens) == 0 { - return - } - - // Only last token should be endBlockMarker. - var deferEOB bool - if tokens[len(tokens)-1] == endBlockMarker { - tokens = tokens[:len(tokens)-1] - deferEOB = true - } - - // Create slices up to the next power of two to avoid bounds checks. - lits := leCodes[:256] - offs := oeCodes[:32] - lengths := leCodes[lengthCodesStart:] - lengths = lengths[:32] - - // Go 1.16 LOVES having these on stack. - bits, nbits, nbytes := w.bits, w.nbits, w.nbytes - - for _, t := range tokens { - if t < 256 { - //w.writeCode(lits[t.literal()]) - c := lits[t] - bits |= c.code64() << (nbits & 63) - nbits += c.len() - if nbits >= 48 { - binary.LittleEndian.PutUint64(w.bytes[nbytes:], bits) - //*(*uint64)(unsafe.Pointer(&w.bytes[nbytes])) = bits - bits >>= 48 - nbits -= 48 - nbytes += 6 - if nbytes >= bufferFlushSize { - if w.err != nil { - nbytes = 0 - return - } - _, w.err = w.writer.Write(w.bytes[:nbytes]) - nbytes = 0 - } - } - continue - } - - // Write the length - length := t.length() - lengthCode := lengthCode(length) & 31 - if false { - w.writeCode(lengths[lengthCode]) - } else { - // inlined - c := lengths[lengthCode] - bits |= c.code64() << (nbits & 63) - nbits += c.len() - if nbits >= 48 { - binary.LittleEndian.PutUint64(w.bytes[nbytes:], bits) - //*(*uint64)(unsafe.Pointer(&w.bytes[nbytes])) = bits - bits >>= 48 - nbits -= 48 - nbytes += 6 - if nbytes >= bufferFlushSize { - if w.err != nil { - nbytes = 0 - return - } - _, w.err = w.writer.Write(w.bytes[:nbytes]) - nbytes = 0 - } - } - } - - if lengthCode >= lengthExtraBitsMinCode { - extraLengthBits := lengthExtraBits[lengthCode] - //w.writeBits(extraLength, extraLengthBits) - extraLength := int32(length - lengthBase[lengthCode]) - bits |= uint64(extraLength) << (nbits & 63) - nbits += extraLengthBits - if nbits >= 48 { - binary.LittleEndian.PutUint64(w.bytes[nbytes:], bits) - //*(*uint64)(unsafe.Pointer(&w.bytes[nbytes])) = bits - bits >>= 48 - nbits -= 48 - nbytes += 6 - if nbytes >= bufferFlushSize { - if w.err != nil { - nbytes = 0 - return - } - _, w.err = w.writer.Write(w.bytes[:nbytes]) - nbytes = 0 - } - } - } - // Write the offset - offset := t.offset() - offsetCode := (offset >> 16) & 31 - if false { - w.writeCode(offs[offsetCode]) - } else { - // inlined - c := offs[offsetCode] - bits |= c.code64() << (nbits & 63) - nbits += c.len() - if nbits >= 48 { - binary.LittleEndian.PutUint64(w.bytes[nbytes:], bits) - //*(*uint64)(unsafe.Pointer(&w.bytes[nbytes])) = bits - bits >>= 48 - nbits -= 48 - nbytes += 6 - if nbytes >= bufferFlushSize { - if w.err != nil { - nbytes = 0 - return - } - _, w.err = w.writer.Write(w.bytes[:nbytes]) - nbytes = 0 - } - } - } - - if offsetCode >= offsetExtraBitsMinCode { - offsetComb := offsetCombined[offsetCode] - //w.writeBits(extraOffset, extraOffsetBits) - bits |= uint64((offset-(offsetComb>>8))&matchOffsetOnlyMask) << (nbits & 63) - nbits += uint8(offsetComb) - if nbits >= 48 { - binary.LittleEndian.PutUint64(w.bytes[nbytes:], bits) - //*(*uint64)(unsafe.Pointer(&w.bytes[nbytes])) = bits - bits >>= 48 - nbits -= 48 - nbytes += 6 - if nbytes >= bufferFlushSize { - if w.err != nil { - nbytes = 0 - return - } - _, w.err = w.writer.Write(w.bytes[:nbytes]) - nbytes = 0 - } - } - } - } - // Restore... - w.bits, w.nbits, w.nbytes = bits, nbits, nbytes - - if deferEOB { - w.writeCode(leCodes[endBlockMarker]) - } -} - -// huffOffset is a static offset encoder used for huffman only encoding. -// It can be reused since we will not be encoding offset values. -var huffOffset *huffmanEncoder - -func init() { - w := newHuffmanBitWriter(nil) - w.offsetFreq[0] = 1 - huffOffset = newHuffmanEncoder(offsetCodeCount) - huffOffset.generate(w.offsetFreq[:offsetCodeCount], 15) -} - -// writeBlockHuff encodes a block of bytes as either -// Huffman encoded literals or uncompressed bytes if the -// results only gains very little from compression. -func (w *huffmanBitWriter) writeBlockHuff(eof bool, input []byte, sync bool) { - if w.err != nil { - return - } - - // Clear histogram - for i := range w.literalFreq[:] { - w.literalFreq[i] = 0 - } - if !w.lastHuffMan { - for i := range w.offsetFreq[:] { - w.offsetFreq[i] = 0 - } - } - - const numLiterals = endBlockMarker + 1 - const numOffsets = 1 - - // Add everything as literals - // We have to estimate the header size. - // Assume header is around 70 bytes: - // https://stackoverflow.com/a/25454430 - const guessHeaderSizeBits = 70 * 8 - histogram(input, w.literalFreq[:numLiterals]) - ssize, storable := w.storedSize(input) - if storable && len(input) > 1024 { - // Quick check for incompressible content. - abs := float64(0) - avg := float64(len(input)) / 256 - max := float64(len(input) * 2) - for _, v := range w.literalFreq[:256] { - diff := float64(v) - avg - abs += diff * diff - if abs > max { - break - } - } - if abs < max { - if debugDeflate { - fmt.Println("stored", abs, "<", max) - } - // No chance we can compress this... - w.writeStoredHeader(len(input), eof) - w.writeBytes(input) - return - } - } - w.literalFreq[endBlockMarker] = 1 - w.tmpLitEncoding.generate(w.literalFreq[:numLiterals], 15) - estBits := w.tmpLitEncoding.canReuseBits(w.literalFreq[:numLiterals]) - if estBits < math.MaxInt32 { - estBits += w.lastHeader - if w.lastHeader == 0 { - estBits += guessHeaderSizeBits - } - estBits += estBits >> w.logNewTablePenalty - } - - // Store bytes, if we don't get a reasonable improvement. - if storable && ssize <= estBits { - if debugDeflate { - fmt.Println("stored,", ssize, "<=", estBits) - } - w.writeStoredHeader(len(input), eof) - w.writeBytes(input) - return - } - - if w.lastHeader > 0 { - reuseSize := w.literalEncoding.canReuseBits(w.literalFreq[:256]) - - if estBits < reuseSize { - if debugDeflate { - fmt.Println("NOT reusing, reuse:", reuseSize/8, "> new:", estBits/8, "header est:", w.lastHeader/8, "bytes") - } - // We owe an EOB - w.writeCode(w.literalEncoding.codes[endBlockMarker]) - w.lastHeader = 0 - } else if debugDeflate { - fmt.Println("reusing, reuse:", reuseSize/8, "> new:", estBits/8, "- header est:", w.lastHeader/8) - } - } - - count := 0 - if w.lastHeader == 0 { - // Use the temp encoding, so swap. - w.literalEncoding, w.tmpLitEncoding = w.tmpLitEncoding, w.literalEncoding - // Generate codegen and codegenFrequencies, which indicates how to encode - // the literalEncoding and the offsetEncoding. - w.generateCodegen(numLiterals, numOffsets, w.literalEncoding, huffOffset) - w.codegenEncoding.generate(w.codegenFreq[:], 7) - numCodegens := w.codegens() - - // Huffman. - w.writeDynamicHeader(numLiterals, numOffsets, numCodegens, eof) - w.lastHuffMan = true - w.lastHeader, _ = w.headerSize() - if debugDeflate { - count += w.lastHeader - fmt.Println("header:", count/8) - } - } - - encoding := w.literalEncoding.codes[:256] - // Go 1.16 LOVES having these on stack. At least 1.5x the speed. - bits, nbits, nbytes := w.bits, w.nbits, w.nbytes - - if debugDeflate { - count -= int(nbytes)*8 + int(nbits) - } - // Unroll, write 3 codes/loop. - // Fastest number of unrolls. - for len(input) > 3 { - // We must have at least 48 bits free. - if nbits >= 8 { - n := nbits >> 3 - binary.LittleEndian.PutUint64(w.bytes[nbytes:], bits) - bits >>= (n * 8) & 63 - nbits -= n * 8 - nbytes += n - } - if nbytes >= bufferFlushSize { - if w.err != nil { - nbytes = 0 - return - } - if debugDeflate { - count += int(nbytes) * 8 - } - _, w.err = w.writer.Write(w.bytes[:nbytes]) - nbytes = 0 - } - a, b := encoding[input[0]], encoding[input[1]] - bits |= a.code64() << (nbits & 63) - bits |= b.code64() << ((nbits + a.len()) & 63) - c := encoding[input[2]] - nbits += b.len() + a.len() - bits |= c.code64() << (nbits & 63) - nbits += c.len() - input = input[3:] - } - - // Remaining... - for _, t := range input { - if nbits >= 48 { - binary.LittleEndian.PutUint64(w.bytes[nbytes:], bits) - //*(*uint64)(unsafe.Pointer(&w.bytes[nbytes])) = bits - bits >>= 48 - nbits -= 48 - nbytes += 6 - if nbytes >= bufferFlushSize { - if w.err != nil { - nbytes = 0 - return - } - if debugDeflate { - count += int(nbytes) * 8 - } - _, w.err = w.writer.Write(w.bytes[:nbytes]) - nbytes = 0 - } - } - // Bitwriting inlined, ~30% speedup - c := encoding[t] - bits |= c.code64() << (nbits & 63) - - nbits += c.len() - if debugDeflate { - count += int(c.len()) - } - } - // Restore... - w.bits, w.nbits, w.nbytes = bits, nbits, nbytes - - if debugDeflate { - nb := count + int(nbytes)*8 + int(nbits) - fmt.Println("wrote", nb, "bits,", nb/8, "bytes.") - } - // Flush if needed to have space. - if w.nbits >= 48 { - w.writeOutBits() - } - - if eof || sync { - w.writeCode(w.literalEncoding.codes[endBlockMarker]) - w.lastHeader = 0 - w.lastHuffMan = false - } -} diff --git a/vendor/github.com/klauspost/compress/flate/huffman_code.go b/vendor/github.com/klauspost/compress/flate/huffman_code.go deleted file mode 100644 index be7b58b47..000000000 --- a/vendor/github.com/klauspost/compress/flate/huffman_code.go +++ /dev/null @@ -1,417 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flate - -import ( - "math" - "math/bits" -) - -const ( - maxBitsLimit = 16 - // number of valid literals - literalCount = 286 -) - -// hcode is a huffman code with a bit code and bit length. -type hcode uint32 - -func (h hcode) len() uint8 { - return uint8(h) -} - -func (h hcode) code64() uint64 { - return uint64(h >> 8) -} - -func (h hcode) zero() bool { - return h == 0 -} - -type huffmanEncoder struct { - codes []hcode - bitCount [17]int32 - - // Allocate a reusable buffer with the longest possible frequency table. - // Possible lengths are codegenCodeCount, offsetCodeCount and literalCount. - // The largest of these is literalCount, so we allocate for that case. - freqcache [literalCount + 1]literalNode -} - -type literalNode struct { - literal uint16 - freq uint16 -} - -// A levelInfo describes the state of the constructed tree for a given depth. -type levelInfo struct { - // Our level. for better printing - level int32 - - // The frequency of the last node at this level - lastFreq int32 - - // The frequency of the next character to add to this level - nextCharFreq int32 - - // The frequency of the next pair (from level below) to add to this level. - // Only valid if the "needed" value of the next lower level is 0. - nextPairFreq int32 - - // The number of chains remaining to generate for this level before moving - // up to the next level - needed int32 -} - -// set sets the code and length of an hcode. -func (h *hcode) set(code uint16, length uint8) { - *h = hcode(length) | (hcode(code) << 8) -} - -func newhcode(code uint16, length uint8) hcode { - return hcode(length) | (hcode(code) << 8) -} - -func reverseBits(number uint16, bitLength byte) uint16 { - return bits.Reverse16(number << ((16 - bitLength) & 15)) -} - -func maxNode() literalNode { return literalNode{math.MaxUint16, math.MaxUint16} } - -func newHuffmanEncoder(size int) *huffmanEncoder { - // Make capacity to next power of two. - c := uint(bits.Len32(uint32(size - 1))) - return &huffmanEncoder{codes: make([]hcode, size, 1<= 3 -// The cases of 0, 1, and 2 literals are handled by special case code. -// -// list An array of the literals with non-zero frequencies -// -// and their associated frequencies. The array is in order of increasing -// frequency, and has as its last element a special element with frequency -// MaxInt32 -// -// maxBits The maximum number of bits that should be used to encode any literal. -// -// Must be less than 16. -// -// return An integer array in which array[i] indicates the number of literals -// -// that should be encoded in i bits. -func (h *huffmanEncoder) bitCounts(list []literalNode, maxBits int32) []int32 { - if maxBits >= maxBitsLimit { - panic("flate: maxBits too large") - } - n := int32(len(list)) - list = list[0 : n+1] - list[n] = maxNode() - - // The tree can't have greater depth than n - 1, no matter what. This - // saves a little bit of work in some small cases - if maxBits > n-1 { - maxBits = n - 1 - } - - // Create information about each of the levels. - // A bogus "Level 0" whose sole purpose is so that - // level1.prev.needed==0. This makes level1.nextPairFreq - // be a legitimate value that never gets chosen. - var levels [maxBitsLimit]levelInfo - // leafCounts[i] counts the number of literals at the left - // of ancestors of the rightmost node at level i. - // leafCounts[i][j] is the number of literals at the left - // of the level j ancestor. - var leafCounts [maxBitsLimit][maxBitsLimit]int32 - - // Descending to only have 1 bounds check. - l2f := int32(list[2].freq) - l1f := int32(list[1].freq) - l0f := int32(list[0].freq) + int32(list[1].freq) - - for level := int32(1); level <= maxBits; level++ { - // For every level, the first two items are the first two characters. - // We initialize the levels as if we had already figured this out. - levels[level] = levelInfo{ - level: level, - lastFreq: l1f, - nextCharFreq: l2f, - nextPairFreq: l0f, - } - leafCounts[level][level] = 2 - if level == 1 { - levels[level].nextPairFreq = math.MaxInt32 - } - } - - // We need a total of 2*n - 2 items at top level and have already generated 2. - levels[maxBits].needed = 2*n - 4 - - level := uint32(maxBits) - for level < 16 { - l := &levels[level] - if l.nextPairFreq == math.MaxInt32 && l.nextCharFreq == math.MaxInt32 { - // We've run out of both leafs and pairs. - // End all calculations for this level. - // To make sure we never come back to this level or any lower level, - // set nextPairFreq impossibly large. - l.needed = 0 - levels[level+1].nextPairFreq = math.MaxInt32 - level++ - continue - } - - prevFreq := l.lastFreq - if l.nextCharFreq < l.nextPairFreq { - // The next item on this row is a leaf node. - n := leafCounts[level][level] + 1 - l.lastFreq = l.nextCharFreq - // Lower leafCounts are the same of the previous node. - leafCounts[level][level] = n - e := list[n] - if e.literal < math.MaxUint16 { - l.nextCharFreq = int32(e.freq) - } else { - l.nextCharFreq = math.MaxInt32 - } - } else { - // The next item on this row is a pair from the previous row. - // nextPairFreq isn't valid until we generate two - // more values in the level below - l.lastFreq = l.nextPairFreq - // Take leaf counts from the lower level, except counts[level] remains the same. - if true { - save := leafCounts[level][level] - leafCounts[level] = leafCounts[level-1] - leafCounts[level][level] = save - } else { - copy(leafCounts[level][:level], leafCounts[level-1][:level]) - } - levels[l.level-1].needed = 2 - } - - if l.needed--; l.needed == 0 { - // We've done everything we need to do for this level. - // Continue calculating one level up. Fill in nextPairFreq - // of that level with the sum of the two nodes we've just calculated on - // this level. - if l.level == maxBits { - // All done! - break - } - levels[l.level+1].nextPairFreq = prevFreq + l.lastFreq - level++ - } else { - // If we stole from below, move down temporarily to replenish it. - for levels[level-1].needed > 0 { - level-- - } - } - } - - // Somethings is wrong if at the end, the top level is null or hasn't used - // all of the leaves. - if leafCounts[maxBits][maxBits] != n { - panic("leafCounts[maxBits][maxBits] != n") - } - - bitCount := h.bitCount[:maxBits+1] - bits := 1 - counts := &leafCounts[maxBits] - for level := maxBits; level > 0; level-- { - // chain.leafCount gives the number of literals requiring at least "bits" - // bits to encode. - bitCount[bits] = counts[level] - counts[level-1] - bits++ - } - return bitCount -} - -// Look at the leaves and assign them a bit count and an encoding as specified -// in RFC 1951 3.2.2 -func (h *huffmanEncoder) assignEncodingAndSize(bitCount []int32, list []literalNode) { - code := uint16(0) - for n, bits := range bitCount { - code <<= 1 - if n == 0 || bits == 0 { - continue - } - // The literals list[len(list)-bits] .. list[len(list)-bits] - // are encoded using "bits" bits, and get the values - // code, code + 1, .... The code values are - // assigned in literal order (not frequency order). - chunk := list[len(list)-int(bits):] - - sortByLiteral(chunk) - for _, node := range chunk { - h.codes[node.literal] = newhcode(reverseBits(code, uint8(n)), uint8(n)) - code++ - } - list = list[0 : len(list)-int(bits)] - } -} - -// Update this Huffman Code object to be the minimum code for the specified frequency count. -// -// freq An array of frequencies, in which frequency[i] gives the frequency of literal i. -// maxBits The maximum number of bits to use for any literal. -func (h *huffmanEncoder) generate(freq []uint16, maxBits int32) { - list := h.freqcache[:len(freq)+1] - codes := h.codes[:len(freq)] - // Number of non-zero literals - count := 0 - // Set list to be the set of all non-zero literals and their frequencies - for i, f := range freq { - if f != 0 { - list[count] = literalNode{uint16(i), f} - count++ - } else { - codes[i] = 0 - } - } - list[count] = literalNode{} - - list = list[:count] - if count <= 2 { - // Handle the small cases here, because they are awkward for the general case code. With - // two or fewer literals, everything has bit length 1. - for i, node := range list { - // "list" is in order of increasing literal value. - h.codes[node.literal].set(uint16(i), 1) - } - return - } - sortByFreq(list) - - // Get the number of literals for each bit count - bitCount := h.bitCounts(list, maxBits) - // And do the assignment - h.assignEncodingAndSize(bitCount, list) -} - -// atLeastOne clamps the result between 1 and 15. -func atLeastOne(v float32) float32 { - if v < 1 { - return 1 - } - if v > 15 { - return 15 - } - return v -} - -func histogram(b []byte, h []uint16) { - if true && len(b) >= 8<<10 { - // Split for bigger inputs - histogramSplit(b, h) - } else { - h = h[:256] - for _, t := range b { - h[t]++ - } - } -} - -func histogramSplit(b []byte, h []uint16) { - // Tested, and slightly faster than 2-way. - // Writing to separate arrays and combining is also slightly slower. - h = h[:256] - for len(b)&3 != 0 { - h[b[0]]++ - b = b[1:] - } - n := len(b) / 4 - x, y, z, w := b[:n], b[n:], b[n+n:], b[n+n+n:] - y, z, w = y[:len(x)], z[:len(x)], w[:len(x)] - for i, t := range x { - v0 := &h[t] - v1 := &h[y[i]] - v3 := &h[w[i]] - v2 := &h[z[i]] - *v0++ - *v1++ - *v2++ - *v3++ - } -} diff --git a/vendor/github.com/klauspost/compress/flate/huffman_sortByFreq.go b/vendor/github.com/klauspost/compress/flate/huffman_sortByFreq.go deleted file mode 100644 index 6c05ba8c1..000000000 --- a/vendor/github.com/klauspost/compress/flate/huffman_sortByFreq.go +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flate - -// Sort sorts data. -// It makes one call to data.Len to determine n, and O(n*log(n)) calls to -// data.Less and data.Swap. The sort is not guaranteed to be stable. -func sortByFreq(data []literalNode) { - n := len(data) - quickSortByFreq(data, 0, n, maxDepth(n)) -} - -func quickSortByFreq(data []literalNode, a, b, maxDepth int) { - for b-a > 12 { // Use ShellSort for slices <= 12 elements - if maxDepth == 0 { - heapSort(data, a, b) - return - } - maxDepth-- - mlo, mhi := doPivotByFreq(data, a, b) - // Avoiding recursion on the larger subproblem guarantees - // a stack depth of at most lg(b-a). - if mlo-a < b-mhi { - quickSortByFreq(data, a, mlo, maxDepth) - a = mhi // i.e., quickSortByFreq(data, mhi, b) - } else { - quickSortByFreq(data, mhi, b, maxDepth) - b = mlo // i.e., quickSortByFreq(data, a, mlo) - } - } - if b-a > 1 { - // Do ShellSort pass with gap 6 - // It could be written in this simplified form cause b-a <= 12 - for i := a + 6; i < b; i++ { - if data[i].freq == data[i-6].freq && data[i].literal < data[i-6].literal || data[i].freq < data[i-6].freq { - data[i], data[i-6] = data[i-6], data[i] - } - } - insertionSortByFreq(data, a, b) - } -} - -func doPivotByFreq(data []literalNode, lo, hi int) (midlo, midhi int) { - m := int(uint(lo+hi) >> 1) // Written like this to avoid integer overflow. - if hi-lo > 40 { - // Tukey's ``Ninther,'' median of three medians of three. - s := (hi - lo) / 8 - medianOfThreeSortByFreq(data, lo, lo+s, lo+2*s) - medianOfThreeSortByFreq(data, m, m-s, m+s) - medianOfThreeSortByFreq(data, hi-1, hi-1-s, hi-1-2*s) - } - medianOfThreeSortByFreq(data, lo, m, hi-1) - - // Invariants are: - // data[lo] = pivot (set up by ChoosePivot) - // data[lo < i < a] < pivot - // data[a <= i < b] <= pivot - // data[b <= i < c] unexamined - // data[c <= i < hi-1] > pivot - // data[hi-1] >= pivot - pivot := lo - a, c := lo+1, hi-1 - - for ; a < c && (data[a].freq == data[pivot].freq && data[a].literal < data[pivot].literal || data[a].freq < data[pivot].freq); a++ { - } - b := a - for { - for ; b < c && (data[pivot].freq == data[b].freq && data[pivot].literal > data[b].literal || data[pivot].freq > data[b].freq); b++ { // data[b] <= pivot - } - for ; b < c && (data[pivot].freq == data[c-1].freq && data[pivot].literal < data[c-1].literal || data[pivot].freq < data[c-1].freq); c-- { // data[c-1] > pivot - } - if b >= c { - break - } - // data[b] > pivot; data[c-1] <= pivot - data[b], data[c-1] = data[c-1], data[b] - b++ - c-- - } - // If hi-c<3 then there are duplicates (by property of median of nine). - // Let's be a bit more conservative, and set border to 5. - protect := hi-c < 5 - if !protect && hi-c < (hi-lo)/4 { - // Lets test some points for equality to pivot - dups := 0 - if data[pivot].freq == data[hi-1].freq && data[pivot].literal > data[hi-1].literal || data[pivot].freq > data[hi-1].freq { // data[hi-1] = pivot - data[c], data[hi-1] = data[hi-1], data[c] - c++ - dups++ - } - if data[b-1].freq == data[pivot].freq && data[b-1].literal > data[pivot].literal || data[b-1].freq > data[pivot].freq { // data[b-1] = pivot - b-- - dups++ - } - // m-lo = (hi-lo)/2 > 6 - // b-lo > (hi-lo)*3/4-1 > 8 - // ==> m < b ==> data[m] <= pivot - if data[m].freq == data[pivot].freq && data[m].literal > data[pivot].literal || data[m].freq > data[pivot].freq { // data[m] = pivot - data[m], data[b-1] = data[b-1], data[m] - b-- - dups++ - } - // if at least 2 points are equal to pivot, assume skewed distribution - protect = dups > 1 - } - if protect { - // Protect against a lot of duplicates - // Add invariant: - // data[a <= i < b] unexamined - // data[b <= i < c] = pivot - for { - for ; a < b && (data[b-1].freq == data[pivot].freq && data[b-1].literal > data[pivot].literal || data[b-1].freq > data[pivot].freq); b-- { // data[b] == pivot - } - for ; a < b && (data[a].freq == data[pivot].freq && data[a].literal < data[pivot].literal || data[a].freq < data[pivot].freq); a++ { // data[a] < pivot - } - if a >= b { - break - } - // data[a] == pivot; data[b-1] < pivot - data[a], data[b-1] = data[b-1], data[a] - a++ - b-- - } - } - // Swap pivot into middle - data[pivot], data[b-1] = data[b-1], data[pivot] - return b - 1, c -} - -// Insertion sort -func insertionSortByFreq(data []literalNode, a, b int) { - for i := a + 1; i < b; i++ { - for j := i; j > a && (data[j].freq == data[j-1].freq && data[j].literal < data[j-1].literal || data[j].freq < data[j-1].freq); j-- { - data[j], data[j-1] = data[j-1], data[j] - } - } -} - -// quickSortByFreq, loosely following Bentley and McIlroy, -// ``Engineering a Sort Function,'' SP&E November 1993. - -// medianOfThreeSortByFreq moves the median of the three values data[m0], data[m1], data[m2] into data[m1]. -func medianOfThreeSortByFreq(data []literalNode, m1, m0, m2 int) { - // sort 3 elements - if data[m1].freq == data[m0].freq && data[m1].literal < data[m0].literal || data[m1].freq < data[m0].freq { - data[m1], data[m0] = data[m0], data[m1] - } - // data[m0] <= data[m1] - if data[m2].freq == data[m1].freq && data[m2].literal < data[m1].literal || data[m2].freq < data[m1].freq { - data[m2], data[m1] = data[m1], data[m2] - // data[m0] <= data[m2] && data[m1] < data[m2] - if data[m1].freq == data[m0].freq && data[m1].literal < data[m0].literal || data[m1].freq < data[m0].freq { - data[m1], data[m0] = data[m0], data[m1] - } - } - // now data[m0] <= data[m1] <= data[m2] -} diff --git a/vendor/github.com/klauspost/compress/flate/huffman_sortByLiteral.go b/vendor/github.com/klauspost/compress/flate/huffman_sortByLiteral.go deleted file mode 100644 index 93f1aea10..000000000 --- a/vendor/github.com/klauspost/compress/flate/huffman_sortByLiteral.go +++ /dev/null @@ -1,201 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flate - -// Sort sorts data. -// It makes one call to data.Len to determine n, and O(n*log(n)) calls to -// data.Less and data.Swap. The sort is not guaranteed to be stable. -func sortByLiteral(data []literalNode) { - n := len(data) - quickSort(data, 0, n, maxDepth(n)) -} - -func quickSort(data []literalNode, a, b, maxDepth int) { - for b-a > 12 { // Use ShellSort for slices <= 12 elements - if maxDepth == 0 { - heapSort(data, a, b) - return - } - maxDepth-- - mlo, mhi := doPivot(data, a, b) - // Avoiding recursion on the larger subproblem guarantees - // a stack depth of at most lg(b-a). - if mlo-a < b-mhi { - quickSort(data, a, mlo, maxDepth) - a = mhi // i.e., quickSort(data, mhi, b) - } else { - quickSort(data, mhi, b, maxDepth) - b = mlo // i.e., quickSort(data, a, mlo) - } - } - if b-a > 1 { - // Do ShellSort pass with gap 6 - // It could be written in this simplified form cause b-a <= 12 - for i := a + 6; i < b; i++ { - if data[i].literal < data[i-6].literal { - data[i], data[i-6] = data[i-6], data[i] - } - } - insertionSort(data, a, b) - } -} -func heapSort(data []literalNode, a, b int) { - first := a - lo := 0 - hi := b - a - - // Build heap with greatest element at top. - for i := (hi - 1) / 2; i >= 0; i-- { - siftDown(data, i, hi, first) - } - - // Pop elements, largest first, into end of data. - for i := hi - 1; i >= 0; i-- { - data[first], data[first+i] = data[first+i], data[first] - siftDown(data, lo, i, first) - } -} - -// siftDown implements the heap property on data[lo, hi). -// first is an offset into the array where the root of the heap lies. -func siftDown(data []literalNode, lo, hi, first int) { - root := lo - for { - child := 2*root + 1 - if child >= hi { - break - } - if child+1 < hi && data[first+child].literal < data[first+child+1].literal { - child++ - } - if data[first+root].literal > data[first+child].literal { - return - } - data[first+root], data[first+child] = data[first+child], data[first+root] - root = child - } -} -func doPivot(data []literalNode, lo, hi int) (midlo, midhi int) { - m := int(uint(lo+hi) >> 1) // Written like this to avoid integer overflow. - if hi-lo > 40 { - // Tukey's ``Ninther,'' median of three medians of three. - s := (hi - lo) / 8 - medianOfThree(data, lo, lo+s, lo+2*s) - medianOfThree(data, m, m-s, m+s) - medianOfThree(data, hi-1, hi-1-s, hi-1-2*s) - } - medianOfThree(data, lo, m, hi-1) - - // Invariants are: - // data[lo] = pivot (set up by ChoosePivot) - // data[lo < i < a] < pivot - // data[a <= i < b] <= pivot - // data[b <= i < c] unexamined - // data[c <= i < hi-1] > pivot - // data[hi-1] >= pivot - pivot := lo - a, c := lo+1, hi-1 - - for ; a < c && data[a].literal < data[pivot].literal; a++ { - } - b := a - for { - for ; b < c && data[pivot].literal > data[b].literal; b++ { // data[b] <= pivot - } - for ; b < c && data[pivot].literal < data[c-1].literal; c-- { // data[c-1] > pivot - } - if b >= c { - break - } - // data[b] > pivot; data[c-1] <= pivot - data[b], data[c-1] = data[c-1], data[b] - b++ - c-- - } - // If hi-c<3 then there are duplicates (by property of median of nine). - // Let's be a bit more conservative, and set border to 5. - protect := hi-c < 5 - if !protect && hi-c < (hi-lo)/4 { - // Lets test some points for equality to pivot - dups := 0 - if data[pivot].literal > data[hi-1].literal { // data[hi-1] = pivot - data[c], data[hi-1] = data[hi-1], data[c] - c++ - dups++ - } - if data[b-1].literal > data[pivot].literal { // data[b-1] = pivot - b-- - dups++ - } - // m-lo = (hi-lo)/2 > 6 - // b-lo > (hi-lo)*3/4-1 > 8 - // ==> m < b ==> data[m] <= pivot - if data[m].literal > data[pivot].literal { // data[m] = pivot - data[m], data[b-1] = data[b-1], data[m] - b-- - dups++ - } - // if at least 2 points are equal to pivot, assume skewed distribution - protect = dups > 1 - } - if protect { - // Protect against a lot of duplicates - // Add invariant: - // data[a <= i < b] unexamined - // data[b <= i < c] = pivot - for { - for ; a < b && data[b-1].literal > data[pivot].literal; b-- { // data[b] == pivot - } - for ; a < b && data[a].literal < data[pivot].literal; a++ { // data[a] < pivot - } - if a >= b { - break - } - // data[a] == pivot; data[b-1] < pivot - data[a], data[b-1] = data[b-1], data[a] - a++ - b-- - } - } - // Swap pivot into middle - data[pivot], data[b-1] = data[b-1], data[pivot] - return b - 1, c -} - -// Insertion sort -func insertionSort(data []literalNode, a, b int) { - for i := a + 1; i < b; i++ { - for j := i; j > a && data[j].literal < data[j-1].literal; j-- { - data[j], data[j-1] = data[j-1], data[j] - } - } -} - -// maxDepth returns a threshold at which quicksort should switch -// to heapsort. It returns 2*ceil(lg(n+1)). -func maxDepth(n int) int { - var depth int - for i := n; i > 0; i >>= 1 { - depth++ - } - return depth * 2 -} - -// medianOfThree moves the median of the three values data[m0], data[m1], data[m2] into data[m1]. -func medianOfThree(data []literalNode, m1, m0, m2 int) { - // sort 3 elements - if data[m1].literal < data[m0].literal { - data[m1], data[m0] = data[m0], data[m1] - } - // data[m0] <= data[m1] - if data[m2].literal < data[m1].literal { - data[m2], data[m1] = data[m1], data[m2] - // data[m0] <= data[m2] && data[m1] < data[m2] - if data[m1].literal < data[m0].literal { - data[m1], data[m0] = data[m0], data[m1] - } - } - // now data[m0] <= data[m1] <= data[m2] -} diff --git a/vendor/github.com/klauspost/compress/flate/inflate.go b/vendor/github.com/klauspost/compress/flate/inflate.go deleted file mode 100644 index 2f410d64f..000000000 --- a/vendor/github.com/klauspost/compress/flate/inflate.go +++ /dev/null @@ -1,829 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package flate implements the DEFLATE compressed data format, described in -// RFC 1951. The gzip and zlib packages implement access to DEFLATE-based file -// formats. -package flate - -import ( - "bufio" - "compress/flate" - "fmt" - "io" - "math/bits" - "sync" -) - -const ( - maxCodeLen = 16 // max length of Huffman code - maxCodeLenMask = 15 // mask for max length of Huffman code - // The next three numbers come from the RFC section 3.2.7, with the - // additional proviso in section 3.2.5 which implies that distance codes - // 30 and 31 should never occur in compressed data. - maxNumLit = 286 - maxNumDist = 30 - numCodes = 19 // number of codes in Huffman meta-code - - debugDecode = false -) - -// Value of length - 3 and extra bits. -type lengthExtra struct { - length, extra uint8 -} - -var decCodeToLen = [32]lengthExtra{{length: 0x0, extra: 0x0}, {length: 0x1, extra: 0x0}, {length: 0x2, extra: 0x0}, {length: 0x3, extra: 0x0}, {length: 0x4, extra: 0x0}, {length: 0x5, extra: 0x0}, {length: 0x6, extra: 0x0}, {length: 0x7, extra: 0x0}, {length: 0x8, extra: 0x1}, {length: 0xa, extra: 0x1}, {length: 0xc, extra: 0x1}, {length: 0xe, extra: 0x1}, {length: 0x10, extra: 0x2}, {length: 0x14, extra: 0x2}, {length: 0x18, extra: 0x2}, {length: 0x1c, extra: 0x2}, {length: 0x20, extra: 0x3}, {length: 0x28, extra: 0x3}, {length: 0x30, extra: 0x3}, {length: 0x38, extra: 0x3}, {length: 0x40, extra: 0x4}, {length: 0x50, extra: 0x4}, {length: 0x60, extra: 0x4}, {length: 0x70, extra: 0x4}, {length: 0x80, extra: 0x5}, {length: 0xa0, extra: 0x5}, {length: 0xc0, extra: 0x5}, {length: 0xe0, extra: 0x5}, {length: 0xff, extra: 0x0}, {length: 0x0, extra: 0x0}, {length: 0x0, extra: 0x0}, {length: 0x0, extra: 0x0}} - -var bitMask32 = [32]uint32{ - 0, 1, 3, 7, 0xF, 0x1F, 0x3F, 0x7F, 0xFF, - 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, - 0x1ffff, 0x3ffff, 0x7FFFF, 0xfFFFF, 0x1fFFFF, 0x3fFFFF, 0x7fFFFF, 0xffFFFF, - 0x1ffFFFF, 0x3ffFFFF, 0x7ffFFFF, 0xfffFFFF, 0x1fffFFFF, 0x3fffFFFF, 0x7fffFFFF, -} // up to 32 bits - -// Initialize the fixedHuffmanDecoder only once upon first use. -var fixedOnce sync.Once -var fixedHuffmanDecoder huffmanDecoder - -// A CorruptInputError reports the presence of corrupt input at a given offset. -type CorruptInputError = flate.CorruptInputError - -// An InternalError reports an error in the flate code itself. -type InternalError string - -func (e InternalError) Error() string { return "flate: internal error: " + string(e) } - -// A ReadError reports an error encountered while reading input. -// -// Deprecated: No longer returned. -type ReadError = flate.ReadError - -// A WriteError reports an error encountered while writing output. -// -// Deprecated: No longer returned. -type WriteError = flate.WriteError - -// Resetter resets a ReadCloser returned by NewReader or NewReaderDict to -// to switch to a new underlying Reader. This permits reusing a ReadCloser -// instead of allocating a new one. -type Resetter interface { - // Reset discards any buffered data and resets the Resetter as if it was - // newly initialized with the given reader. - Reset(r io.Reader, dict []byte) error -} - -// The data structure for decoding Huffman tables is based on that of -// zlib. There is a lookup table of a fixed bit width (huffmanChunkBits), -// For codes smaller than the table width, there are multiple entries -// (each combination of trailing bits has the same value). For codes -// larger than the table width, the table contains a link to an overflow -// table. The width of each entry in the link table is the maximum code -// size minus the chunk width. -// -// Note that you can do a lookup in the table even without all bits -// filled. Since the extra bits are zero, and the DEFLATE Huffman codes -// have the property that shorter codes come before longer ones, the -// bit length estimate in the result is a lower bound on the actual -// number of bits. -// -// See the following: -// http://www.gzip.org/algorithm.txt - -// chunk & 15 is number of bits -// chunk >> 4 is value, including table link - -const ( - huffmanChunkBits = 9 - huffmanNumChunks = 1 << huffmanChunkBits - huffmanCountMask = 15 - huffmanValueShift = 4 -) - -type huffmanDecoder struct { - maxRead int // the maximum number of bits we can read and not overread - chunks *[huffmanNumChunks]uint16 // chunks as described above - links [][]uint16 // overflow links - linkMask uint32 // mask the width of the link table -} - -// Initialize Huffman decoding tables from array of code lengths. -// Following this function, h is guaranteed to be initialized into a complete -// tree (i.e., neither over-subscribed nor under-subscribed). The exception is a -// degenerate case where the tree has only a single symbol with length 1. Empty -// trees are permitted. -func (h *huffmanDecoder) init(lengths []int) bool { - // Sanity enables additional runtime tests during Huffman - // table construction. It's intended to be used during - // development to supplement the currently ad-hoc unit tests. - const sanity = false - - if h.chunks == nil { - h.chunks = new([huffmanNumChunks]uint16) - } - - if h.maxRead != 0 { - *h = huffmanDecoder{chunks: h.chunks, links: h.links} - } - - // Count number of codes of each length, - // compute maxRead and max length. - var count [maxCodeLen]int - var min, max int - for _, n := range lengths { - if n == 0 { - continue - } - if min == 0 || n < min { - min = n - } - if n > max { - max = n - } - count[n&maxCodeLenMask]++ - } - - // Empty tree. The decompressor.huffSym function will fail later if the tree - // is used. Technically, an empty tree is only valid for the HDIST tree and - // not the HCLEN and HLIT tree. However, a stream with an empty HCLEN tree - // is guaranteed to fail since it will attempt to use the tree to decode the - // codes for the HLIT and HDIST trees. Similarly, an empty HLIT tree is - // guaranteed to fail later since the compressed data section must be - // composed of at least one symbol (the end-of-block marker). - if max == 0 { - return true - } - - code := 0 - var nextcode [maxCodeLen]int - for i := min; i <= max; i++ { - code <<= 1 - nextcode[i&maxCodeLenMask] = code - code += count[i&maxCodeLenMask] - } - - // Check that the coding is complete (i.e., that we've - // assigned all 2-to-the-max possible bit sequences). - // Exception: To be compatible with zlib, we also need to - // accept degenerate single-code codings. See also - // TestDegenerateHuffmanCoding. - if code != 1< huffmanChunkBits { - numLinks := 1 << (uint(max) - huffmanChunkBits) - h.linkMask = uint32(numLinks - 1) - - // create link tables - link := nextcode[huffmanChunkBits+1] >> 1 - if cap(h.links) < huffmanNumChunks-link { - h.links = make([][]uint16, huffmanNumChunks-link) - } else { - h.links = h.links[:huffmanNumChunks-link] - } - for j := uint(link); j < huffmanNumChunks; j++ { - reverse := int(bits.Reverse16(uint16(j))) - reverse >>= uint(16 - huffmanChunkBits) - off := j - uint(link) - if sanity && h.chunks[reverse] != 0 { - panic("impossible: overwriting existing chunk") - } - h.chunks[reverse] = uint16(off<>= uint(16 - n) - if n <= huffmanChunkBits { - for off := reverse; off < len(h.chunks); off += 1 << uint(n) { - // We should never need to overwrite - // an existing chunk. Also, 0 is - // never a valid chunk, because the - // lower 4 "count" bits should be - // between 1 and 15. - if sanity && h.chunks[off] != 0 { - panic("impossible: overwriting existing chunk") - } - h.chunks[off] = chunk - } - } else { - j := reverse & (huffmanNumChunks - 1) - if sanity && h.chunks[j]&huffmanCountMask != huffmanChunkBits+1 { - // Longer codes should have been - // associated with a link table above. - panic("impossible: not an indirect chunk") - } - value := h.chunks[j] >> huffmanValueShift - linktab := h.links[value] - reverse >>= huffmanChunkBits - for off := reverse; off < len(linktab); off += 1 << uint(n-huffmanChunkBits) { - if sanity && linktab[off] != 0 { - panic("impossible: overwriting existing chunk") - } - linktab[off] = chunk - } - } - } - - if sanity { - // Above we've sanity checked that we never overwrote - // an existing entry. Here we additionally check that - // we filled the tables completely. - for i, chunk := range h.chunks { - if chunk == 0 { - // As an exception, in the degenerate - // single-code case, we allow odd - // chunks to be missing. - if code == 1 && i%2 == 1 { - continue - } - panic("impossible: missing chunk") - } - } - for _, linktab := range h.links { - for _, chunk := range linktab { - if chunk == 0 { - panic("impossible: missing chunk") - } - } - } - } - - return true -} - -// Reader is the actual read interface needed by NewReader. -// If the passed in io.Reader does not also have ReadByte, -// the NewReader will introduce its own buffering. -type Reader interface { - io.Reader - io.ByteReader -} - -type step uint8 - -const ( - copyData step = iota + 1 - nextBlock - huffmanBytesBuffer - huffmanBytesReader - huffmanBufioReader - huffmanStringsReader - huffmanGenericReader -) - -// Decompress state. -type decompressor struct { - // Input source. - r Reader - roffset int64 - - // Huffman decoders for literal/length, distance. - h1, h2 huffmanDecoder - - // Length arrays used to define Huffman codes. - bits *[maxNumLit + maxNumDist]int - codebits *[numCodes]int - - // Output history, buffer. - dict dictDecoder - - // Next step in the decompression, - // and decompression state. - step step - stepState int - err error - toRead []byte - hl, hd *huffmanDecoder - copyLen int - copyDist int - - // Temporary buffer (avoids repeated allocation). - buf [4]byte - - // Input bits, in top of b. - b uint32 - - nb uint - final bool -} - -func (f *decompressor) nextBlock() { - for f.nb < 1+2 { - if f.err = f.moreBits(); f.err != nil { - return - } - } - f.final = f.b&1 == 1 - f.b >>= 1 - typ := f.b & 3 - f.b >>= 2 - f.nb -= 1 + 2 - switch typ { - case 0: - f.dataBlock() - if debugDecode { - fmt.Println("stored block") - } - case 1: - // compressed, fixed Huffman tables - f.hl = &fixedHuffmanDecoder - f.hd = nil - f.huffmanBlockDecoder() - if debugDecode { - fmt.Println("predefinied huffman block") - } - case 2: - // compressed, dynamic Huffman tables - if f.err = f.readHuffman(); f.err != nil { - break - } - f.hl = &f.h1 - f.hd = &f.h2 - f.huffmanBlockDecoder() - if debugDecode { - fmt.Println("dynamic huffman block") - } - default: - // 3 is reserved. - if debugDecode { - fmt.Println("reserved data block encountered") - } - f.err = CorruptInputError(f.roffset) - } -} - -func (f *decompressor) Read(b []byte) (int, error) { - for { - if len(f.toRead) > 0 { - n := copy(b, f.toRead) - f.toRead = f.toRead[n:] - if len(f.toRead) == 0 { - return n, f.err - } - return n, nil - } - if f.err != nil { - return 0, f.err - } - - f.doStep() - - if f.err != nil && len(f.toRead) == 0 { - f.toRead = f.dict.readFlush() // Flush what's left in case of error - } - } -} - -// WriteTo implements the io.WriteTo interface for io.Copy and friends. -func (f *decompressor) WriteTo(w io.Writer) (int64, error) { - total := int64(0) - flushed := false - for { - if len(f.toRead) > 0 { - n, err := w.Write(f.toRead) - total += int64(n) - if err != nil { - f.err = err - return total, err - } - if n != len(f.toRead) { - return total, io.ErrShortWrite - } - f.toRead = f.toRead[:0] - } - if f.err != nil && flushed { - if f.err == io.EOF { - return total, nil - } - return total, f.err - } - if f.err == nil { - f.doStep() - } - if len(f.toRead) == 0 && f.err != nil && !flushed { - f.toRead = f.dict.readFlush() // Flush what's left in case of error - flushed = true - } - } -} - -func (f *decompressor) Close() error { - if f.err == io.EOF { - return nil - } - return f.err -} - -// RFC 1951 section 3.2.7. -// Compression with dynamic Huffman codes - -var codeOrder = [...]int{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15} - -func (f *decompressor) readHuffman() error { - // HLIT[5], HDIST[5], HCLEN[4]. - for f.nb < 5+5+4 { - if err := f.moreBits(); err != nil { - return err - } - } - nlit := int(f.b&0x1F) + 257 - if nlit > maxNumLit { - if debugDecode { - fmt.Println("nlit > maxNumLit", nlit) - } - return CorruptInputError(f.roffset) - } - f.b >>= 5 - ndist := int(f.b&0x1F) + 1 - if ndist > maxNumDist { - if debugDecode { - fmt.Println("ndist > maxNumDist", ndist) - } - return CorruptInputError(f.roffset) - } - f.b >>= 5 - nclen := int(f.b&0xF) + 4 - // numCodes is 19, so nclen is always valid. - f.b >>= 4 - f.nb -= 5 + 5 + 4 - - // (HCLEN+4)*3 bits: code lengths in the magic codeOrder order. - for i := 0; i < nclen; i++ { - for f.nb < 3 { - if err := f.moreBits(); err != nil { - return err - } - } - f.codebits[codeOrder[i]] = int(f.b & 0x7) - f.b >>= 3 - f.nb -= 3 - } - for i := nclen; i < len(codeOrder); i++ { - f.codebits[codeOrder[i]] = 0 - } - if !f.h1.init(f.codebits[0:]) { - if debugDecode { - fmt.Println("init codebits failed") - } - return CorruptInputError(f.roffset) - } - - // HLIT + 257 code lengths, HDIST + 1 code lengths, - // using the code length Huffman code. - for i, n := 0, nlit+ndist; i < n; { - x, err := f.huffSym(&f.h1) - if err != nil { - return err - } - if x < 16 { - // Actual length. - f.bits[i] = x - i++ - continue - } - // Repeat previous length or zero. - var rep int - var nb uint - var b int - switch x { - default: - return InternalError("unexpected length code") - case 16: - rep = 3 - nb = 2 - if i == 0 { - if debugDecode { - fmt.Println("i==0") - } - return CorruptInputError(f.roffset) - } - b = f.bits[i-1] - case 17: - rep = 3 - nb = 3 - b = 0 - case 18: - rep = 11 - nb = 7 - b = 0 - } - for f.nb < nb { - if err := f.moreBits(); err != nil { - if debugDecode { - fmt.Println("morebits:", err) - } - return err - } - } - rep += int(f.b & uint32(1<<(nb®SizeMaskUint32)-1)) - f.b >>= nb & regSizeMaskUint32 - f.nb -= nb - if i+rep > n { - if debugDecode { - fmt.Println("i+rep > n", i, rep, n) - } - return CorruptInputError(f.roffset) - } - for j := 0; j < rep; j++ { - f.bits[i] = b - i++ - } - } - - if !f.h1.init(f.bits[0:nlit]) || !f.h2.init(f.bits[nlit:nlit+ndist]) { - if debugDecode { - fmt.Println("init2 failed") - } - return CorruptInputError(f.roffset) - } - - // As an optimization, we can initialize the maxRead bits to read at a time - // for the HLIT tree to the length of the EOB marker since we know that - // every block must terminate with one. This preserves the property that - // we never read any extra bytes after the end of the DEFLATE stream. - if f.h1.maxRead < f.bits[endBlockMarker] { - f.h1.maxRead = f.bits[endBlockMarker] - } - if !f.final { - // If not the final block, the smallest block possible is - // a predefined table, BTYPE=01, with a single EOB marker. - // This will take up 3 + 7 bits. - f.h1.maxRead += 10 - } - - return nil -} - -// Copy a single uncompressed data block from input to output. -func (f *decompressor) dataBlock() { - // Uncompressed. - // Discard current half-byte. - left := (f.nb) & 7 - f.nb -= left - f.b >>= left - - offBytes := f.nb >> 3 - // Unfilled values will be overwritten. - f.buf[0] = uint8(f.b) - f.buf[1] = uint8(f.b >> 8) - f.buf[2] = uint8(f.b >> 16) - f.buf[3] = uint8(f.b >> 24) - - f.roffset += int64(offBytes) - f.nb, f.b = 0, 0 - - // Length then ones-complement of length. - nr, err := io.ReadFull(f.r, f.buf[offBytes:4]) - f.roffset += int64(nr) - if err != nil { - f.err = noEOF(err) - return - } - n := uint16(f.buf[0]) | uint16(f.buf[1])<<8 - nn := uint16(f.buf[2]) | uint16(f.buf[3])<<8 - if nn != ^n { - if debugDecode { - ncomp := ^n - fmt.Println("uint16(nn) != uint16(^n)", nn, ncomp) - } - f.err = CorruptInputError(f.roffset) - return - } - - if n == 0 { - f.toRead = f.dict.readFlush() - f.finishBlock() - return - } - - f.copyLen = int(n) - f.copyData() -} - -// copyData copies f.copyLen bytes from the underlying reader into f.hist. -// It pauses for reads when f.hist is full. -func (f *decompressor) copyData() { - buf := f.dict.writeSlice() - if len(buf) > f.copyLen { - buf = buf[:f.copyLen] - } - - cnt, err := io.ReadFull(f.r, buf) - f.roffset += int64(cnt) - f.copyLen -= cnt - f.dict.writeMark(cnt) - if err != nil { - f.err = noEOF(err) - return - } - - if f.dict.availWrite() == 0 || f.copyLen > 0 { - f.toRead = f.dict.readFlush() - f.step = copyData - return - } - f.finishBlock() -} - -func (f *decompressor) finishBlock() { - if f.final { - if f.dict.availRead() > 0 { - f.toRead = f.dict.readFlush() - } - f.err = io.EOF - } - f.step = nextBlock -} - -func (f *decompressor) doStep() { - switch f.step { - case copyData: - f.copyData() - case nextBlock: - f.nextBlock() - case huffmanBytesBuffer: - f.huffmanBytesBuffer() - case huffmanBytesReader: - f.huffmanBytesReader() - case huffmanBufioReader: - f.huffmanBufioReader() - case huffmanStringsReader: - f.huffmanStringsReader() - case huffmanGenericReader: - f.huffmanGenericReader() - default: - panic("BUG: unexpected step state") - } -} - -// noEOF returns err, unless err == io.EOF, in which case it returns io.ErrUnexpectedEOF. -func noEOF(e error) error { - if e == io.EOF { - return io.ErrUnexpectedEOF - } - return e -} - -func (f *decompressor) moreBits() error { - c, err := f.r.ReadByte() - if err != nil { - return noEOF(err) - } - f.roffset++ - f.b |= uint32(c) << (f.nb & regSizeMaskUint32) - f.nb += 8 - return nil -} - -// Read the next Huffman-encoded symbol from f according to h. -func (f *decompressor) huffSym(h *huffmanDecoder) (int, error) { - // Since a huffmanDecoder can be empty or be composed of a degenerate tree - // with single element, huffSym must error on these two edge cases. In both - // cases, the chunks slice will be 0 for the invalid sequence, leading it - // satisfy the n == 0 check below. - n := uint(h.maxRead) - // Optimization. Compiler isn't smart enough to keep f.b,f.nb in registers, - // but is smart enough to keep local variables in registers, so use nb and b, - // inline call to moreBits and reassign b,nb back to f on return. - nb, b := f.nb, f.b - for { - for nb < n { - c, err := f.r.ReadByte() - if err != nil { - f.b = b - f.nb = nb - return 0, noEOF(err) - } - f.roffset++ - b |= uint32(c) << (nb & regSizeMaskUint32) - nb += 8 - } - chunk := h.chunks[b&(huffmanNumChunks-1)] - n = uint(chunk & huffmanCountMask) - if n > huffmanChunkBits { - chunk = h.links[chunk>>huffmanValueShift][(b>>huffmanChunkBits)&h.linkMask] - n = uint(chunk & huffmanCountMask) - } - if n <= nb { - if n == 0 { - f.b = b - f.nb = nb - if debugDecode { - fmt.Println("huffsym: n==0") - } - f.err = CorruptInputError(f.roffset) - return 0, f.err - } - f.b = b >> (n & regSizeMaskUint32) - f.nb = nb - n - return int(chunk >> huffmanValueShift), nil - } - } -} - -func makeReader(r io.Reader) Reader { - if rr, ok := r.(Reader); ok { - return rr - } - return bufio.NewReader(r) -} - -func fixedHuffmanDecoderInit() { - fixedOnce.Do(func() { - // These come from the RFC section 3.2.6. - var bits [288]int - for i := 0; i < 144; i++ { - bits[i] = 8 - } - for i := 144; i < 256; i++ { - bits[i] = 9 - } - for i := 256; i < 280; i++ { - bits[i] = 7 - } - for i := 280; i < 288; i++ { - bits[i] = 8 - } - fixedHuffmanDecoder.init(bits[:]) - }) -} - -func (f *decompressor) Reset(r io.Reader, dict []byte) error { - *f = decompressor{ - r: makeReader(r), - bits: f.bits, - codebits: f.codebits, - h1: f.h1, - h2: f.h2, - dict: f.dict, - step: nextBlock, - } - f.dict.init(maxMatchOffset, dict) - return nil -} - -// NewReader returns a new ReadCloser that can be used -// to read the uncompressed version of r. -// If r does not also implement io.ByteReader, -// the decompressor may read more data than necessary from r. -// It is the caller's responsibility to call Close on the ReadCloser -// when finished reading. -// -// The ReadCloser returned by NewReader also implements Resetter. -func NewReader(r io.Reader) io.ReadCloser { - fixedHuffmanDecoderInit() - - var f decompressor - f.r = makeReader(r) - f.bits = new([maxNumLit + maxNumDist]int) - f.codebits = new([numCodes]int) - f.step = nextBlock - f.dict.init(maxMatchOffset, nil) - return &f -} - -// NewReaderDict is like NewReader but initializes the reader -// with a preset dictionary. The returned Reader behaves as if -// the uncompressed data stream started with the given dictionary, -// which has already been read. NewReaderDict is typically used -// to read data compressed by NewWriterDict. -// -// The ReadCloser returned by NewReader also implements Resetter. -func NewReaderDict(r io.Reader, dict []byte) io.ReadCloser { - fixedHuffmanDecoderInit() - - var f decompressor - f.r = makeReader(r) - f.bits = new([maxNumLit + maxNumDist]int) - f.codebits = new([numCodes]int) - f.step = nextBlock - f.dict.init(maxMatchOffset, dict) - return &f -} diff --git a/vendor/github.com/klauspost/compress/flate/inflate_gen.go b/vendor/github.com/klauspost/compress/flate/inflate_gen.go deleted file mode 100644 index 2b2f993f7..000000000 --- a/vendor/github.com/klauspost/compress/flate/inflate_gen.go +++ /dev/null @@ -1,1283 +0,0 @@ -// Code generated by go generate gen_inflate.go. DO NOT EDIT. - -package flate - -import ( - "bufio" - "bytes" - "fmt" - "math/bits" - "strings" -) - -// Decode a single Huffman block from f. -// hl and hd are the Huffman states for the lit/length values -// and the distance values, respectively. If hd == nil, using the -// fixed distance encoding associated with fixed Huffman blocks. -func (f *decompressor) huffmanBytesBuffer() { - const ( - stateInit = iota // Zero value must be stateInit - stateDict - ) - fr := f.r.(*bytes.Buffer) - - // Optimization. Compiler isn't smart enough to keep f.b,f.nb in registers, - // but is smart enough to keep local variables in registers, so use nb and b, - // inline call to moreBits and reassign b,nb back to f on return. - fnb, fb, dict := f.nb, f.b, &f.dict - - switch f.stepState { - case stateInit: - goto readLiteral - case stateDict: - goto copyHistory - } - -readLiteral: - // Read literal and/or (length, distance) according to RFC section 3.2.3. - { - var v int - { - // Inlined v, err := f.huffSym(f.hl) - // Since a huffmanDecoder can be empty or be composed of a degenerate tree - // with single element, huffSym must error on these two edge cases. In both - // cases, the chunks slice will be 0 for the invalid sequence, leading it - // satisfy the n == 0 check below. - n := uint(f.hl.maxRead) - for { - for fnb < n { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - f.err = noEOF(err) - return - } - f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) - fnb += 8 - } - chunk := f.hl.chunks[fb&(huffmanNumChunks-1)] - n = uint(chunk & huffmanCountMask) - if n > huffmanChunkBits { - chunk = f.hl.links[chunk>>huffmanValueShift][(fb>>huffmanChunkBits)&f.hl.linkMask] - n = uint(chunk & huffmanCountMask) - } - if n <= fnb { - if n == 0 { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("huffsym: n==0") - } - f.err = CorruptInputError(f.roffset) - return - } - fb = fb >> (n & regSizeMaskUint32) - fnb = fnb - n - v = int(chunk >> huffmanValueShift) - break - } - } - } - - var length int - switch { - case v < 256: - dict.writeByte(byte(v)) - if dict.availWrite() == 0 { - f.toRead = dict.readFlush() - f.step = huffmanBytesBuffer - f.stepState = stateInit - f.b, f.nb = fb, fnb - return - } - goto readLiteral - case v == 256: - f.b, f.nb = fb, fnb - f.finishBlock() - return - // otherwise, reference to older data - case v < 265: - length = v - (257 - 3) - case v < maxNumLit: - val := decCodeToLen[(v - 257)] - length = int(val.length) + 3 - n := uint(val.extra) - for fnb < n { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("morebits n>0:", err) - } - f.err = err - return - } - f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) - fnb += 8 - } - length += int(fb & bitMask32[n]) - fb >>= n & regSizeMaskUint32 - fnb -= n - default: - if debugDecode { - fmt.Println(v, ">= maxNumLit") - } - f.err = CorruptInputError(f.roffset) - f.b, f.nb = fb, fnb - return - } - - var dist uint32 - if f.hd == nil { - for fnb < 5 { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("morebits f.nb<5:", err) - } - f.err = err - return - } - f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) - fnb += 8 - } - dist = uint32(bits.Reverse8(uint8(fb & 0x1F << 3))) - fb >>= 5 - fnb -= 5 - } else { - // Since a huffmanDecoder can be empty or be composed of a degenerate tree - // with single element, huffSym must error on these two edge cases. In both - // cases, the chunks slice will be 0 for the invalid sequence, leading it - // satisfy the n == 0 check below. - n := uint(f.hd.maxRead) - // Optimization. Compiler isn't smart enough to keep f.b,f.nb in registers, - // but is smart enough to keep local variables in registers, so use nb and b, - // inline call to moreBits and reassign b,nb back to f on return. - for { - for fnb < n { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - f.err = noEOF(err) - return - } - f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) - fnb += 8 - } - chunk := f.hd.chunks[fb&(huffmanNumChunks-1)] - n = uint(chunk & huffmanCountMask) - if n > huffmanChunkBits { - chunk = f.hd.links[chunk>>huffmanValueShift][(fb>>huffmanChunkBits)&f.hd.linkMask] - n = uint(chunk & huffmanCountMask) - } - if n <= fnb { - if n == 0 { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("huffsym: n==0") - } - f.err = CorruptInputError(f.roffset) - return - } - fb = fb >> (n & regSizeMaskUint32) - fnb = fnb - n - dist = uint32(chunk >> huffmanValueShift) - break - } - } - } - - switch { - case dist < 4: - dist++ - case dist < maxNumDist: - nb := uint(dist-2) >> 1 - // have 1 bit in bottom of dist, need nb more. - extra := (dist & 1) << (nb & regSizeMaskUint32) - for fnb < nb { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("morebits f.nb>= nb & regSizeMaskUint32 - fnb -= nb - dist = 1<<((nb+1)®SizeMaskUint32) + 1 + extra - // slower: dist = bitMask32[nb+1] + 2 + extra - default: - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("dist too big:", dist, maxNumDist) - } - f.err = CorruptInputError(f.roffset) - return - } - - // No check on length; encoding can be prescient. - if dist > uint32(dict.histSize()) { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("dist > dict.histSize():", dist, dict.histSize()) - } - f.err = CorruptInputError(f.roffset) - return - } - - f.copyLen, f.copyDist = length, int(dist) - goto copyHistory - } - -copyHistory: - // Perform a backwards copy according to RFC section 3.2.3. - { - cnt := dict.tryWriteCopy(f.copyDist, f.copyLen) - if cnt == 0 { - cnt = dict.writeCopy(f.copyDist, f.copyLen) - } - f.copyLen -= cnt - - if dict.availWrite() == 0 || f.copyLen > 0 { - f.toRead = dict.readFlush() - f.step = huffmanBytesBuffer // We need to continue this work - f.stepState = stateDict - f.b, f.nb = fb, fnb - return - } - goto readLiteral - } - // Not reached -} - -// Decode a single Huffman block from f. -// hl and hd are the Huffman states for the lit/length values -// and the distance values, respectively. If hd == nil, using the -// fixed distance encoding associated with fixed Huffman blocks. -func (f *decompressor) huffmanBytesReader() { - const ( - stateInit = iota // Zero value must be stateInit - stateDict - ) - fr := f.r.(*bytes.Reader) - - // Optimization. Compiler isn't smart enough to keep f.b,f.nb in registers, - // but is smart enough to keep local variables in registers, so use nb and b, - // inline call to moreBits and reassign b,nb back to f on return. - fnb, fb, dict := f.nb, f.b, &f.dict - - switch f.stepState { - case stateInit: - goto readLiteral - case stateDict: - goto copyHistory - } - -readLiteral: - // Read literal and/or (length, distance) according to RFC section 3.2.3. - { - var v int - { - // Inlined v, err := f.huffSym(f.hl) - // Since a huffmanDecoder can be empty or be composed of a degenerate tree - // with single element, huffSym must error on these two edge cases. In both - // cases, the chunks slice will be 0 for the invalid sequence, leading it - // satisfy the n == 0 check below. - n := uint(f.hl.maxRead) - for { - for fnb < n { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - f.err = noEOF(err) - return - } - f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) - fnb += 8 - } - chunk := f.hl.chunks[fb&(huffmanNumChunks-1)] - n = uint(chunk & huffmanCountMask) - if n > huffmanChunkBits { - chunk = f.hl.links[chunk>>huffmanValueShift][(fb>>huffmanChunkBits)&f.hl.linkMask] - n = uint(chunk & huffmanCountMask) - } - if n <= fnb { - if n == 0 { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("huffsym: n==0") - } - f.err = CorruptInputError(f.roffset) - return - } - fb = fb >> (n & regSizeMaskUint32) - fnb = fnb - n - v = int(chunk >> huffmanValueShift) - break - } - } - } - - var length int - switch { - case v < 256: - dict.writeByte(byte(v)) - if dict.availWrite() == 0 { - f.toRead = dict.readFlush() - f.step = huffmanBytesReader - f.stepState = stateInit - f.b, f.nb = fb, fnb - return - } - goto readLiteral - case v == 256: - f.b, f.nb = fb, fnb - f.finishBlock() - return - // otherwise, reference to older data - case v < 265: - length = v - (257 - 3) - case v < maxNumLit: - val := decCodeToLen[(v - 257)] - length = int(val.length) + 3 - n := uint(val.extra) - for fnb < n { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("morebits n>0:", err) - } - f.err = err - return - } - f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) - fnb += 8 - } - length += int(fb & bitMask32[n]) - fb >>= n & regSizeMaskUint32 - fnb -= n - default: - if debugDecode { - fmt.Println(v, ">= maxNumLit") - } - f.err = CorruptInputError(f.roffset) - f.b, f.nb = fb, fnb - return - } - - var dist uint32 - if f.hd == nil { - for fnb < 5 { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("morebits f.nb<5:", err) - } - f.err = err - return - } - f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) - fnb += 8 - } - dist = uint32(bits.Reverse8(uint8(fb & 0x1F << 3))) - fb >>= 5 - fnb -= 5 - } else { - // Since a huffmanDecoder can be empty or be composed of a degenerate tree - // with single element, huffSym must error on these two edge cases. In both - // cases, the chunks slice will be 0 for the invalid sequence, leading it - // satisfy the n == 0 check below. - n := uint(f.hd.maxRead) - // Optimization. Compiler isn't smart enough to keep f.b,f.nb in registers, - // but is smart enough to keep local variables in registers, so use nb and b, - // inline call to moreBits and reassign b,nb back to f on return. - for { - for fnb < n { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - f.err = noEOF(err) - return - } - f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) - fnb += 8 - } - chunk := f.hd.chunks[fb&(huffmanNumChunks-1)] - n = uint(chunk & huffmanCountMask) - if n > huffmanChunkBits { - chunk = f.hd.links[chunk>>huffmanValueShift][(fb>>huffmanChunkBits)&f.hd.linkMask] - n = uint(chunk & huffmanCountMask) - } - if n <= fnb { - if n == 0 { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("huffsym: n==0") - } - f.err = CorruptInputError(f.roffset) - return - } - fb = fb >> (n & regSizeMaskUint32) - fnb = fnb - n - dist = uint32(chunk >> huffmanValueShift) - break - } - } - } - - switch { - case dist < 4: - dist++ - case dist < maxNumDist: - nb := uint(dist-2) >> 1 - // have 1 bit in bottom of dist, need nb more. - extra := (dist & 1) << (nb & regSizeMaskUint32) - for fnb < nb { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("morebits f.nb>= nb & regSizeMaskUint32 - fnb -= nb - dist = 1<<((nb+1)®SizeMaskUint32) + 1 + extra - // slower: dist = bitMask32[nb+1] + 2 + extra - default: - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("dist too big:", dist, maxNumDist) - } - f.err = CorruptInputError(f.roffset) - return - } - - // No check on length; encoding can be prescient. - if dist > uint32(dict.histSize()) { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("dist > dict.histSize():", dist, dict.histSize()) - } - f.err = CorruptInputError(f.roffset) - return - } - - f.copyLen, f.copyDist = length, int(dist) - goto copyHistory - } - -copyHistory: - // Perform a backwards copy according to RFC section 3.2.3. - { - cnt := dict.tryWriteCopy(f.copyDist, f.copyLen) - if cnt == 0 { - cnt = dict.writeCopy(f.copyDist, f.copyLen) - } - f.copyLen -= cnt - - if dict.availWrite() == 0 || f.copyLen > 0 { - f.toRead = dict.readFlush() - f.step = huffmanBytesReader // We need to continue this work - f.stepState = stateDict - f.b, f.nb = fb, fnb - return - } - goto readLiteral - } - // Not reached -} - -// Decode a single Huffman block from f. -// hl and hd are the Huffman states for the lit/length values -// and the distance values, respectively. If hd == nil, using the -// fixed distance encoding associated with fixed Huffman blocks. -func (f *decompressor) huffmanBufioReader() { - const ( - stateInit = iota // Zero value must be stateInit - stateDict - ) - fr := f.r.(*bufio.Reader) - - // Optimization. Compiler isn't smart enough to keep f.b,f.nb in registers, - // but is smart enough to keep local variables in registers, so use nb and b, - // inline call to moreBits and reassign b,nb back to f on return. - fnb, fb, dict := f.nb, f.b, &f.dict - - switch f.stepState { - case stateInit: - goto readLiteral - case stateDict: - goto copyHistory - } - -readLiteral: - // Read literal and/or (length, distance) according to RFC section 3.2.3. - { - var v int - { - // Inlined v, err := f.huffSym(f.hl) - // Since a huffmanDecoder can be empty or be composed of a degenerate tree - // with single element, huffSym must error on these two edge cases. In both - // cases, the chunks slice will be 0 for the invalid sequence, leading it - // satisfy the n == 0 check below. - n := uint(f.hl.maxRead) - for { - for fnb < n { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - f.err = noEOF(err) - return - } - f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) - fnb += 8 - } - chunk := f.hl.chunks[fb&(huffmanNumChunks-1)] - n = uint(chunk & huffmanCountMask) - if n > huffmanChunkBits { - chunk = f.hl.links[chunk>>huffmanValueShift][(fb>>huffmanChunkBits)&f.hl.linkMask] - n = uint(chunk & huffmanCountMask) - } - if n <= fnb { - if n == 0 { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("huffsym: n==0") - } - f.err = CorruptInputError(f.roffset) - return - } - fb = fb >> (n & regSizeMaskUint32) - fnb = fnb - n - v = int(chunk >> huffmanValueShift) - break - } - } - } - - var length int - switch { - case v < 256: - dict.writeByte(byte(v)) - if dict.availWrite() == 0 { - f.toRead = dict.readFlush() - f.step = huffmanBufioReader - f.stepState = stateInit - f.b, f.nb = fb, fnb - return - } - goto readLiteral - case v == 256: - f.b, f.nb = fb, fnb - f.finishBlock() - return - // otherwise, reference to older data - case v < 265: - length = v - (257 - 3) - case v < maxNumLit: - val := decCodeToLen[(v - 257)] - length = int(val.length) + 3 - n := uint(val.extra) - for fnb < n { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("morebits n>0:", err) - } - f.err = err - return - } - f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) - fnb += 8 - } - length += int(fb & bitMask32[n]) - fb >>= n & regSizeMaskUint32 - fnb -= n - default: - if debugDecode { - fmt.Println(v, ">= maxNumLit") - } - f.err = CorruptInputError(f.roffset) - f.b, f.nb = fb, fnb - return - } - - var dist uint32 - if f.hd == nil { - for fnb < 5 { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("morebits f.nb<5:", err) - } - f.err = err - return - } - f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) - fnb += 8 - } - dist = uint32(bits.Reverse8(uint8(fb & 0x1F << 3))) - fb >>= 5 - fnb -= 5 - } else { - // Since a huffmanDecoder can be empty or be composed of a degenerate tree - // with single element, huffSym must error on these two edge cases. In both - // cases, the chunks slice will be 0 for the invalid sequence, leading it - // satisfy the n == 0 check below. - n := uint(f.hd.maxRead) - // Optimization. Compiler isn't smart enough to keep f.b,f.nb in registers, - // but is smart enough to keep local variables in registers, so use nb and b, - // inline call to moreBits and reassign b,nb back to f on return. - for { - for fnb < n { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - f.err = noEOF(err) - return - } - f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) - fnb += 8 - } - chunk := f.hd.chunks[fb&(huffmanNumChunks-1)] - n = uint(chunk & huffmanCountMask) - if n > huffmanChunkBits { - chunk = f.hd.links[chunk>>huffmanValueShift][(fb>>huffmanChunkBits)&f.hd.linkMask] - n = uint(chunk & huffmanCountMask) - } - if n <= fnb { - if n == 0 { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("huffsym: n==0") - } - f.err = CorruptInputError(f.roffset) - return - } - fb = fb >> (n & regSizeMaskUint32) - fnb = fnb - n - dist = uint32(chunk >> huffmanValueShift) - break - } - } - } - - switch { - case dist < 4: - dist++ - case dist < maxNumDist: - nb := uint(dist-2) >> 1 - // have 1 bit in bottom of dist, need nb more. - extra := (dist & 1) << (nb & regSizeMaskUint32) - for fnb < nb { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("morebits f.nb>= nb & regSizeMaskUint32 - fnb -= nb - dist = 1<<((nb+1)®SizeMaskUint32) + 1 + extra - // slower: dist = bitMask32[nb+1] + 2 + extra - default: - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("dist too big:", dist, maxNumDist) - } - f.err = CorruptInputError(f.roffset) - return - } - - // No check on length; encoding can be prescient. - if dist > uint32(dict.histSize()) { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("dist > dict.histSize():", dist, dict.histSize()) - } - f.err = CorruptInputError(f.roffset) - return - } - - f.copyLen, f.copyDist = length, int(dist) - goto copyHistory - } - -copyHistory: - // Perform a backwards copy according to RFC section 3.2.3. - { - cnt := dict.tryWriteCopy(f.copyDist, f.copyLen) - if cnt == 0 { - cnt = dict.writeCopy(f.copyDist, f.copyLen) - } - f.copyLen -= cnt - - if dict.availWrite() == 0 || f.copyLen > 0 { - f.toRead = dict.readFlush() - f.step = huffmanBufioReader // We need to continue this work - f.stepState = stateDict - f.b, f.nb = fb, fnb - return - } - goto readLiteral - } - // Not reached -} - -// Decode a single Huffman block from f. -// hl and hd are the Huffman states for the lit/length values -// and the distance values, respectively. If hd == nil, using the -// fixed distance encoding associated with fixed Huffman blocks. -func (f *decompressor) huffmanStringsReader() { - const ( - stateInit = iota // Zero value must be stateInit - stateDict - ) - fr := f.r.(*strings.Reader) - - // Optimization. Compiler isn't smart enough to keep f.b,f.nb in registers, - // but is smart enough to keep local variables in registers, so use nb and b, - // inline call to moreBits and reassign b,nb back to f on return. - fnb, fb, dict := f.nb, f.b, &f.dict - - switch f.stepState { - case stateInit: - goto readLiteral - case stateDict: - goto copyHistory - } - -readLiteral: - // Read literal and/or (length, distance) according to RFC section 3.2.3. - { - var v int - { - // Inlined v, err := f.huffSym(f.hl) - // Since a huffmanDecoder can be empty or be composed of a degenerate tree - // with single element, huffSym must error on these two edge cases. In both - // cases, the chunks slice will be 0 for the invalid sequence, leading it - // satisfy the n == 0 check below. - n := uint(f.hl.maxRead) - for { - for fnb < n { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - f.err = noEOF(err) - return - } - f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) - fnb += 8 - } - chunk := f.hl.chunks[fb&(huffmanNumChunks-1)] - n = uint(chunk & huffmanCountMask) - if n > huffmanChunkBits { - chunk = f.hl.links[chunk>>huffmanValueShift][(fb>>huffmanChunkBits)&f.hl.linkMask] - n = uint(chunk & huffmanCountMask) - } - if n <= fnb { - if n == 0 { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("huffsym: n==0") - } - f.err = CorruptInputError(f.roffset) - return - } - fb = fb >> (n & regSizeMaskUint32) - fnb = fnb - n - v = int(chunk >> huffmanValueShift) - break - } - } - } - - var length int - switch { - case v < 256: - dict.writeByte(byte(v)) - if dict.availWrite() == 0 { - f.toRead = dict.readFlush() - f.step = huffmanStringsReader - f.stepState = stateInit - f.b, f.nb = fb, fnb - return - } - goto readLiteral - case v == 256: - f.b, f.nb = fb, fnb - f.finishBlock() - return - // otherwise, reference to older data - case v < 265: - length = v - (257 - 3) - case v < maxNumLit: - val := decCodeToLen[(v - 257)] - length = int(val.length) + 3 - n := uint(val.extra) - for fnb < n { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("morebits n>0:", err) - } - f.err = err - return - } - f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) - fnb += 8 - } - length += int(fb & bitMask32[n]) - fb >>= n & regSizeMaskUint32 - fnb -= n - default: - if debugDecode { - fmt.Println(v, ">= maxNumLit") - } - f.err = CorruptInputError(f.roffset) - f.b, f.nb = fb, fnb - return - } - - var dist uint32 - if f.hd == nil { - for fnb < 5 { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("morebits f.nb<5:", err) - } - f.err = err - return - } - f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) - fnb += 8 - } - dist = uint32(bits.Reverse8(uint8(fb & 0x1F << 3))) - fb >>= 5 - fnb -= 5 - } else { - // Since a huffmanDecoder can be empty or be composed of a degenerate tree - // with single element, huffSym must error on these two edge cases. In both - // cases, the chunks slice will be 0 for the invalid sequence, leading it - // satisfy the n == 0 check below. - n := uint(f.hd.maxRead) - // Optimization. Compiler isn't smart enough to keep f.b,f.nb in registers, - // but is smart enough to keep local variables in registers, so use nb and b, - // inline call to moreBits and reassign b,nb back to f on return. - for { - for fnb < n { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - f.err = noEOF(err) - return - } - f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) - fnb += 8 - } - chunk := f.hd.chunks[fb&(huffmanNumChunks-1)] - n = uint(chunk & huffmanCountMask) - if n > huffmanChunkBits { - chunk = f.hd.links[chunk>>huffmanValueShift][(fb>>huffmanChunkBits)&f.hd.linkMask] - n = uint(chunk & huffmanCountMask) - } - if n <= fnb { - if n == 0 { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("huffsym: n==0") - } - f.err = CorruptInputError(f.roffset) - return - } - fb = fb >> (n & regSizeMaskUint32) - fnb = fnb - n - dist = uint32(chunk >> huffmanValueShift) - break - } - } - } - - switch { - case dist < 4: - dist++ - case dist < maxNumDist: - nb := uint(dist-2) >> 1 - // have 1 bit in bottom of dist, need nb more. - extra := (dist & 1) << (nb & regSizeMaskUint32) - for fnb < nb { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("morebits f.nb>= nb & regSizeMaskUint32 - fnb -= nb - dist = 1<<((nb+1)®SizeMaskUint32) + 1 + extra - // slower: dist = bitMask32[nb+1] + 2 + extra - default: - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("dist too big:", dist, maxNumDist) - } - f.err = CorruptInputError(f.roffset) - return - } - - // No check on length; encoding can be prescient. - if dist > uint32(dict.histSize()) { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("dist > dict.histSize():", dist, dict.histSize()) - } - f.err = CorruptInputError(f.roffset) - return - } - - f.copyLen, f.copyDist = length, int(dist) - goto copyHistory - } - -copyHistory: - // Perform a backwards copy according to RFC section 3.2.3. - { - cnt := dict.tryWriteCopy(f.copyDist, f.copyLen) - if cnt == 0 { - cnt = dict.writeCopy(f.copyDist, f.copyLen) - } - f.copyLen -= cnt - - if dict.availWrite() == 0 || f.copyLen > 0 { - f.toRead = dict.readFlush() - f.step = huffmanStringsReader // We need to continue this work - f.stepState = stateDict - f.b, f.nb = fb, fnb - return - } - goto readLiteral - } - // Not reached -} - -// Decode a single Huffman block from f. -// hl and hd are the Huffman states for the lit/length values -// and the distance values, respectively. If hd == nil, using the -// fixed distance encoding associated with fixed Huffman blocks. -func (f *decompressor) huffmanGenericReader() { - const ( - stateInit = iota // Zero value must be stateInit - stateDict - ) - fr := f.r.(Reader) - - // Optimization. Compiler isn't smart enough to keep f.b,f.nb in registers, - // but is smart enough to keep local variables in registers, so use nb and b, - // inline call to moreBits and reassign b,nb back to f on return. - fnb, fb, dict := f.nb, f.b, &f.dict - - switch f.stepState { - case stateInit: - goto readLiteral - case stateDict: - goto copyHistory - } - -readLiteral: - // Read literal and/or (length, distance) according to RFC section 3.2.3. - { - var v int - { - // Inlined v, err := f.huffSym(f.hl) - // Since a huffmanDecoder can be empty or be composed of a degenerate tree - // with single element, huffSym must error on these two edge cases. In both - // cases, the chunks slice will be 0 for the invalid sequence, leading it - // satisfy the n == 0 check below. - n := uint(f.hl.maxRead) - for { - for fnb < n { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - f.err = noEOF(err) - return - } - f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) - fnb += 8 - } - chunk := f.hl.chunks[fb&(huffmanNumChunks-1)] - n = uint(chunk & huffmanCountMask) - if n > huffmanChunkBits { - chunk = f.hl.links[chunk>>huffmanValueShift][(fb>>huffmanChunkBits)&f.hl.linkMask] - n = uint(chunk & huffmanCountMask) - } - if n <= fnb { - if n == 0 { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("huffsym: n==0") - } - f.err = CorruptInputError(f.roffset) - return - } - fb = fb >> (n & regSizeMaskUint32) - fnb = fnb - n - v = int(chunk >> huffmanValueShift) - break - } - } - } - - var length int - switch { - case v < 256: - dict.writeByte(byte(v)) - if dict.availWrite() == 0 { - f.toRead = dict.readFlush() - f.step = huffmanGenericReader - f.stepState = stateInit - f.b, f.nb = fb, fnb - return - } - goto readLiteral - case v == 256: - f.b, f.nb = fb, fnb - f.finishBlock() - return - // otherwise, reference to older data - case v < 265: - length = v - (257 - 3) - case v < maxNumLit: - val := decCodeToLen[(v - 257)] - length = int(val.length) + 3 - n := uint(val.extra) - for fnb < n { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("morebits n>0:", err) - } - f.err = err - return - } - f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) - fnb += 8 - } - length += int(fb & bitMask32[n]) - fb >>= n & regSizeMaskUint32 - fnb -= n - default: - if debugDecode { - fmt.Println(v, ">= maxNumLit") - } - f.err = CorruptInputError(f.roffset) - f.b, f.nb = fb, fnb - return - } - - var dist uint32 - if f.hd == nil { - for fnb < 5 { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("morebits f.nb<5:", err) - } - f.err = err - return - } - f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) - fnb += 8 - } - dist = uint32(bits.Reverse8(uint8(fb & 0x1F << 3))) - fb >>= 5 - fnb -= 5 - } else { - // Since a huffmanDecoder can be empty or be composed of a degenerate tree - // with single element, huffSym must error on these two edge cases. In both - // cases, the chunks slice will be 0 for the invalid sequence, leading it - // satisfy the n == 0 check below. - n := uint(f.hd.maxRead) - // Optimization. Compiler isn't smart enough to keep f.b,f.nb in registers, - // but is smart enough to keep local variables in registers, so use nb and b, - // inline call to moreBits and reassign b,nb back to f on return. - for { - for fnb < n { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - f.err = noEOF(err) - return - } - f.roffset++ - fb |= uint32(c) << (fnb & regSizeMaskUint32) - fnb += 8 - } - chunk := f.hd.chunks[fb&(huffmanNumChunks-1)] - n = uint(chunk & huffmanCountMask) - if n > huffmanChunkBits { - chunk = f.hd.links[chunk>>huffmanValueShift][(fb>>huffmanChunkBits)&f.hd.linkMask] - n = uint(chunk & huffmanCountMask) - } - if n <= fnb { - if n == 0 { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("huffsym: n==0") - } - f.err = CorruptInputError(f.roffset) - return - } - fb = fb >> (n & regSizeMaskUint32) - fnb = fnb - n - dist = uint32(chunk >> huffmanValueShift) - break - } - } - } - - switch { - case dist < 4: - dist++ - case dist < maxNumDist: - nb := uint(dist-2) >> 1 - // have 1 bit in bottom of dist, need nb more. - extra := (dist & 1) << (nb & regSizeMaskUint32) - for fnb < nb { - c, err := fr.ReadByte() - if err != nil { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("morebits f.nb>= nb & regSizeMaskUint32 - fnb -= nb - dist = 1<<((nb+1)®SizeMaskUint32) + 1 + extra - // slower: dist = bitMask32[nb+1] + 2 + extra - default: - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("dist too big:", dist, maxNumDist) - } - f.err = CorruptInputError(f.roffset) - return - } - - // No check on length; encoding can be prescient. - if dist > uint32(dict.histSize()) { - f.b, f.nb = fb, fnb - if debugDecode { - fmt.Println("dist > dict.histSize():", dist, dict.histSize()) - } - f.err = CorruptInputError(f.roffset) - return - } - - f.copyLen, f.copyDist = length, int(dist) - goto copyHistory - } - -copyHistory: - // Perform a backwards copy according to RFC section 3.2.3. - { - cnt := dict.tryWriteCopy(f.copyDist, f.copyLen) - if cnt == 0 { - cnt = dict.writeCopy(f.copyDist, f.copyLen) - } - f.copyLen -= cnt - - if dict.availWrite() == 0 || f.copyLen > 0 { - f.toRead = dict.readFlush() - f.step = huffmanGenericReader // We need to continue this work - f.stepState = stateDict - f.b, f.nb = fb, fnb - return - } - goto readLiteral - } - // Not reached -} - -func (f *decompressor) huffmanBlockDecoder() { - switch f.r.(type) { - case *bytes.Buffer: - f.huffmanBytesBuffer() - case *bytes.Reader: - f.huffmanBytesReader() - case *bufio.Reader: - f.huffmanBufioReader() - case *strings.Reader: - f.huffmanStringsReader() - case Reader: - f.huffmanGenericReader() - default: - f.huffmanGenericReader() - } -} diff --git a/vendor/github.com/klauspost/compress/flate/level1.go b/vendor/github.com/klauspost/compress/flate/level1.go deleted file mode 100644 index 703b9a89a..000000000 --- a/vendor/github.com/klauspost/compress/flate/level1.go +++ /dev/null @@ -1,241 +0,0 @@ -package flate - -import ( - "encoding/binary" - "fmt" - "math/bits" -) - -// fastGen maintains the table for matches, -// and the previous byte block for level 2. -// This is the generic implementation. -type fastEncL1 struct { - fastGen - table [tableSize]tableEntry -} - -// EncodeL1 uses a similar algorithm to level 1 -func (e *fastEncL1) Encode(dst *tokens, src []byte) { - const ( - inputMargin = 12 - 1 - minNonLiteralBlockSize = 1 + 1 + inputMargin - hashBytes = 5 - ) - if debugDeflate && e.cur < 0 { - panic(fmt.Sprint("e.cur < 0: ", e.cur)) - } - - // Protect against e.cur wraparound. - for e.cur >= bufferReset { - if len(e.hist) == 0 { - for i := range e.table[:] { - e.table[i] = tableEntry{} - } - e.cur = maxMatchOffset - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - maxMatchOffset - for i := range e.table[:] { - v := e.table[i].offset - if v <= minOff { - v = 0 - } else { - v = v - e.cur + maxMatchOffset - } - e.table[i].offset = v - } - e.cur = maxMatchOffset - } - - s := e.addBlock(src) - - // This check isn't in the Snappy implementation, but there, the caller - // instead of the callee handles this case. - if len(src) < minNonLiteralBlockSize { - // We do not fill the token table. - // This will be picked up by caller. - dst.n = uint16(len(src)) - return - } - - // Override src - src = e.hist - nextEmit := s - - // sLimit is when to stop looking for offset/length copies. The inputMargin - // lets us use a fast path for emitLiteral in the main loop, while we are - // looking for copies. - sLimit := int32(len(src) - inputMargin) - - // nextEmit is where in src the next emitLiteral should start from. - cv := load6432(src, s) - - for { - const skipLog = 5 - const doEvery = 2 - - nextS := s - var candidate tableEntry - for { - nextHash := hashLen(cv, tableBits, hashBytes) - candidate = e.table[nextHash] - nextS = s + doEvery + (s-nextEmit)>>skipLog - if nextS > sLimit { - goto emitRemainder - } - - now := load6432(src, nextS) - e.table[nextHash] = tableEntry{offset: s + e.cur} - nextHash = hashLen(now, tableBits, hashBytes) - - offset := s - (candidate.offset - e.cur) - if offset < maxMatchOffset && uint32(cv) == load3232(src, candidate.offset-e.cur) { - e.table[nextHash] = tableEntry{offset: nextS + e.cur} - break - } - - // Do one right away... - cv = now - s = nextS - nextS++ - candidate = e.table[nextHash] - now >>= 8 - e.table[nextHash] = tableEntry{offset: s + e.cur} - - offset = s - (candidate.offset - e.cur) - if offset < maxMatchOffset && uint32(cv) == load3232(src, candidate.offset-e.cur) { - e.table[nextHash] = tableEntry{offset: nextS + e.cur} - break - } - cv = now - s = nextS - } - - // A 4-byte match has been found. We'll later see if more than 4 bytes - // match. But, prior to the match, src[nextEmit:s] are unmatched. Emit - // them as literal bytes. - for { - // Invariant: we have a 4-byte match at s, and no need to emit any - // literal bytes prior to s. - - // Extend the 4-byte match as long as possible. - t := candidate.offset - e.cur - var l = int32(4) - if false { - l = e.matchlenLong(s+4, t+4, src) + 4 - } else { - // inlined: - a := src[s+4:] - b := src[t+4:] - for len(a) >= 8 { - if diff := binary.LittleEndian.Uint64(a) ^ binary.LittleEndian.Uint64(b); diff != 0 { - l += int32(bits.TrailingZeros64(diff) >> 3) - break - } - l += 8 - a = a[8:] - b = b[8:] - } - if len(a) < 8 { - b = b[:len(a)] - for i := range a { - if a[i] != b[i] { - break - } - l++ - } - } - } - - // Extend backwards - for t > 0 && s > nextEmit && src[t-1] == src[s-1] { - s-- - t-- - l++ - } - if nextEmit < s { - if false { - emitLiteral(dst, src[nextEmit:s]) - } else { - for _, v := range src[nextEmit:s] { - dst.tokens[dst.n] = token(v) - dst.litHist[v]++ - dst.n++ - } - } - } - - // Save the match found - if false { - dst.AddMatchLong(l, uint32(s-t-baseMatchOffset)) - } else { - // Inlined... - xoffset := uint32(s - t - baseMatchOffset) - xlength := l - oc := offsetCode(xoffset) - xoffset |= oc << 16 - for xlength > 0 { - xl := xlength - if xl > 258 { - if xl > 258+baseMatchLength { - xl = 258 - } else { - xl = 258 - baseMatchLength - } - } - xlength -= xl - xl -= baseMatchLength - dst.extraHist[lengthCodes1[uint8(xl)]]++ - dst.offHist[oc]++ - dst.tokens[dst.n] = token(matchType | uint32(xl)<= s { - s = nextS + 1 - } - if s >= sLimit { - // Index first pair after match end. - if int(s+l+8) < len(src) { - cv := load6432(src, s) - e.table[hashLen(cv, tableBits, hashBytes)] = tableEntry{offset: s + e.cur} - } - goto emitRemainder - } - - // We could immediately start working at s now, but to improve - // compression we first update the hash table at s-2 and at s. If - // another emitCopy is not our next move, also calculate nextHash - // at s+1. At least on GOARCH=amd64, these three hash calculations - // are faster as one load64 call (with some shifts) instead of - // three load32 calls. - x := load6432(src, s-2) - o := e.cur + s - 2 - prevHash := hashLen(x, tableBits, hashBytes) - e.table[prevHash] = tableEntry{offset: o} - x >>= 16 - currHash := hashLen(x, tableBits, hashBytes) - candidate = e.table[currHash] - e.table[currHash] = tableEntry{offset: o + 2} - - offset := s - (candidate.offset - e.cur) - if offset > maxMatchOffset || uint32(x) != load3232(src, candidate.offset-e.cur) { - cv = x >> 8 - s++ - break - } - } - } - -emitRemainder: - if int(nextEmit) < len(src) { - // If nothing was added, don't encode literals. - if dst.n == 0 { - return - } - emitLiteral(dst, src[nextEmit:]) - } -} diff --git a/vendor/github.com/klauspost/compress/flate/level2.go b/vendor/github.com/klauspost/compress/flate/level2.go deleted file mode 100644 index 876dfbe30..000000000 --- a/vendor/github.com/klauspost/compress/flate/level2.go +++ /dev/null @@ -1,214 +0,0 @@ -package flate - -import "fmt" - -// fastGen maintains the table for matches, -// and the previous byte block for level 2. -// This is the generic implementation. -type fastEncL2 struct { - fastGen - table [bTableSize]tableEntry -} - -// EncodeL2 uses a similar algorithm to level 1, but is capable -// of matching across blocks giving better compression at a small slowdown. -func (e *fastEncL2) Encode(dst *tokens, src []byte) { - const ( - inputMargin = 12 - 1 - minNonLiteralBlockSize = 1 + 1 + inputMargin - hashBytes = 5 - ) - - if debugDeflate && e.cur < 0 { - panic(fmt.Sprint("e.cur < 0: ", e.cur)) - } - - // Protect against e.cur wraparound. - for e.cur >= bufferReset { - if len(e.hist) == 0 { - for i := range e.table[:] { - e.table[i] = tableEntry{} - } - e.cur = maxMatchOffset - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - maxMatchOffset - for i := range e.table[:] { - v := e.table[i].offset - if v <= minOff { - v = 0 - } else { - v = v - e.cur + maxMatchOffset - } - e.table[i].offset = v - } - e.cur = maxMatchOffset - } - - s := e.addBlock(src) - - // This check isn't in the Snappy implementation, but there, the caller - // instead of the callee handles this case. - if len(src) < minNonLiteralBlockSize { - // We do not fill the token table. - // This will be picked up by caller. - dst.n = uint16(len(src)) - return - } - - // Override src - src = e.hist - nextEmit := s - - // sLimit is when to stop looking for offset/length copies. The inputMargin - // lets us use a fast path for emitLiteral in the main loop, while we are - // looking for copies. - sLimit := int32(len(src) - inputMargin) - - // nextEmit is where in src the next emitLiteral should start from. - cv := load6432(src, s) - for { - // When should we start skipping if we haven't found matches in a long while. - const skipLog = 5 - const doEvery = 2 - - nextS := s - var candidate tableEntry - for { - nextHash := hashLen(cv, bTableBits, hashBytes) - s = nextS - nextS = s + doEvery + (s-nextEmit)>>skipLog - if nextS > sLimit { - goto emitRemainder - } - candidate = e.table[nextHash] - now := load6432(src, nextS) - e.table[nextHash] = tableEntry{offset: s + e.cur} - nextHash = hashLen(now, bTableBits, hashBytes) - - offset := s - (candidate.offset - e.cur) - if offset < maxMatchOffset && uint32(cv) == load3232(src, candidate.offset-e.cur) { - e.table[nextHash] = tableEntry{offset: nextS + e.cur} - break - } - - // Do one right away... - cv = now - s = nextS - nextS++ - candidate = e.table[nextHash] - now >>= 8 - e.table[nextHash] = tableEntry{offset: s + e.cur} - - offset = s - (candidate.offset - e.cur) - if offset < maxMatchOffset && uint32(cv) == load3232(src, candidate.offset-e.cur) { - break - } - cv = now - } - - // A 4-byte match has been found. We'll later see if more than 4 bytes - // match. But, prior to the match, src[nextEmit:s] are unmatched. Emit - // them as literal bytes. - - // Call emitCopy, and then see if another emitCopy could be our next - // move. Repeat until we find no match for the input immediately after - // what was consumed by the last emitCopy call. - // - // If we exit this loop normally then we need to call emitLiteral next, - // though we don't yet know how big the literal will be. We handle that - // by proceeding to the next iteration of the main loop. We also can - // exit this loop via goto if we get close to exhausting the input. - for { - // Invariant: we have a 4-byte match at s, and no need to emit any - // literal bytes prior to s. - - // Extend the 4-byte match as long as possible. - t := candidate.offset - e.cur - l := e.matchlenLong(s+4, t+4, src) + 4 - - // Extend backwards - for t > 0 && s > nextEmit && src[t-1] == src[s-1] { - s-- - t-- - l++ - } - if nextEmit < s { - if false { - emitLiteral(dst, src[nextEmit:s]) - } else { - for _, v := range src[nextEmit:s] { - dst.tokens[dst.n] = token(v) - dst.litHist[v]++ - dst.n++ - } - } - } - - dst.AddMatchLong(l, uint32(s-t-baseMatchOffset)) - s += l - nextEmit = s - if nextS >= s { - s = nextS + 1 - } - - if s >= sLimit { - // Index first pair after match end. - if int(s+l+8) < len(src) { - cv := load6432(src, s) - e.table[hashLen(cv, bTableBits, hashBytes)] = tableEntry{offset: s + e.cur} - } - goto emitRemainder - } - - // Store every second hash in-between, but offset by 1. - for i := s - l + 2; i < s-5; i += 7 { - x := load6432(src, i) - nextHash := hashLen(x, bTableBits, hashBytes) - e.table[nextHash] = tableEntry{offset: e.cur + i} - // Skip one - x >>= 16 - nextHash = hashLen(x, bTableBits, hashBytes) - e.table[nextHash] = tableEntry{offset: e.cur + i + 2} - // Skip one - x >>= 16 - nextHash = hashLen(x, bTableBits, hashBytes) - e.table[nextHash] = tableEntry{offset: e.cur + i + 4} - } - - // We could immediately start working at s now, but to improve - // compression we first update the hash table at s-2 to s. If - // another emitCopy is not our next move, also calculate nextHash - // at s+1. At least on GOARCH=amd64, these three hash calculations - // are faster as one load64 call (with some shifts) instead of - // three load32 calls. - x := load6432(src, s-2) - o := e.cur + s - 2 - prevHash := hashLen(x, bTableBits, hashBytes) - prevHash2 := hashLen(x>>8, bTableBits, hashBytes) - e.table[prevHash] = tableEntry{offset: o} - e.table[prevHash2] = tableEntry{offset: o + 1} - currHash := hashLen(x>>16, bTableBits, hashBytes) - candidate = e.table[currHash] - e.table[currHash] = tableEntry{offset: o + 2} - - offset := s - (candidate.offset - e.cur) - if offset > maxMatchOffset || uint32(x>>16) != load3232(src, candidate.offset-e.cur) { - cv = x >> 24 - s++ - break - } - } - } - -emitRemainder: - if int(nextEmit) < len(src) { - // If nothing was added, don't encode literals. - if dst.n == 0 { - return - } - - emitLiteral(dst, src[nextEmit:]) - } -} diff --git a/vendor/github.com/klauspost/compress/flate/level3.go b/vendor/github.com/klauspost/compress/flate/level3.go deleted file mode 100644 index 7aa2b72a1..000000000 --- a/vendor/github.com/klauspost/compress/flate/level3.go +++ /dev/null @@ -1,241 +0,0 @@ -package flate - -import "fmt" - -// fastEncL3 -type fastEncL3 struct { - fastGen - table [1 << 16]tableEntryPrev -} - -// Encode uses a similar algorithm to level 2, will check up to two candidates. -func (e *fastEncL3) Encode(dst *tokens, src []byte) { - const ( - inputMargin = 12 - 1 - minNonLiteralBlockSize = 1 + 1 + inputMargin - tableBits = 16 - tableSize = 1 << tableBits - hashBytes = 5 - ) - - if debugDeflate && e.cur < 0 { - panic(fmt.Sprint("e.cur < 0: ", e.cur)) - } - - // Protect against e.cur wraparound. - for e.cur >= bufferReset { - if len(e.hist) == 0 { - for i := range e.table[:] { - e.table[i] = tableEntryPrev{} - } - e.cur = maxMatchOffset - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - maxMatchOffset - for i := range e.table[:] { - v := e.table[i] - if v.Cur.offset <= minOff { - v.Cur.offset = 0 - } else { - v.Cur.offset = v.Cur.offset - e.cur + maxMatchOffset - } - if v.Prev.offset <= minOff { - v.Prev.offset = 0 - } else { - v.Prev.offset = v.Prev.offset - e.cur + maxMatchOffset - } - e.table[i] = v - } - e.cur = maxMatchOffset - } - - s := e.addBlock(src) - - // Skip if too small. - if len(src) < minNonLiteralBlockSize { - // We do not fill the token table. - // This will be picked up by caller. - dst.n = uint16(len(src)) - return - } - - // Override src - src = e.hist - nextEmit := s - - // sLimit is when to stop looking for offset/length copies. The inputMargin - // lets us use a fast path for emitLiteral in the main loop, while we are - // looking for copies. - sLimit := int32(len(src) - inputMargin) - - // nextEmit is where in src the next emitLiteral should start from. - cv := load6432(src, s) - for { - const skipLog = 7 - nextS := s - var candidate tableEntry - for { - nextHash := hashLen(cv, tableBits, hashBytes) - s = nextS - nextS = s + 1 + (s-nextEmit)>>skipLog - if nextS > sLimit { - goto emitRemainder - } - candidates := e.table[nextHash] - now := load6432(src, nextS) - - // Safe offset distance until s + 4... - minOffset := e.cur + s - (maxMatchOffset - 4) - e.table[nextHash] = tableEntryPrev{Prev: candidates.Cur, Cur: tableEntry{offset: s + e.cur}} - - // Check both candidates - candidate = candidates.Cur - if candidate.offset < minOffset { - cv = now - // Previous will also be invalid, we have nothing. - continue - } - - if uint32(cv) == load3232(src, candidate.offset-e.cur) { - if candidates.Prev.offset < minOffset || uint32(cv) != load3232(src, candidates.Prev.offset-e.cur) { - break - } - // Both match and are valid, pick longest. - offset := s - (candidate.offset - e.cur) - o2 := s - (candidates.Prev.offset - e.cur) - l1, l2 := matchLen(src[s+4:], src[s-offset+4:]), matchLen(src[s+4:], src[s-o2+4:]) - if l2 > l1 { - candidate = candidates.Prev - } - break - } else { - // We only check if value mismatches. - // Offset will always be invalid in other cases. - candidate = candidates.Prev - if candidate.offset > minOffset && uint32(cv) == load3232(src, candidate.offset-e.cur) { - break - } - } - cv = now - } - - // Call emitCopy, and then see if another emitCopy could be our next - // move. Repeat until we find no match for the input immediately after - // what was consumed by the last emitCopy call. - // - // If we exit this loop normally then we need to call emitLiteral next, - // though we don't yet know how big the literal will be. We handle that - // by proceeding to the next iteration of the main loop. We also can - // exit this loop via goto if we get close to exhausting the input. - for { - // Invariant: we have a 4-byte match at s, and no need to emit any - // literal bytes prior to s. - - // Extend the 4-byte match as long as possible. - // - t := candidate.offset - e.cur - l := e.matchlenLong(s+4, t+4, src) + 4 - - // Extend backwards - for t > 0 && s > nextEmit && src[t-1] == src[s-1] { - s-- - t-- - l++ - } - if nextEmit < s { - if false { - emitLiteral(dst, src[nextEmit:s]) - } else { - for _, v := range src[nextEmit:s] { - dst.tokens[dst.n] = token(v) - dst.litHist[v]++ - dst.n++ - } - } - } - - dst.AddMatchLong(l, uint32(s-t-baseMatchOffset)) - s += l - nextEmit = s - if nextS >= s { - s = nextS + 1 - } - - if s >= sLimit { - t += l - // Index first pair after match end. - if int(t+8) < len(src) && t > 0 { - cv = load6432(src, t) - nextHash := hashLen(cv, tableBits, hashBytes) - e.table[nextHash] = tableEntryPrev{ - Prev: e.table[nextHash].Cur, - Cur: tableEntry{offset: e.cur + t}, - } - } - goto emitRemainder - } - - // Store every 5th hash in-between. - for i := s - l + 2; i < s-5; i += 6 { - nextHash := hashLen(load6432(src, i), tableBits, hashBytes) - e.table[nextHash] = tableEntryPrev{ - Prev: e.table[nextHash].Cur, - Cur: tableEntry{offset: e.cur + i}} - } - // We could immediately start working at s now, but to improve - // compression we first update the hash table at s-2 to s. - x := load6432(src, s-2) - prevHash := hashLen(x, tableBits, hashBytes) - - e.table[prevHash] = tableEntryPrev{ - Prev: e.table[prevHash].Cur, - Cur: tableEntry{offset: e.cur + s - 2}, - } - x >>= 8 - prevHash = hashLen(x, tableBits, hashBytes) - - e.table[prevHash] = tableEntryPrev{ - Prev: e.table[prevHash].Cur, - Cur: tableEntry{offset: e.cur + s - 1}, - } - x >>= 8 - currHash := hashLen(x, tableBits, hashBytes) - candidates := e.table[currHash] - cv = x - e.table[currHash] = tableEntryPrev{ - Prev: candidates.Cur, - Cur: tableEntry{offset: s + e.cur}, - } - - // Check both candidates - candidate = candidates.Cur - minOffset := e.cur + s - (maxMatchOffset - 4) - - if candidate.offset > minOffset { - if uint32(cv) == load3232(src, candidate.offset-e.cur) { - // Found a match... - continue - } - candidate = candidates.Prev - if candidate.offset > minOffset && uint32(cv) == load3232(src, candidate.offset-e.cur) { - // Match at prev... - continue - } - } - cv = x >> 8 - s++ - break - } - } - -emitRemainder: - if int(nextEmit) < len(src) { - // If nothing was added, don't encode literals. - if dst.n == 0 { - return - } - - emitLiteral(dst, src[nextEmit:]) - } -} diff --git a/vendor/github.com/klauspost/compress/flate/level4.go b/vendor/github.com/klauspost/compress/flate/level4.go deleted file mode 100644 index 23c08b325..000000000 --- a/vendor/github.com/klauspost/compress/flate/level4.go +++ /dev/null @@ -1,221 +0,0 @@ -package flate - -import "fmt" - -type fastEncL4 struct { - fastGen - table [tableSize]tableEntry - bTable [tableSize]tableEntry -} - -func (e *fastEncL4) Encode(dst *tokens, src []byte) { - const ( - inputMargin = 12 - 1 - minNonLiteralBlockSize = 1 + 1 + inputMargin - hashShortBytes = 4 - ) - if debugDeflate && e.cur < 0 { - panic(fmt.Sprint("e.cur < 0: ", e.cur)) - } - // Protect against e.cur wraparound. - for e.cur >= bufferReset { - if len(e.hist) == 0 { - for i := range e.table[:] { - e.table[i] = tableEntry{} - } - for i := range e.bTable[:] { - e.bTable[i] = tableEntry{} - } - e.cur = maxMatchOffset - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - maxMatchOffset - for i := range e.table[:] { - v := e.table[i].offset - if v <= minOff { - v = 0 - } else { - v = v - e.cur + maxMatchOffset - } - e.table[i].offset = v - } - for i := range e.bTable[:] { - v := e.bTable[i].offset - if v <= minOff { - v = 0 - } else { - v = v - e.cur + maxMatchOffset - } - e.bTable[i].offset = v - } - e.cur = maxMatchOffset - } - - s := e.addBlock(src) - - // This check isn't in the Snappy implementation, but there, the caller - // instead of the callee handles this case. - if len(src) < minNonLiteralBlockSize { - // We do not fill the token table. - // This will be picked up by caller. - dst.n = uint16(len(src)) - return - } - - // Override src - src = e.hist - nextEmit := s - - // sLimit is when to stop looking for offset/length copies. The inputMargin - // lets us use a fast path for emitLiteral in the main loop, while we are - // looking for copies. - sLimit := int32(len(src) - inputMargin) - - // nextEmit is where in src the next emitLiteral should start from. - cv := load6432(src, s) - for { - const skipLog = 6 - const doEvery = 1 - - nextS := s - var t int32 - for { - nextHashS := hashLen(cv, tableBits, hashShortBytes) - nextHashL := hash7(cv, tableBits) - - s = nextS - nextS = s + doEvery + (s-nextEmit)>>skipLog - if nextS > sLimit { - goto emitRemainder - } - // Fetch a short+long candidate - sCandidate := e.table[nextHashS] - lCandidate := e.bTable[nextHashL] - next := load6432(src, nextS) - entry := tableEntry{offset: s + e.cur} - e.table[nextHashS] = entry - e.bTable[nextHashL] = entry - - t = lCandidate.offset - e.cur - if s-t < maxMatchOffset && uint32(cv) == load3232(src, lCandidate.offset-e.cur) { - // We got a long match. Use that. - break - } - - t = sCandidate.offset - e.cur - if s-t < maxMatchOffset && uint32(cv) == load3232(src, sCandidate.offset-e.cur) { - // Found a 4 match... - lCandidate = e.bTable[hash7(next, tableBits)] - - // If the next long is a candidate, check if we should use that instead... - lOff := nextS - (lCandidate.offset - e.cur) - if lOff < maxMatchOffset && load3232(src, lCandidate.offset-e.cur) == uint32(next) { - l1, l2 := matchLen(src[s+4:], src[t+4:]), matchLen(src[nextS+4:], src[nextS-lOff+4:]) - if l2 > l1 { - s = nextS - t = lCandidate.offset - e.cur - } - } - break - } - cv = next - } - - // A 4-byte match has been found. We'll later see if more than 4 bytes - // match. But, prior to the match, src[nextEmit:s] are unmatched. Emit - // them as literal bytes. - - // Extend the 4-byte match as long as possible. - l := e.matchlenLong(s+4, t+4, src) + 4 - - // Extend backwards - for t > 0 && s > nextEmit && src[t-1] == src[s-1] { - s-- - t-- - l++ - } - if nextEmit < s { - if false { - emitLiteral(dst, src[nextEmit:s]) - } else { - for _, v := range src[nextEmit:s] { - dst.tokens[dst.n] = token(v) - dst.litHist[v]++ - dst.n++ - } - } - } - if debugDeflate { - if t >= s { - panic("s-t") - } - if (s - t) > maxMatchOffset { - panic(fmt.Sprintln("mmo", t)) - } - if l < baseMatchLength { - panic("bml") - } - } - - dst.AddMatchLong(l, uint32(s-t-baseMatchOffset)) - s += l - nextEmit = s - if nextS >= s { - s = nextS + 1 - } - - if s >= sLimit { - // Index first pair after match end. - if int(s+8) < len(src) { - cv := load6432(src, s) - e.table[hashLen(cv, tableBits, hashShortBytes)] = tableEntry{offset: s + e.cur} - e.bTable[hash7(cv, tableBits)] = tableEntry{offset: s + e.cur} - } - goto emitRemainder - } - - // Store every 3rd hash in-between - if true { - i := nextS - if i < s-1 { - cv := load6432(src, i) - t := tableEntry{offset: i + e.cur} - t2 := tableEntry{offset: t.offset + 1} - e.bTable[hash7(cv, tableBits)] = t - e.bTable[hash7(cv>>8, tableBits)] = t2 - e.table[hashLen(cv>>8, tableBits, hashShortBytes)] = t2 - - i += 3 - for ; i < s-1; i += 3 { - cv := load6432(src, i) - t := tableEntry{offset: i + e.cur} - t2 := tableEntry{offset: t.offset + 1} - e.bTable[hash7(cv, tableBits)] = t - e.bTable[hash7(cv>>8, tableBits)] = t2 - e.table[hashLen(cv>>8, tableBits, hashShortBytes)] = t2 - } - } - } - - // We could immediately start working at s now, but to improve - // compression we first update the hash table at s-1 and at s. - x := load6432(src, s-1) - o := e.cur + s - 1 - prevHashS := hashLen(x, tableBits, hashShortBytes) - prevHashL := hash7(x, tableBits) - e.table[prevHashS] = tableEntry{offset: o} - e.bTable[prevHashL] = tableEntry{offset: o} - cv = x >> 8 - } - -emitRemainder: - if int(nextEmit) < len(src) { - // If nothing was added, don't encode literals. - if dst.n == 0 { - return - } - - emitLiteral(dst, src[nextEmit:]) - } -} diff --git a/vendor/github.com/klauspost/compress/flate/level5.go b/vendor/github.com/klauspost/compress/flate/level5.go deleted file mode 100644 index 1f61ec182..000000000 --- a/vendor/github.com/klauspost/compress/flate/level5.go +++ /dev/null @@ -1,708 +0,0 @@ -package flate - -import "fmt" - -type fastEncL5 struct { - fastGen - table [tableSize]tableEntry - bTable [tableSize]tableEntryPrev -} - -func (e *fastEncL5) Encode(dst *tokens, src []byte) { - const ( - inputMargin = 12 - 1 - minNonLiteralBlockSize = 1 + 1 + inputMargin - hashShortBytes = 4 - ) - if debugDeflate && e.cur < 0 { - panic(fmt.Sprint("e.cur < 0: ", e.cur)) - } - - // Protect against e.cur wraparound. - for e.cur >= bufferReset { - if len(e.hist) == 0 { - for i := range e.table[:] { - e.table[i] = tableEntry{} - } - for i := range e.bTable[:] { - e.bTable[i] = tableEntryPrev{} - } - e.cur = maxMatchOffset - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - maxMatchOffset - for i := range e.table[:] { - v := e.table[i].offset - if v <= minOff { - v = 0 - } else { - v = v - e.cur + maxMatchOffset - } - e.table[i].offset = v - } - for i := range e.bTable[:] { - v := e.bTable[i] - if v.Cur.offset <= minOff { - v.Cur.offset = 0 - v.Prev.offset = 0 - } else { - v.Cur.offset = v.Cur.offset - e.cur + maxMatchOffset - if v.Prev.offset <= minOff { - v.Prev.offset = 0 - } else { - v.Prev.offset = v.Prev.offset - e.cur + maxMatchOffset - } - } - e.bTable[i] = v - } - e.cur = maxMatchOffset - } - - s := e.addBlock(src) - - // This check isn't in the Snappy implementation, but there, the caller - // instead of the callee handles this case. - if len(src) < minNonLiteralBlockSize { - // We do not fill the token table. - // This will be picked up by caller. - dst.n = uint16(len(src)) - return - } - - // Override src - src = e.hist - nextEmit := s - - // sLimit is when to stop looking for offset/length copies. The inputMargin - // lets us use a fast path for emitLiteral in the main loop, while we are - // looking for copies. - sLimit := int32(len(src) - inputMargin) - - // nextEmit is where in src the next emitLiteral should start from. - cv := load6432(src, s) - for { - const skipLog = 6 - const doEvery = 1 - - nextS := s - var l int32 - var t int32 - for { - nextHashS := hashLen(cv, tableBits, hashShortBytes) - nextHashL := hash7(cv, tableBits) - - s = nextS - nextS = s + doEvery + (s-nextEmit)>>skipLog - if nextS > sLimit { - goto emitRemainder - } - // Fetch a short+long candidate - sCandidate := e.table[nextHashS] - lCandidate := e.bTable[nextHashL] - next := load6432(src, nextS) - entry := tableEntry{offset: s + e.cur} - e.table[nextHashS] = entry - eLong := &e.bTable[nextHashL] - eLong.Cur, eLong.Prev = entry, eLong.Cur - - nextHashS = hashLen(next, tableBits, hashShortBytes) - nextHashL = hash7(next, tableBits) - - t = lCandidate.Cur.offset - e.cur - if s-t < maxMatchOffset { - if uint32(cv) == load3232(src, lCandidate.Cur.offset-e.cur) { - // Store the next match - e.table[nextHashS] = tableEntry{offset: nextS + e.cur} - eLong := &e.bTable[nextHashL] - eLong.Cur, eLong.Prev = tableEntry{offset: nextS + e.cur}, eLong.Cur - - t2 := lCandidate.Prev.offset - e.cur - if s-t2 < maxMatchOffset && uint32(cv) == load3232(src, lCandidate.Prev.offset-e.cur) { - l = e.matchlen(s+4, t+4, src) + 4 - ml1 := e.matchlen(s+4, t2+4, src) + 4 - if ml1 > l { - t = t2 - l = ml1 - break - } - } - break - } - t = lCandidate.Prev.offset - e.cur - if s-t < maxMatchOffset && uint32(cv) == load3232(src, lCandidate.Prev.offset-e.cur) { - // Store the next match - e.table[nextHashS] = tableEntry{offset: nextS + e.cur} - eLong := &e.bTable[nextHashL] - eLong.Cur, eLong.Prev = tableEntry{offset: nextS + e.cur}, eLong.Cur - break - } - } - - t = sCandidate.offset - e.cur - if s-t < maxMatchOffset && uint32(cv) == load3232(src, sCandidate.offset-e.cur) { - // Found a 4 match... - l = e.matchlen(s+4, t+4, src) + 4 - lCandidate = e.bTable[nextHashL] - // Store the next match - - e.table[nextHashS] = tableEntry{offset: nextS + e.cur} - eLong := &e.bTable[nextHashL] - eLong.Cur, eLong.Prev = tableEntry{offset: nextS + e.cur}, eLong.Cur - - // If the next long is a candidate, use that... - t2 := lCandidate.Cur.offset - e.cur - if nextS-t2 < maxMatchOffset { - if load3232(src, lCandidate.Cur.offset-e.cur) == uint32(next) { - ml := e.matchlen(nextS+4, t2+4, src) + 4 - if ml > l { - t = t2 - s = nextS - l = ml - break - } - } - // If the previous long is a candidate, use that... - t2 = lCandidate.Prev.offset - e.cur - if nextS-t2 < maxMatchOffset && load3232(src, lCandidate.Prev.offset-e.cur) == uint32(next) { - ml := e.matchlen(nextS+4, t2+4, src) + 4 - if ml > l { - t = t2 - s = nextS - l = ml - break - } - } - } - break - } - cv = next - } - - // A 4-byte match has been found. We'll later see if more than 4 bytes - // match. But, prior to the match, src[nextEmit:s] are unmatched. Emit - // them as literal bytes. - - if l == 0 { - // Extend the 4-byte match as long as possible. - l = e.matchlenLong(s+4, t+4, src) + 4 - } else if l == maxMatchLength { - l += e.matchlenLong(s+l, t+l, src) - } - - // Try to locate a better match by checking the end of best match... - if sAt := s + l; l < 30 && sAt < sLimit { - // Allow some bytes at the beginning to mismatch. - // Sweet spot is 2/3 bytes depending on input. - // 3 is only a little better when it is but sometimes a lot worse. - // The skipped bytes are tested in Extend backwards, - // and still picked up as part of the match if they do. - const skipBeginning = 2 - eLong := e.bTable[hash7(load6432(src, sAt), tableBits)].Cur.offset - t2 := eLong - e.cur - l + skipBeginning - s2 := s + skipBeginning - off := s2 - t2 - if t2 >= 0 && off < maxMatchOffset && off > 0 { - if l2 := e.matchlenLong(s2, t2, src); l2 > l { - t = t2 - l = l2 - s = s2 - } - } - } - - // Extend backwards - for t > 0 && s > nextEmit && src[t-1] == src[s-1] { - s-- - t-- - l++ - } - if nextEmit < s { - if false { - emitLiteral(dst, src[nextEmit:s]) - } else { - for _, v := range src[nextEmit:s] { - dst.tokens[dst.n] = token(v) - dst.litHist[v]++ - dst.n++ - } - } - } - if debugDeflate { - if t >= s { - panic(fmt.Sprintln("s-t", s, t)) - } - if (s - t) > maxMatchOffset { - panic(fmt.Sprintln("mmo", s-t)) - } - if l < baseMatchLength { - panic("bml") - } - } - - dst.AddMatchLong(l, uint32(s-t-baseMatchOffset)) - s += l - nextEmit = s - if nextS >= s { - s = nextS + 1 - } - - if s >= sLimit { - goto emitRemainder - } - - // Store every 3rd hash in-between. - if true { - const hashEvery = 3 - i := s - l + 1 - if i < s-1 { - cv := load6432(src, i) - t := tableEntry{offset: i + e.cur} - e.table[hashLen(cv, tableBits, hashShortBytes)] = t - eLong := &e.bTable[hash7(cv, tableBits)] - eLong.Cur, eLong.Prev = t, eLong.Cur - - // Do an long at i+1 - cv >>= 8 - t = tableEntry{offset: t.offset + 1} - eLong = &e.bTable[hash7(cv, tableBits)] - eLong.Cur, eLong.Prev = t, eLong.Cur - - // We only have enough bits for a short entry at i+2 - cv >>= 8 - t = tableEntry{offset: t.offset + 1} - e.table[hashLen(cv, tableBits, hashShortBytes)] = t - - // Skip one - otherwise we risk hitting 's' - i += 4 - for ; i < s-1; i += hashEvery { - cv := load6432(src, i) - t := tableEntry{offset: i + e.cur} - t2 := tableEntry{offset: t.offset + 1} - eLong := &e.bTable[hash7(cv, tableBits)] - eLong.Cur, eLong.Prev = t, eLong.Cur - e.table[hashLen(cv>>8, tableBits, hashShortBytes)] = t2 - } - } - } - - // We could immediately start working at s now, but to improve - // compression we first update the hash table at s-1 and at s. - x := load6432(src, s-1) - o := e.cur + s - 1 - prevHashS := hashLen(x, tableBits, hashShortBytes) - prevHashL := hash7(x, tableBits) - e.table[prevHashS] = tableEntry{offset: o} - eLong := &e.bTable[prevHashL] - eLong.Cur, eLong.Prev = tableEntry{offset: o}, eLong.Cur - cv = x >> 8 - } - -emitRemainder: - if int(nextEmit) < len(src) { - // If nothing was added, don't encode literals. - if dst.n == 0 { - return - } - - emitLiteral(dst, src[nextEmit:]) - } -} - -// fastEncL5Window is a level 5 encoder, -// but with a custom window size. -type fastEncL5Window struct { - hist []byte - cur int32 - maxOffset int32 - table [tableSize]tableEntry - bTable [tableSize]tableEntryPrev -} - -func (e *fastEncL5Window) Encode(dst *tokens, src []byte) { - const ( - inputMargin = 12 - 1 - minNonLiteralBlockSize = 1 + 1 + inputMargin - hashShortBytes = 4 - ) - maxMatchOffset := e.maxOffset - if debugDeflate && e.cur < 0 { - panic(fmt.Sprint("e.cur < 0: ", e.cur)) - } - - // Protect against e.cur wraparound. - for e.cur >= bufferReset { - if len(e.hist) == 0 { - for i := range e.table[:] { - e.table[i] = tableEntry{} - } - for i := range e.bTable[:] { - e.bTable[i] = tableEntryPrev{} - } - e.cur = maxMatchOffset - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - maxMatchOffset - for i := range e.table[:] { - v := e.table[i].offset - if v <= minOff { - v = 0 - } else { - v = v - e.cur + maxMatchOffset - } - e.table[i].offset = v - } - for i := range e.bTable[:] { - v := e.bTable[i] - if v.Cur.offset <= minOff { - v.Cur.offset = 0 - v.Prev.offset = 0 - } else { - v.Cur.offset = v.Cur.offset - e.cur + maxMatchOffset - if v.Prev.offset <= minOff { - v.Prev.offset = 0 - } else { - v.Prev.offset = v.Prev.offset - e.cur + maxMatchOffset - } - } - e.bTable[i] = v - } - e.cur = maxMatchOffset - } - - s := e.addBlock(src) - - // This check isn't in the Snappy implementation, but there, the caller - // instead of the callee handles this case. - if len(src) < minNonLiteralBlockSize { - // We do not fill the token table. - // This will be picked up by caller. - dst.n = uint16(len(src)) - return - } - - // Override src - src = e.hist - nextEmit := s - - // sLimit is when to stop looking for offset/length copies. The inputMargin - // lets us use a fast path for emitLiteral in the main loop, while we are - // looking for copies. - sLimit := int32(len(src) - inputMargin) - - // nextEmit is where in src the next emitLiteral should start from. - cv := load6432(src, s) - for { - const skipLog = 6 - const doEvery = 1 - - nextS := s - var l int32 - var t int32 - for { - nextHashS := hashLen(cv, tableBits, hashShortBytes) - nextHashL := hash7(cv, tableBits) - - s = nextS - nextS = s + doEvery + (s-nextEmit)>>skipLog - if nextS > sLimit { - goto emitRemainder - } - // Fetch a short+long candidate - sCandidate := e.table[nextHashS] - lCandidate := e.bTable[nextHashL] - next := load6432(src, nextS) - entry := tableEntry{offset: s + e.cur} - e.table[nextHashS] = entry - eLong := &e.bTable[nextHashL] - eLong.Cur, eLong.Prev = entry, eLong.Cur - - nextHashS = hashLen(next, tableBits, hashShortBytes) - nextHashL = hash7(next, tableBits) - - t = lCandidate.Cur.offset - e.cur - if s-t < maxMatchOffset { - if uint32(cv) == load3232(src, lCandidate.Cur.offset-e.cur) { - // Store the next match - e.table[nextHashS] = tableEntry{offset: nextS + e.cur} - eLong := &e.bTable[nextHashL] - eLong.Cur, eLong.Prev = tableEntry{offset: nextS + e.cur}, eLong.Cur - - t2 := lCandidate.Prev.offset - e.cur - if s-t2 < maxMatchOffset && uint32(cv) == load3232(src, lCandidate.Prev.offset-e.cur) { - l = e.matchlen(s+4, t+4, src) + 4 - ml1 := e.matchlen(s+4, t2+4, src) + 4 - if ml1 > l { - t = t2 - l = ml1 - break - } - } - break - } - t = lCandidate.Prev.offset - e.cur - if s-t < maxMatchOffset && uint32(cv) == load3232(src, lCandidate.Prev.offset-e.cur) { - // Store the next match - e.table[nextHashS] = tableEntry{offset: nextS + e.cur} - eLong := &e.bTable[nextHashL] - eLong.Cur, eLong.Prev = tableEntry{offset: nextS + e.cur}, eLong.Cur - break - } - } - - t = sCandidate.offset - e.cur - if s-t < maxMatchOffset && uint32(cv) == load3232(src, sCandidate.offset-e.cur) { - // Found a 4 match... - l = e.matchlen(s+4, t+4, src) + 4 - lCandidate = e.bTable[nextHashL] - // Store the next match - - e.table[nextHashS] = tableEntry{offset: nextS + e.cur} - eLong := &e.bTable[nextHashL] - eLong.Cur, eLong.Prev = tableEntry{offset: nextS + e.cur}, eLong.Cur - - // If the next long is a candidate, use that... - t2 := lCandidate.Cur.offset - e.cur - if nextS-t2 < maxMatchOffset { - if load3232(src, lCandidate.Cur.offset-e.cur) == uint32(next) { - ml := e.matchlen(nextS+4, t2+4, src) + 4 - if ml > l { - t = t2 - s = nextS - l = ml - break - } - } - // If the previous long is a candidate, use that... - t2 = lCandidate.Prev.offset - e.cur - if nextS-t2 < maxMatchOffset && load3232(src, lCandidate.Prev.offset-e.cur) == uint32(next) { - ml := e.matchlen(nextS+4, t2+4, src) + 4 - if ml > l { - t = t2 - s = nextS - l = ml - break - } - } - } - break - } - cv = next - } - - // A 4-byte match has been found. We'll later see if more than 4 bytes - // match. But, prior to the match, src[nextEmit:s] are unmatched. Emit - // them as literal bytes. - - if l == 0 { - // Extend the 4-byte match as long as possible. - l = e.matchlenLong(s+4, t+4, src) + 4 - } else if l == maxMatchLength { - l += e.matchlenLong(s+l, t+l, src) - } - - // Try to locate a better match by checking the end of best match... - if sAt := s + l; l < 30 && sAt < sLimit { - // Allow some bytes at the beginning to mismatch. - // Sweet spot is 2/3 bytes depending on input. - // 3 is only a little better when it is but sometimes a lot worse. - // The skipped bytes are tested in Extend backwards, - // and still picked up as part of the match if they do. - const skipBeginning = 2 - eLong := e.bTable[hash7(load6432(src, sAt), tableBits)].Cur.offset - t2 := eLong - e.cur - l + skipBeginning - s2 := s + skipBeginning - off := s2 - t2 - if t2 >= 0 && off < maxMatchOffset && off > 0 { - if l2 := e.matchlenLong(s2, t2, src); l2 > l { - t = t2 - l = l2 - s = s2 - } - } - } - - // Extend backwards - for t > 0 && s > nextEmit && src[t-1] == src[s-1] { - s-- - t-- - l++ - } - if nextEmit < s { - if false { - emitLiteral(dst, src[nextEmit:s]) - } else { - for _, v := range src[nextEmit:s] { - dst.tokens[dst.n] = token(v) - dst.litHist[v]++ - dst.n++ - } - } - } - if debugDeflate { - if t >= s { - panic(fmt.Sprintln("s-t", s, t)) - } - if (s - t) > maxMatchOffset { - panic(fmt.Sprintln("mmo", s-t)) - } - if l < baseMatchLength { - panic("bml") - } - } - - dst.AddMatchLong(l, uint32(s-t-baseMatchOffset)) - s += l - nextEmit = s - if nextS >= s { - s = nextS + 1 - } - - if s >= sLimit { - goto emitRemainder - } - - // Store every 3rd hash in-between. - if true { - const hashEvery = 3 - i := s - l + 1 - if i < s-1 { - cv := load6432(src, i) - t := tableEntry{offset: i + e.cur} - e.table[hashLen(cv, tableBits, hashShortBytes)] = t - eLong := &e.bTable[hash7(cv, tableBits)] - eLong.Cur, eLong.Prev = t, eLong.Cur - - // Do an long at i+1 - cv >>= 8 - t = tableEntry{offset: t.offset + 1} - eLong = &e.bTable[hash7(cv, tableBits)] - eLong.Cur, eLong.Prev = t, eLong.Cur - - // We only have enough bits for a short entry at i+2 - cv >>= 8 - t = tableEntry{offset: t.offset + 1} - e.table[hashLen(cv, tableBits, hashShortBytes)] = t - - // Skip one - otherwise we risk hitting 's' - i += 4 - for ; i < s-1; i += hashEvery { - cv := load6432(src, i) - t := tableEntry{offset: i + e.cur} - t2 := tableEntry{offset: t.offset + 1} - eLong := &e.bTable[hash7(cv, tableBits)] - eLong.Cur, eLong.Prev = t, eLong.Cur - e.table[hashLen(cv>>8, tableBits, hashShortBytes)] = t2 - } - } - } - - // We could immediately start working at s now, but to improve - // compression we first update the hash table at s-1 and at s. - x := load6432(src, s-1) - o := e.cur + s - 1 - prevHashS := hashLen(x, tableBits, hashShortBytes) - prevHashL := hash7(x, tableBits) - e.table[prevHashS] = tableEntry{offset: o} - eLong := &e.bTable[prevHashL] - eLong.Cur, eLong.Prev = tableEntry{offset: o}, eLong.Cur - cv = x >> 8 - } - -emitRemainder: - if int(nextEmit) < len(src) { - // If nothing was added, don't encode literals. - if dst.n == 0 { - return - } - - emitLiteral(dst, src[nextEmit:]) - } -} - -// Reset the encoding table. -func (e *fastEncL5Window) Reset() { - // We keep the same allocs, since we are compressing the same block sizes. - if cap(e.hist) < allocHistory { - e.hist = make([]byte, 0, allocHistory) - } - - // We offset current position so everything will be out of reach. - // If we are above the buffer reset it will be cleared anyway since len(hist) == 0. - if e.cur <= int32(bufferReset) { - e.cur += e.maxOffset + int32(len(e.hist)) - } - e.hist = e.hist[:0] -} - -func (e *fastEncL5Window) addBlock(src []byte) int32 { - // check if we have space already - maxMatchOffset := e.maxOffset - - if len(e.hist)+len(src) > cap(e.hist) { - if cap(e.hist) == 0 { - e.hist = make([]byte, 0, allocHistory) - } else { - if cap(e.hist) < int(maxMatchOffset*2) { - panic("unexpected buffer size") - } - // Move down - offset := int32(len(e.hist)) - maxMatchOffset - copy(e.hist[0:maxMatchOffset], e.hist[offset:]) - e.cur += offset - e.hist = e.hist[:maxMatchOffset] - } - } - s := int32(len(e.hist)) - e.hist = append(e.hist, src...) - return s -} - -// matchlen will return the match length between offsets and t in src. -// The maximum length returned is maxMatchLength - 4. -// It is assumed that s > t, that t >=0 and s < len(src). -func (e *fastEncL5Window) matchlen(s, t int32, src []byte) int32 { - if debugDecode { - if t >= s { - panic(fmt.Sprint("t >=s:", t, s)) - } - if int(s) >= len(src) { - panic(fmt.Sprint("s >= len(src):", s, len(src))) - } - if t < 0 { - panic(fmt.Sprint("t < 0:", t)) - } - if s-t > e.maxOffset { - panic(fmt.Sprint(s, "-", t, "(", s-t, ") > maxMatchLength (", maxMatchOffset, ")")) - } - } - s1 := int(s) + maxMatchLength - 4 - if s1 > len(src) { - s1 = len(src) - } - - // Extend the match to be as long as possible. - return int32(matchLen(src[s:s1], src[t:])) -} - -// matchlenLong will return the match length between offsets and t in src. -// It is assumed that s > t, that t >=0 and s < len(src). -func (e *fastEncL5Window) matchlenLong(s, t int32, src []byte) int32 { - if debugDeflate { - if t >= s { - panic(fmt.Sprint("t >=s:", t, s)) - } - if int(s) >= len(src) { - panic(fmt.Sprint("s >= len(src):", s, len(src))) - } - if t < 0 { - panic(fmt.Sprint("t < 0:", t)) - } - if s-t > e.maxOffset { - panic(fmt.Sprint(s, "-", t, "(", s-t, ") > maxMatchLength (", maxMatchOffset, ")")) - } - } - // Extend the match to be as long as possible. - return int32(matchLen(src[s:], src[t:])) -} diff --git a/vendor/github.com/klauspost/compress/flate/level6.go b/vendor/github.com/klauspost/compress/flate/level6.go deleted file mode 100644 index f1e9d98fa..000000000 --- a/vendor/github.com/klauspost/compress/flate/level6.go +++ /dev/null @@ -1,325 +0,0 @@ -package flate - -import "fmt" - -type fastEncL6 struct { - fastGen - table [tableSize]tableEntry - bTable [tableSize]tableEntryPrev -} - -func (e *fastEncL6) Encode(dst *tokens, src []byte) { - const ( - inputMargin = 12 - 1 - minNonLiteralBlockSize = 1 + 1 + inputMargin - hashShortBytes = 4 - ) - if debugDeflate && e.cur < 0 { - panic(fmt.Sprint("e.cur < 0: ", e.cur)) - } - - // Protect against e.cur wraparound. - for e.cur >= bufferReset { - if len(e.hist) == 0 { - for i := range e.table[:] { - e.table[i] = tableEntry{} - } - for i := range e.bTable[:] { - e.bTable[i] = tableEntryPrev{} - } - e.cur = maxMatchOffset - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - maxMatchOffset - for i := range e.table[:] { - v := e.table[i].offset - if v <= minOff { - v = 0 - } else { - v = v - e.cur + maxMatchOffset - } - e.table[i].offset = v - } - for i := range e.bTable[:] { - v := e.bTable[i] - if v.Cur.offset <= minOff { - v.Cur.offset = 0 - v.Prev.offset = 0 - } else { - v.Cur.offset = v.Cur.offset - e.cur + maxMatchOffset - if v.Prev.offset <= minOff { - v.Prev.offset = 0 - } else { - v.Prev.offset = v.Prev.offset - e.cur + maxMatchOffset - } - } - e.bTable[i] = v - } - e.cur = maxMatchOffset - } - - s := e.addBlock(src) - - // This check isn't in the Snappy implementation, but there, the caller - // instead of the callee handles this case. - if len(src) < minNonLiteralBlockSize { - // We do not fill the token table. - // This will be picked up by caller. - dst.n = uint16(len(src)) - return - } - - // Override src - src = e.hist - nextEmit := s - - // sLimit is when to stop looking for offset/length copies. The inputMargin - // lets us use a fast path for emitLiteral in the main loop, while we are - // looking for copies. - sLimit := int32(len(src) - inputMargin) - - // nextEmit is where in src the next emitLiteral should start from. - cv := load6432(src, s) - // Repeat MUST be > 1 and within range - repeat := int32(1) - for { - const skipLog = 7 - const doEvery = 1 - - nextS := s - var l int32 - var t int32 - for { - nextHashS := hashLen(cv, tableBits, hashShortBytes) - nextHashL := hash7(cv, tableBits) - s = nextS - nextS = s + doEvery + (s-nextEmit)>>skipLog - if nextS > sLimit { - goto emitRemainder - } - // Fetch a short+long candidate - sCandidate := e.table[nextHashS] - lCandidate := e.bTable[nextHashL] - next := load6432(src, nextS) - entry := tableEntry{offset: s + e.cur} - e.table[nextHashS] = entry - eLong := &e.bTable[nextHashL] - eLong.Cur, eLong.Prev = entry, eLong.Cur - - // Calculate hashes of 'next' - nextHashS = hashLen(next, tableBits, hashShortBytes) - nextHashL = hash7(next, tableBits) - - t = lCandidate.Cur.offset - e.cur - if s-t < maxMatchOffset { - if uint32(cv) == load3232(src, lCandidate.Cur.offset-e.cur) { - // Long candidate matches at least 4 bytes. - - // Store the next match - e.table[nextHashS] = tableEntry{offset: nextS + e.cur} - eLong := &e.bTable[nextHashL] - eLong.Cur, eLong.Prev = tableEntry{offset: nextS + e.cur}, eLong.Cur - - // Check the previous long candidate as well. - t2 := lCandidate.Prev.offset - e.cur - if s-t2 < maxMatchOffset && uint32(cv) == load3232(src, lCandidate.Prev.offset-e.cur) { - l = e.matchlen(s+4, t+4, src) + 4 - ml1 := e.matchlen(s+4, t2+4, src) + 4 - if ml1 > l { - t = t2 - l = ml1 - break - } - } - break - } - // Current value did not match, but check if previous long value does. - t = lCandidate.Prev.offset - e.cur - if s-t < maxMatchOffset && uint32(cv) == load3232(src, lCandidate.Prev.offset-e.cur) { - // Store the next match - e.table[nextHashS] = tableEntry{offset: nextS + e.cur} - eLong := &e.bTable[nextHashL] - eLong.Cur, eLong.Prev = tableEntry{offset: nextS + e.cur}, eLong.Cur - break - } - } - - t = sCandidate.offset - e.cur - if s-t < maxMatchOffset && uint32(cv) == load3232(src, sCandidate.offset-e.cur) { - // Found a 4 match... - l = e.matchlen(s+4, t+4, src) + 4 - - // Look up next long candidate (at nextS) - lCandidate = e.bTable[nextHashL] - - // Store the next match - e.table[nextHashS] = tableEntry{offset: nextS + e.cur} - eLong := &e.bTable[nextHashL] - eLong.Cur, eLong.Prev = tableEntry{offset: nextS + e.cur}, eLong.Cur - - // Check repeat at s + repOff - const repOff = 1 - t2 := s - repeat + repOff - if load3232(src, t2) == uint32(cv>>(8*repOff)) { - ml := e.matchlen(s+4+repOff, t2+4, src) + 4 - if ml > l { - t = t2 - l = ml - s += repOff - // Not worth checking more. - break - } - } - - // If the next long is a candidate, use that... - t2 = lCandidate.Cur.offset - e.cur - if nextS-t2 < maxMatchOffset { - if load3232(src, lCandidate.Cur.offset-e.cur) == uint32(next) { - ml := e.matchlen(nextS+4, t2+4, src) + 4 - if ml > l { - t = t2 - s = nextS - l = ml - // This is ok, but check previous as well. - } - } - // If the previous long is a candidate, use that... - t2 = lCandidate.Prev.offset - e.cur - if nextS-t2 < maxMatchOffset && load3232(src, lCandidate.Prev.offset-e.cur) == uint32(next) { - ml := e.matchlen(nextS+4, t2+4, src) + 4 - if ml > l { - t = t2 - s = nextS - l = ml - break - } - } - } - break - } - cv = next - } - - // A 4-byte match has been found. We'll later see if more than 4 bytes - // match. But, prior to the match, src[nextEmit:s] are unmatched. Emit - // them as literal bytes. - - // Extend the 4-byte match as long as possible. - if l == 0 { - l = e.matchlenLong(s+4, t+4, src) + 4 - } else if l == maxMatchLength { - l += e.matchlenLong(s+l, t+l, src) - } - - // Try to locate a better match by checking the end-of-match... - if sAt := s + l; sAt < sLimit { - // Allow some bytes at the beginning to mismatch. - // Sweet spot is 2/3 bytes depending on input. - // 3 is only a little better when it is but sometimes a lot worse. - // The skipped bytes are tested in Extend backwards, - // and still picked up as part of the match if they do. - const skipBeginning = 2 - eLong := &e.bTable[hash7(load6432(src, sAt), tableBits)] - // Test current - t2 := eLong.Cur.offset - e.cur - l + skipBeginning - s2 := s + skipBeginning - off := s2 - t2 - if off < maxMatchOffset { - if off > 0 && t2 >= 0 { - if l2 := e.matchlenLong(s2, t2, src); l2 > l { - t = t2 - l = l2 - s = s2 - } - } - // Test next: - t2 = eLong.Prev.offset - e.cur - l + skipBeginning - off := s2 - t2 - if off > 0 && off < maxMatchOffset && t2 >= 0 { - if l2 := e.matchlenLong(s2, t2, src); l2 > l { - t = t2 - l = l2 - s = s2 - } - } - } - } - - // Extend backwards - for t > 0 && s > nextEmit && src[t-1] == src[s-1] { - s-- - t-- - l++ - } - if nextEmit < s { - if false { - emitLiteral(dst, src[nextEmit:s]) - } else { - for _, v := range src[nextEmit:s] { - dst.tokens[dst.n] = token(v) - dst.litHist[v]++ - dst.n++ - } - } - } - if false { - if t >= s { - panic(fmt.Sprintln("s-t", s, t)) - } - if (s - t) > maxMatchOffset { - panic(fmt.Sprintln("mmo", s-t)) - } - if l < baseMatchLength { - panic("bml") - } - } - - dst.AddMatchLong(l, uint32(s-t-baseMatchOffset)) - repeat = s - t - s += l - nextEmit = s - if nextS >= s { - s = nextS + 1 - } - - if s >= sLimit { - // Index after match end. - for i := nextS + 1; i < int32(len(src))-8; i += 2 { - cv := load6432(src, i) - e.table[hashLen(cv, tableBits, hashShortBytes)] = tableEntry{offset: i + e.cur} - eLong := &e.bTable[hash7(cv, tableBits)] - eLong.Cur, eLong.Prev = tableEntry{offset: i + e.cur}, eLong.Cur - } - goto emitRemainder - } - - // Store every long hash in-between and every second short. - if true { - for i := nextS + 1; i < s-1; i += 2 { - cv := load6432(src, i) - t := tableEntry{offset: i + e.cur} - t2 := tableEntry{offset: t.offset + 1} - eLong := &e.bTable[hash7(cv, tableBits)] - eLong2 := &e.bTable[hash7(cv>>8, tableBits)] - e.table[hashLen(cv, tableBits, hashShortBytes)] = t - eLong.Cur, eLong.Prev = t, eLong.Cur - eLong2.Cur, eLong2.Prev = t2, eLong2.Cur - } - } - - // We could immediately start working at s now, but to improve - // compression we first update the hash table at s-1 and at s. - cv = load6432(src, s) - } - -emitRemainder: - if int(nextEmit) < len(src) { - // If nothing was added, don't encode literals. - if dst.n == 0 { - return - } - - emitLiteral(dst, src[nextEmit:]) - } -} diff --git a/vendor/github.com/klauspost/compress/flate/matchlen_amd64.go b/vendor/github.com/klauspost/compress/flate/matchlen_amd64.go deleted file mode 100644 index 4bd388584..000000000 --- a/vendor/github.com/klauspost/compress/flate/matchlen_amd64.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build amd64 && !appengine && !noasm && gc -// +build amd64,!appengine,!noasm,gc - -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. - -package flate - -// matchLen returns how many bytes match in a and b -// -// It assumes that: -// -// len(a) <= len(b) and len(a) > 0 -// -//go:noescape -func matchLen(a []byte, b []byte) int diff --git a/vendor/github.com/klauspost/compress/flate/matchlen_amd64.s b/vendor/github.com/klauspost/compress/flate/matchlen_amd64.s deleted file mode 100644 index 9a7655c0f..000000000 --- a/vendor/github.com/klauspost/compress/flate/matchlen_amd64.s +++ /dev/null @@ -1,68 +0,0 @@ -// Copied from S2 implementation. - -//go:build !appengine && !noasm && gc && !noasm - -#include "textflag.h" - -// func matchLen(a []byte, b []byte) int -// Requires: BMI -TEXT ·matchLen(SB), NOSPLIT, $0-56 - MOVQ a_base+0(FP), AX - MOVQ b_base+24(FP), CX - MOVQ a_len+8(FP), DX - - // matchLen - XORL SI, SI - CMPL DX, $0x08 - JB matchlen_match4_standalone - -matchlen_loopback_standalone: - MOVQ (AX)(SI*1), BX - XORQ (CX)(SI*1), BX - TESTQ BX, BX - JZ matchlen_loop_standalone - -#ifdef GOAMD64_v3 - TZCNTQ BX, BX -#else - BSFQ BX, BX -#endif - SARQ $0x03, BX - LEAL (SI)(BX*1), SI - JMP gen_match_len_end - -matchlen_loop_standalone: - LEAL -8(DX), DX - LEAL 8(SI), SI - CMPL DX, $0x08 - JAE matchlen_loopback_standalone - -matchlen_match4_standalone: - CMPL DX, $0x04 - JB matchlen_match2_standalone - MOVL (AX)(SI*1), BX - CMPL (CX)(SI*1), BX - JNE matchlen_match2_standalone - LEAL -4(DX), DX - LEAL 4(SI), SI - -matchlen_match2_standalone: - CMPL DX, $0x02 - JB matchlen_match1_standalone - MOVW (AX)(SI*1), BX - CMPW (CX)(SI*1), BX - JNE matchlen_match1_standalone - LEAL -2(DX), DX - LEAL 2(SI), SI - -matchlen_match1_standalone: - CMPL DX, $0x01 - JB gen_match_len_end - MOVB (AX)(SI*1), BL - CMPB (CX)(SI*1), BL - JNE gen_match_len_end - INCL SI - -gen_match_len_end: - MOVQ SI, ret+48(FP) - RET diff --git a/vendor/github.com/klauspost/compress/flate/matchlen_generic.go b/vendor/github.com/klauspost/compress/flate/matchlen_generic.go deleted file mode 100644 index ad5cd814b..000000000 --- a/vendor/github.com/klauspost/compress/flate/matchlen_generic.go +++ /dev/null @@ -1,33 +0,0 @@ -//go:build !amd64 || appengine || !gc || noasm -// +build !amd64 appengine !gc noasm - -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. - -package flate - -import ( - "encoding/binary" - "math/bits" -) - -// matchLen returns the maximum common prefix length of a and b. -// a must be the shortest of the two. -func matchLen(a, b []byte) (n int) { - for ; len(a) >= 8 && len(b) >= 8; a, b = a[8:], b[8:] { - diff := binary.LittleEndian.Uint64(a) ^ binary.LittleEndian.Uint64(b) - if diff != 0 { - return n + bits.TrailingZeros64(diff)>>3 - } - n += 8 - } - - for i := range a { - if a[i] != b[i] { - break - } - n++ - } - return n - -} diff --git a/vendor/github.com/klauspost/compress/flate/regmask_amd64.go b/vendor/github.com/klauspost/compress/flate/regmask_amd64.go deleted file mode 100644 index 6ed28061b..000000000 --- a/vendor/github.com/klauspost/compress/flate/regmask_amd64.go +++ /dev/null @@ -1,37 +0,0 @@ -package flate - -const ( - // Masks for shifts with register sizes of the shift value. - // This can be used to work around the x86 design of shifting by mod register size. - // It can be used when a variable shift is always smaller than the register size. - - // reg8SizeMaskX - shift value is 8 bits, shifted is X - reg8SizeMask8 = 7 - reg8SizeMask16 = 15 - reg8SizeMask32 = 31 - reg8SizeMask64 = 63 - - // reg16SizeMaskX - shift value is 16 bits, shifted is X - reg16SizeMask8 = reg8SizeMask8 - reg16SizeMask16 = reg8SizeMask16 - reg16SizeMask32 = reg8SizeMask32 - reg16SizeMask64 = reg8SizeMask64 - - // reg32SizeMaskX - shift value is 32 bits, shifted is X - reg32SizeMask8 = reg8SizeMask8 - reg32SizeMask16 = reg8SizeMask16 - reg32SizeMask32 = reg8SizeMask32 - reg32SizeMask64 = reg8SizeMask64 - - // reg64SizeMaskX - shift value is 64 bits, shifted is X - reg64SizeMask8 = reg8SizeMask8 - reg64SizeMask16 = reg8SizeMask16 - reg64SizeMask32 = reg8SizeMask32 - reg64SizeMask64 = reg8SizeMask64 - - // regSizeMaskUintX - shift value is uint, shifted is X - regSizeMaskUint8 = reg8SizeMask8 - regSizeMaskUint16 = reg8SizeMask16 - regSizeMaskUint32 = reg8SizeMask32 - regSizeMaskUint64 = reg8SizeMask64 -) diff --git a/vendor/github.com/klauspost/compress/flate/regmask_other.go b/vendor/github.com/klauspost/compress/flate/regmask_other.go deleted file mode 100644 index 1b7a2cbd7..000000000 --- a/vendor/github.com/klauspost/compress/flate/regmask_other.go +++ /dev/null @@ -1,40 +0,0 @@ -//go:build !amd64 -// +build !amd64 - -package flate - -const ( - // Masks for shifts with register sizes of the shift value. - // This can be used to work around the x86 design of shifting by mod register size. - // It can be used when a variable shift is always smaller than the register size. - - // reg8SizeMaskX - shift value is 8 bits, shifted is X - reg8SizeMask8 = 0xff - reg8SizeMask16 = 0xff - reg8SizeMask32 = 0xff - reg8SizeMask64 = 0xff - - // reg16SizeMaskX - shift value is 16 bits, shifted is X - reg16SizeMask8 = 0xffff - reg16SizeMask16 = 0xffff - reg16SizeMask32 = 0xffff - reg16SizeMask64 = 0xffff - - // reg32SizeMaskX - shift value is 32 bits, shifted is X - reg32SizeMask8 = 0xffffffff - reg32SizeMask16 = 0xffffffff - reg32SizeMask32 = 0xffffffff - reg32SizeMask64 = 0xffffffff - - // reg64SizeMaskX - shift value is 64 bits, shifted is X - reg64SizeMask8 = 0xffffffffffffffff - reg64SizeMask16 = 0xffffffffffffffff - reg64SizeMask32 = 0xffffffffffffffff - reg64SizeMask64 = 0xffffffffffffffff - - // regSizeMaskUintX - shift value is uint, shifted is X - regSizeMaskUint8 = ^uint(0) - regSizeMaskUint16 = ^uint(0) - regSizeMaskUint32 = ^uint(0) - regSizeMaskUint64 = ^uint(0) -) diff --git a/vendor/github.com/klauspost/compress/flate/stateless.go b/vendor/github.com/klauspost/compress/flate/stateless.go deleted file mode 100644 index f3d4139ef..000000000 --- a/vendor/github.com/klauspost/compress/flate/stateless.go +++ /dev/null @@ -1,318 +0,0 @@ -package flate - -import ( - "io" - "math" - "sync" -) - -const ( - maxStatelessBlock = math.MaxInt16 - // dictionary will be taken from maxStatelessBlock, so limit it. - maxStatelessDict = 8 << 10 - - slTableBits = 13 - slTableSize = 1 << slTableBits - slTableShift = 32 - slTableBits -) - -type statelessWriter struct { - dst io.Writer - closed bool -} - -func (s *statelessWriter) Close() error { - if s.closed { - return nil - } - s.closed = true - // Emit EOF block - return StatelessDeflate(s.dst, nil, true, nil) -} - -func (s *statelessWriter) Write(p []byte) (n int, err error) { - err = StatelessDeflate(s.dst, p, false, nil) - if err != nil { - return 0, err - } - return len(p), nil -} - -func (s *statelessWriter) Reset(w io.Writer) { - s.dst = w - s.closed = false -} - -// NewStatelessWriter will do compression but without maintaining any state -// between Write calls. -// There will be no memory kept between Write calls, -// but compression and speed will be suboptimal. -// Because of this, the size of actual Write calls will affect output size. -func NewStatelessWriter(dst io.Writer) io.WriteCloser { - return &statelessWriter{dst: dst} -} - -// bitWriterPool contains bit writers that can be reused. -var bitWriterPool = sync.Pool{ - New: func() interface{} { - return newHuffmanBitWriter(nil) - }, -} - -// StatelessDeflate allows compressing directly to a Writer without retaining state. -// When returning everything will be flushed. -// Up to 8KB of an optional dictionary can be given which is presumed to precede the block. -// Longer dictionaries will be truncated and will still produce valid output. -// Sending nil dictionary is perfectly fine. -func StatelessDeflate(out io.Writer, in []byte, eof bool, dict []byte) error { - var dst tokens - bw := bitWriterPool.Get().(*huffmanBitWriter) - bw.reset(out) - defer func() { - // don't keep a reference to our output - bw.reset(nil) - bitWriterPool.Put(bw) - }() - if eof && len(in) == 0 { - // Just write an EOF block. - // Could be faster... - bw.writeStoredHeader(0, true) - bw.flush() - return bw.err - } - - // Truncate dict - if len(dict) > maxStatelessDict { - dict = dict[len(dict)-maxStatelessDict:] - } - - // For subsequent loops, keep shallow dict reference to avoid alloc+copy. - var inDict []byte - - for len(in) > 0 { - todo := in - if len(inDict) > 0 { - if len(todo) > maxStatelessBlock-maxStatelessDict { - todo = todo[:maxStatelessBlock-maxStatelessDict] - } - } else if len(todo) > maxStatelessBlock-len(dict) { - todo = todo[:maxStatelessBlock-len(dict)] - } - inOrg := in - in = in[len(todo):] - uncompressed := todo - if len(dict) > 0 { - // combine dict and source - bufLen := len(todo) + len(dict) - combined := make([]byte, bufLen) - copy(combined, dict) - copy(combined[len(dict):], todo) - todo = combined - } - // Compress - if len(inDict) == 0 { - statelessEnc(&dst, todo, int16(len(dict))) - } else { - statelessEnc(&dst, inDict[:maxStatelessDict+len(todo)], maxStatelessDict) - } - isEof := eof && len(in) == 0 - - if dst.n == 0 { - bw.writeStoredHeader(len(uncompressed), isEof) - if bw.err != nil { - return bw.err - } - bw.writeBytes(uncompressed) - } else if int(dst.n) > len(uncompressed)-len(uncompressed)>>4 { - // If we removed less than 1/16th, huffman compress the block. - bw.writeBlockHuff(isEof, uncompressed, len(in) == 0) - } else { - bw.writeBlockDynamic(&dst, isEof, uncompressed, len(in) == 0) - } - if len(in) > 0 { - // Retain a dict if we have more - inDict = inOrg[len(uncompressed)-maxStatelessDict:] - dict = nil - dst.Reset() - } - if bw.err != nil { - return bw.err - } - } - if !eof { - // Align, only a stored block can do that. - bw.writeStoredHeader(0, false) - } - bw.flush() - return bw.err -} - -func hashSL(u uint32) uint32 { - return (u * 0x1e35a7bd) >> slTableShift -} - -func load3216(b []byte, i int16) uint32 { - // Help the compiler eliminate bounds checks on the read so it can be done in a single read. - b = b[i:] - b = b[:4] - return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 -} - -func load6416(b []byte, i int16) uint64 { - // Help the compiler eliminate bounds checks on the read so it can be done in a single read. - b = b[i:] - b = b[:8] - return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | - uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 -} - -func statelessEnc(dst *tokens, src []byte, startAt int16) { - const ( - inputMargin = 12 - 1 - minNonLiteralBlockSize = 1 + 1 + inputMargin - ) - - type tableEntry struct { - offset int16 - } - - var table [slTableSize]tableEntry - - // This check isn't in the Snappy implementation, but there, the caller - // instead of the callee handles this case. - if len(src)-int(startAt) < minNonLiteralBlockSize { - // We do not fill the token table. - // This will be picked up by caller. - dst.n = 0 - return - } - // Index until startAt - if startAt > 0 { - cv := load3232(src, 0) - for i := int16(0); i < startAt; i++ { - table[hashSL(cv)] = tableEntry{offset: i} - cv = (cv >> 8) | (uint32(src[i+4]) << 24) - } - } - - s := startAt + 1 - nextEmit := startAt - // sLimit is when to stop looking for offset/length copies. The inputMargin - // lets us use a fast path for emitLiteral in the main loop, while we are - // looking for copies. - sLimit := int16(len(src) - inputMargin) - - // nextEmit is where in src the next emitLiteral should start from. - cv := load3216(src, s) - - for { - const skipLog = 5 - const doEvery = 2 - - nextS := s - var candidate tableEntry - for { - nextHash := hashSL(cv) - candidate = table[nextHash] - nextS = s + doEvery + (s-nextEmit)>>skipLog - if nextS > sLimit || nextS <= 0 { - goto emitRemainder - } - - now := load6416(src, nextS) - table[nextHash] = tableEntry{offset: s} - nextHash = hashSL(uint32(now)) - - if cv == load3216(src, candidate.offset) { - table[nextHash] = tableEntry{offset: nextS} - break - } - - // Do one right away... - cv = uint32(now) - s = nextS - nextS++ - candidate = table[nextHash] - now >>= 8 - table[nextHash] = tableEntry{offset: s} - - if cv == load3216(src, candidate.offset) { - table[nextHash] = tableEntry{offset: nextS} - break - } - cv = uint32(now) - s = nextS - } - - // A 4-byte match has been found. We'll later see if more than 4 bytes - // match. But, prior to the match, src[nextEmit:s] are unmatched. Emit - // them as literal bytes. - for { - // Invariant: we have a 4-byte match at s, and no need to emit any - // literal bytes prior to s. - - // Extend the 4-byte match as long as possible. - t := candidate.offset - l := int16(matchLen(src[s+4:], src[t+4:]) + 4) - - // Extend backwards - for t > 0 && s > nextEmit && src[t-1] == src[s-1] { - s-- - t-- - l++ - } - if nextEmit < s { - if false { - emitLiteral(dst, src[nextEmit:s]) - } else { - for _, v := range src[nextEmit:s] { - dst.tokens[dst.n] = token(v) - dst.litHist[v]++ - dst.n++ - } - } - } - - // Save the match found - dst.AddMatchLong(int32(l), uint32(s-t-baseMatchOffset)) - s += l - nextEmit = s - if nextS >= s { - s = nextS + 1 - } - if s >= sLimit { - goto emitRemainder - } - - // We could immediately start working at s now, but to improve - // compression we first update the hash table at s-2 and at s. If - // another emitCopy is not our next move, also calculate nextHash - // at s+1. At least on GOARCH=amd64, these three hash calculations - // are faster as one load64 call (with some shifts) instead of - // three load32 calls. - x := load6416(src, s-2) - o := s - 2 - prevHash := hashSL(uint32(x)) - table[prevHash] = tableEntry{offset: o} - x >>= 16 - currHash := hashSL(uint32(x)) - candidate = table[currHash] - table[currHash] = tableEntry{offset: o + 2} - - if uint32(x) != load3216(src, candidate.offset) { - cv = uint32(x >> 8) - s++ - break - } - } - } - -emitRemainder: - if int(nextEmit) < len(src) { - // If nothing was added, don't encode literals. - if dst.n == 0 { - return - } - emitLiteral(dst, src[nextEmit:]) - } -} diff --git a/vendor/github.com/klauspost/compress/flate/token.go b/vendor/github.com/klauspost/compress/flate/token.go deleted file mode 100644 index d818790c1..000000000 --- a/vendor/github.com/klauspost/compress/flate/token.go +++ /dev/null @@ -1,379 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flate - -import ( - "bytes" - "encoding/binary" - "fmt" - "io" - "math" -) - -const ( - // bits 0-16 xoffset = offset - MIN_OFFSET_SIZE, or literal - 16 bits - // bits 16-22 offsetcode - 5 bits - // bits 22-30 xlength = length - MIN_MATCH_LENGTH - 8 bits - // bits 30-32 type 0 = literal 1=EOF 2=Match 3=Unused - 2 bits - lengthShift = 22 - offsetMask = 1<maxnumlit - offHist [32]uint16 // offset codes - litHist [256]uint16 // codes 0->255 - nFilled int - n uint16 // Must be able to contain maxStoreBlockSize - tokens [maxStoreBlockSize + 1]token -} - -func (t *tokens) Reset() { - if t.n == 0 { - return - } - t.n = 0 - t.nFilled = 0 - for i := range t.litHist[:] { - t.litHist[i] = 0 - } - for i := range t.extraHist[:] { - t.extraHist[i] = 0 - } - for i := range t.offHist[:] { - t.offHist[i] = 0 - } -} - -func (t *tokens) Fill() { - if t.n == 0 { - return - } - for i, v := range t.litHist[:] { - if v == 0 { - t.litHist[i] = 1 - t.nFilled++ - } - } - for i, v := range t.extraHist[:literalCount-256] { - if v == 0 { - t.nFilled++ - t.extraHist[i] = 1 - } - } - for i, v := range t.offHist[:offsetCodeCount] { - if v == 0 { - t.offHist[i] = 1 - } - } -} - -func indexTokens(in []token) tokens { - var t tokens - t.indexTokens(in) - return t -} - -func (t *tokens) indexTokens(in []token) { - t.Reset() - for _, tok := range in { - if tok < matchType { - t.AddLiteral(tok.literal()) - continue - } - t.AddMatch(uint32(tok.length()), tok.offset()&matchOffsetOnlyMask) - } -} - -// emitLiteral writes a literal chunk and returns the number of bytes written. -func emitLiteral(dst *tokens, lit []byte) { - for _, v := range lit { - dst.tokens[dst.n] = token(v) - dst.litHist[v]++ - dst.n++ - } -} - -func (t *tokens) AddLiteral(lit byte) { - t.tokens[t.n] = token(lit) - t.litHist[lit]++ - t.n++ -} - -// from https://stackoverflow.com/a/28730362 -func mFastLog2(val float32) float32 { - ux := int32(math.Float32bits(val)) - log2 := (float32)(((ux >> 23) & 255) - 128) - ux &= -0x7f800001 - ux += 127 << 23 - uval := math.Float32frombits(uint32(ux)) - log2 += ((-0.34484843)*uval+2.02466578)*uval - 0.67487759 - return log2 -} - -// EstimatedBits will return an minimum size estimated by an *optimal* -// compression of the block. -// The size of the block -func (t *tokens) EstimatedBits() int { - shannon := float32(0) - bits := int(0) - nMatches := 0 - total := int(t.n) + t.nFilled - if total > 0 { - invTotal := 1.0 / float32(total) - for _, v := range t.litHist[:] { - if v > 0 { - n := float32(v) - shannon += atLeastOne(-mFastLog2(n*invTotal)) * n - } - } - // Just add 15 for EOB - shannon += 15 - for i, v := range t.extraHist[1 : literalCount-256] { - if v > 0 { - n := float32(v) - shannon += atLeastOne(-mFastLog2(n*invTotal)) * n - bits += int(lengthExtraBits[i&31]) * int(v) - nMatches += int(v) - } - } - } - if nMatches > 0 { - invTotal := 1.0 / float32(nMatches) - for i, v := range t.offHist[:offsetCodeCount] { - if v > 0 { - n := float32(v) - shannon += atLeastOne(-mFastLog2(n*invTotal)) * n - bits += int(offsetExtraBits[i&31]) * int(v) - } - } - } - return int(shannon) + bits -} - -// AddMatch adds a match to the tokens. -// This function is very sensitive to inlining and right on the border. -func (t *tokens) AddMatch(xlength uint32, xoffset uint32) { - if debugDeflate { - if xlength >= maxMatchLength+baseMatchLength { - panic(fmt.Errorf("invalid length: %v", xlength)) - } - if xoffset >= maxMatchOffset+baseMatchOffset { - panic(fmt.Errorf("invalid offset: %v", xoffset)) - } - } - oCode := offsetCode(xoffset) - xoffset |= oCode << 16 - - t.extraHist[lengthCodes1[uint8(xlength)]]++ - t.offHist[oCode&31]++ - t.tokens[t.n] = token(matchType | xlength<= maxMatchOffset+baseMatchOffset { - panic(fmt.Errorf("invalid offset: %v", xoffset)) - } - } - oc := offsetCode(xoffset) - xoffset |= oc << 16 - for xlength > 0 { - xl := xlength - if xl > 258 { - // We need to have at least baseMatchLength left over for next loop. - if xl > 258+baseMatchLength { - xl = 258 - } else { - xl = 258 - baseMatchLength - } - } - xlength -= xl - xl -= baseMatchLength - t.extraHist[lengthCodes1[uint8(xl)]]++ - t.offHist[oc&31]++ - t.tokens[t.n] = token(matchType | uint32(xl)<> lengthShift) } - -// Convert length to code. -func lengthCode(len uint8) uint8 { return lengthCodes[len] } - -// Returns the offset code corresponding to a specific offset -func offsetCode(off uint32) uint32 { - if false { - if off < uint32(len(offsetCodes)) { - return offsetCodes[off&255] - } else if off>>7 < uint32(len(offsetCodes)) { - return offsetCodes[(off>>7)&255] + 14 - } else { - return offsetCodes[(off>>14)&255] + 28 - } - } - if off < uint32(len(offsetCodes)) { - return offsetCodes[uint8(off)] - } - return offsetCodes14[uint8(off>>7)] -} diff --git a/vendor/github.com/klauspost/compress/fse/README.md b/vendor/github.com/klauspost/compress/fse/README.md deleted file mode 100644 index ea7324da6..000000000 --- a/vendor/github.com/klauspost/compress/fse/README.md +++ /dev/null @@ -1,79 +0,0 @@ -# Finite State Entropy - -This package provides Finite State Entropy encoding and decoding. - -Finite State Entropy (also referenced as [tANS](https://en.wikipedia.org/wiki/Asymmetric_numeral_systems#tANS)) -encoding provides a fast near-optimal symbol encoding/decoding -for byte blocks as implemented in [zstandard](https://github.com/facebook/zstd). - -This can be used for compressing input with a lot of similar input values to the smallest number of bytes. -This does not perform any multi-byte [dictionary coding](https://en.wikipedia.org/wiki/Dictionary_coder) as LZ coders, -but it can be used as a secondary step to compressors (like Snappy) that does not do entropy encoding. - -* [Godoc documentation](https://godoc.org/github.com/klauspost/compress/fse) - -## News - - * Feb 2018: First implementation released. Consider this beta software for now. - -# Usage - -This package provides a low level interface that allows to compress single independent blocks. - -Each block is separate, and there is no built in integrity checks. -This means that the caller should keep track of block sizes and also do checksums if needed. - -Compressing a block is done via the [`Compress`](https://godoc.org/github.com/klauspost/compress/fse#Compress) function. -You must provide input and will receive the output and maybe an error. - -These error values can be returned: - -| Error | Description | -|---------------------|-----------------------------------------------------------------------------| -| `` | Everything ok, output is returned | -| `ErrIncompressible` | Returned when input is judged to be too hard to compress | -| `ErrUseRLE` | Returned from the compressor when the input is a single byte value repeated | -| `(error)` | An internal error occurred. | - -As can be seen above there are errors that will be returned even under normal operation so it is important to handle these. - -To reduce allocations you can provide a [`Scratch`](https://godoc.org/github.com/klauspost/compress/fse#Scratch) object -that can be re-used for successive calls. Both compression and decompression accepts a `Scratch` object, and the same -object can be used for both. - -Be aware, that when re-using a `Scratch` object that the *output* buffer is also re-used, so if you are still using this -you must set the `Out` field in the scratch to nil. The same buffer is used for compression and decompression output. - -Decompressing is done by calling the [`Decompress`](https://godoc.org/github.com/klauspost/compress/fse#Decompress) function. -You must provide the output from the compression stage, at exactly the size you got back. If you receive an error back -your input was likely corrupted. - -It is important to note that a successful decoding does *not* mean your output matches your original input. -There are no integrity checks, so relying on errors from the decompressor does not assure your data is valid. - -For more detailed usage, see examples in the [godoc documentation](https://godoc.org/github.com/klauspost/compress/fse#pkg-examples). - -# Performance - -A lot of factors are affecting speed. Block sizes and compressibility of the material are primary factors. -All compression functions are currently only running on the calling goroutine so only one core will be used per block. - -The compressor is significantly faster if symbols are kept as small as possible. The highest byte value of the input -is used to reduce some of the processing, so if all your input is above byte value 64 for instance, it may be -beneficial to transpose all your input values down by 64. - -With moderate block sizes around 64k speed are typically 200MB/s per core for compression and -around 300MB/s decompression speed. - -The same hardware typically does Huffman (deflate) encoding at 125MB/s and decompression at 100MB/s. - -# Plans - -At one point, more internals will be exposed to facilitate more "expert" usage of the components. - -A streaming interface is also likely to be implemented. Likely compatible with [FSE stream format](https://github.com/Cyan4973/FiniteStateEntropy/blob/dev/programs/fileio.c#L261). - -# Contributing - -Contributions are always welcome. Be aware that adding public functions will require good justification and breaking -changes will likely not be accepted. If in doubt open an issue before writing the PR. \ No newline at end of file diff --git a/vendor/github.com/klauspost/compress/fse/bitreader.go b/vendor/github.com/klauspost/compress/fse/bitreader.go deleted file mode 100644 index f65eb3909..000000000 --- a/vendor/github.com/klauspost/compress/fse/bitreader.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2018 Klaus Post. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. - -package fse - -import ( - "encoding/binary" - "errors" - "io" -) - -// bitReader reads a bitstream in reverse. -// The last set bit indicates the start of the stream and is used -// for aligning the input. -type bitReader struct { - in []byte - off uint // next byte to read is at in[off - 1] - value uint64 - bitsRead uint8 -} - -// init initializes and resets the bit reader. -func (b *bitReader) init(in []byte) error { - if len(in) < 1 { - return errors.New("corrupt stream: too short") - } - b.in = in - b.off = uint(len(in)) - // The highest bit of the last byte indicates where to start - v := in[len(in)-1] - if v == 0 { - return errors.New("corrupt stream, did not find end of stream") - } - b.bitsRead = 64 - b.value = 0 - if len(in) >= 8 { - b.fillFastStart() - } else { - b.fill() - b.fill() - } - b.bitsRead += 8 - uint8(highBits(uint32(v))) - return nil -} - -// getBits will return n bits. n can be 0. -func (b *bitReader) getBits(n uint8) uint16 { - if n == 0 || b.bitsRead >= 64 { - return 0 - } - return b.getBitsFast(n) -} - -// getBitsFast requires that at least one bit is requested every time. -// There are no checks if the buffer is filled. -func (b *bitReader) getBitsFast(n uint8) uint16 { - const regMask = 64 - 1 - v := uint16((b.value << (b.bitsRead & regMask)) >> ((regMask + 1 - n) & regMask)) - b.bitsRead += n - return v -} - -// fillFast() will make sure at least 32 bits are available. -// There must be at least 4 bytes available. -func (b *bitReader) fillFast() { - if b.bitsRead < 32 { - return - } - // 2 bounds checks. - v := b.in[b.off-4:] - v = v[:4] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - b.value = (b.value << 32) | uint64(low) - b.bitsRead -= 32 - b.off -= 4 -} - -// fill() will make sure at least 32 bits are available. -func (b *bitReader) fill() { - if b.bitsRead < 32 { - return - } - if b.off > 4 { - v := b.in[b.off-4:] - v = v[:4] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - b.value = (b.value << 32) | uint64(low) - b.bitsRead -= 32 - b.off -= 4 - return - } - for b.off > 0 { - b.value = (b.value << 8) | uint64(b.in[b.off-1]) - b.bitsRead -= 8 - b.off-- - } -} - -// fillFastStart() assumes the bitreader is empty and there is at least 8 bytes to read. -func (b *bitReader) fillFastStart() { - // Do single re-slice to avoid bounds checks. - b.value = binary.LittleEndian.Uint64(b.in[b.off-8:]) - b.bitsRead = 0 - b.off -= 8 -} - -// finished returns true if all bits have been read from the bit stream. -func (b *bitReader) finished() bool { - return b.bitsRead >= 64 && b.off == 0 -} - -// close the bitstream and returns an error if out-of-buffer reads occurred. -func (b *bitReader) close() error { - // Release reference. - b.in = nil - if b.bitsRead > 64 { - return io.ErrUnexpectedEOF - } - return nil -} diff --git a/vendor/github.com/klauspost/compress/fse/bitwriter.go b/vendor/github.com/klauspost/compress/fse/bitwriter.go deleted file mode 100644 index e82fa3bb7..000000000 --- a/vendor/github.com/klauspost/compress/fse/bitwriter.go +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright 2018 Klaus Post. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. - -package fse - -import "fmt" - -// bitWriter will write bits. -// First bit will be LSB of the first byte of output. -type bitWriter struct { - bitContainer uint64 - nBits uint8 - out []byte -} - -// bitMask16 is bitmasks. Has extra to avoid bounds check. -var bitMask16 = [32]uint16{ - 0, 1, 3, 7, 0xF, 0x1F, - 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, - 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, 0xFFFF, - 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, - 0xFFFF, 0xFFFF} /* up to 16 bits */ - -// addBits16NC will add up to 16 bits. -// It will not check if there is space for them, -// so the caller must ensure that it has flushed recently. -func (b *bitWriter) addBits16NC(value uint16, bits uint8) { - b.bitContainer |= uint64(value&bitMask16[bits&31]) << (b.nBits & 63) - b.nBits += bits -} - -// addBits16Clean will add up to 16 bits. value may not contain more set bits than indicated. -// It will not check if there is space for them, so the caller must ensure that it has flushed recently. -func (b *bitWriter) addBits16Clean(value uint16, bits uint8) { - b.bitContainer |= uint64(value) << (b.nBits & 63) - b.nBits += bits -} - -// addBits16ZeroNC will add up to 16 bits. -// It will not check if there is space for them, -// so the caller must ensure that it has flushed recently. -// This is fastest if bits can be zero. -func (b *bitWriter) addBits16ZeroNC(value uint16, bits uint8) { - if bits == 0 { - return - } - value <<= (16 - bits) & 15 - value >>= (16 - bits) & 15 - b.bitContainer |= uint64(value) << (b.nBits & 63) - b.nBits += bits -} - -// flush will flush all pending full bytes. -// There will be at least 56 bits available for writing when this has been called. -// Using flush32 is faster, but leaves less space for writing. -func (b *bitWriter) flush() { - v := b.nBits >> 3 - switch v { - case 0: - case 1: - b.out = append(b.out, - byte(b.bitContainer), - ) - case 2: - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - ) - case 3: - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - byte(b.bitContainer>>16), - ) - case 4: - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - byte(b.bitContainer>>16), - byte(b.bitContainer>>24), - ) - case 5: - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - byte(b.bitContainer>>16), - byte(b.bitContainer>>24), - byte(b.bitContainer>>32), - ) - case 6: - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - byte(b.bitContainer>>16), - byte(b.bitContainer>>24), - byte(b.bitContainer>>32), - byte(b.bitContainer>>40), - ) - case 7: - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - byte(b.bitContainer>>16), - byte(b.bitContainer>>24), - byte(b.bitContainer>>32), - byte(b.bitContainer>>40), - byte(b.bitContainer>>48), - ) - case 8: - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - byte(b.bitContainer>>16), - byte(b.bitContainer>>24), - byte(b.bitContainer>>32), - byte(b.bitContainer>>40), - byte(b.bitContainer>>48), - byte(b.bitContainer>>56), - ) - default: - panic(fmt.Errorf("bits (%d) > 64", b.nBits)) - } - b.bitContainer >>= v << 3 - b.nBits &= 7 -} - -// flush32 will flush out, so there are at least 32 bits available for writing. -func (b *bitWriter) flush32() { - if b.nBits < 32 { - return - } - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - byte(b.bitContainer>>16), - byte(b.bitContainer>>24)) - b.nBits -= 32 - b.bitContainer >>= 32 -} - -// flushAlign will flush remaining full bytes and align to next byte boundary. -func (b *bitWriter) flushAlign() { - nbBytes := (b.nBits + 7) >> 3 - for i := uint8(0); i < nbBytes; i++ { - b.out = append(b.out, byte(b.bitContainer>>(i*8))) - } - b.nBits = 0 - b.bitContainer = 0 -} - -// close will write the alignment bit and write the final byte(s) -// to the output. -func (b *bitWriter) close() { - // End mark - b.addBits16Clean(1, 1) - // flush until next byte. - b.flushAlign() -} - -// reset and continue writing by appending to out. -func (b *bitWriter) reset(out []byte) { - b.bitContainer = 0 - b.nBits = 0 - b.out = out -} diff --git a/vendor/github.com/klauspost/compress/fse/bytereader.go b/vendor/github.com/klauspost/compress/fse/bytereader.go deleted file mode 100644 index abade2d60..000000000 --- a/vendor/github.com/klauspost/compress/fse/bytereader.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2018 Klaus Post. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. - -package fse - -// byteReader provides a byte reader that reads -// little endian values from a byte stream. -// The input stream is manually advanced. -// The reader performs no bounds checks. -type byteReader struct { - b []byte - off int -} - -// init will initialize the reader and set the input. -func (b *byteReader) init(in []byte) { - b.b = in - b.off = 0 -} - -// advance the stream b n bytes. -func (b *byteReader) advance(n uint) { - b.off += int(n) -} - -// Uint32 returns a little endian uint32 starting at current offset. -func (b byteReader) Uint32() uint32 { - b2 := b.b[b.off:] - b2 = b2[:4] - v3 := uint32(b2[3]) - v2 := uint32(b2[2]) - v1 := uint32(b2[1]) - v0 := uint32(b2[0]) - return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24) -} - -// unread returns the unread portion of the input. -func (b byteReader) unread() []byte { - return b.b[b.off:] -} - -// remain will return the number of bytes remaining. -func (b byteReader) remain() int { - return len(b.b) - b.off -} diff --git a/vendor/github.com/klauspost/compress/fse/compress.go b/vendor/github.com/klauspost/compress/fse/compress.go deleted file mode 100644 index 65d777357..000000000 --- a/vendor/github.com/klauspost/compress/fse/compress.go +++ /dev/null @@ -1,683 +0,0 @@ -// Copyright 2018 Klaus Post. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. - -package fse - -import ( - "errors" - "fmt" -) - -// Compress the input bytes. Input must be < 2GB. -// Provide a Scratch buffer to avoid memory allocations. -// Note that the output is also kept in the scratch buffer. -// If input is too hard to compress, ErrIncompressible is returned. -// If input is a single byte value repeated ErrUseRLE is returned. -func Compress(in []byte, s *Scratch) ([]byte, error) { - if len(in) <= 1 { - return nil, ErrIncompressible - } - if len(in) > (2<<30)-1 { - return nil, errors.New("input too big, must be < 2GB") - } - s, err := s.prepare(in) - if err != nil { - return nil, err - } - - // Create histogram, if none was provided. - maxCount := s.maxCount - if maxCount == 0 { - maxCount = s.countSimple(in) - } - // Reset for next run. - s.clearCount = true - s.maxCount = 0 - if maxCount == len(in) { - // One symbol, use RLE - return nil, ErrUseRLE - } - if maxCount == 1 || maxCount < (len(in)>>7) { - // Each symbol present maximum once or too well distributed. - return nil, ErrIncompressible - } - s.optimalTableLog() - err = s.normalizeCount() - if err != nil { - return nil, err - } - err = s.writeCount() - if err != nil { - return nil, err - } - - if false { - err = s.validateNorm() - if err != nil { - return nil, err - } - } - - err = s.buildCTable() - if err != nil { - return nil, err - } - err = s.compress(in) - if err != nil { - return nil, err - } - s.Out = s.bw.out - // Check if we compressed. - if len(s.Out) >= len(in) { - return nil, ErrIncompressible - } - return s.Out, nil -} - -// cState contains the compression state of a stream. -type cState struct { - bw *bitWriter - stateTable []uint16 - state uint16 -} - -// init will initialize the compression state to the first symbol of the stream. -func (c *cState) init(bw *bitWriter, ct *cTable, tableLog uint8, first symbolTransform) { - c.bw = bw - c.stateTable = ct.stateTable - - nbBitsOut := (first.deltaNbBits + (1 << 15)) >> 16 - im := int32((nbBitsOut << 16) - first.deltaNbBits) - lu := (im >> nbBitsOut) + first.deltaFindState - c.state = c.stateTable[lu] -} - -// encode the output symbol provided and write it to the bitstream. -func (c *cState) encode(symbolTT symbolTransform) { - nbBitsOut := (uint32(c.state) + symbolTT.deltaNbBits) >> 16 - dstState := int32(c.state>>(nbBitsOut&15)) + symbolTT.deltaFindState - c.bw.addBits16NC(c.state, uint8(nbBitsOut)) - c.state = c.stateTable[dstState] -} - -// encode the output symbol provided and write it to the bitstream. -func (c *cState) encodeZero(symbolTT symbolTransform) { - nbBitsOut := (uint32(c.state) + symbolTT.deltaNbBits) >> 16 - dstState := int32(c.state>>(nbBitsOut&15)) + symbolTT.deltaFindState - c.bw.addBits16ZeroNC(c.state, uint8(nbBitsOut)) - c.state = c.stateTable[dstState] -} - -// flush will write the tablelog to the output and flush the remaining full bytes. -func (c *cState) flush(tableLog uint8) { - c.bw.flush32() - c.bw.addBits16NC(c.state, tableLog) - c.bw.flush() -} - -// compress is the main compression loop that will encode the input from the last byte to the first. -func (s *Scratch) compress(src []byte) error { - if len(src) <= 2 { - return errors.New("compress: src too small") - } - tt := s.ct.symbolTT[:256] - s.bw.reset(s.Out) - - // Our two states each encodes every second byte. - // Last byte encoded (first byte decoded) will always be encoded by c1. - var c1, c2 cState - - // Encode so remaining size is divisible by 4. - ip := len(src) - if ip&1 == 1 { - c1.init(&s.bw, &s.ct, s.actualTableLog, tt[src[ip-1]]) - c2.init(&s.bw, &s.ct, s.actualTableLog, tt[src[ip-2]]) - c1.encodeZero(tt[src[ip-3]]) - ip -= 3 - } else { - c2.init(&s.bw, &s.ct, s.actualTableLog, tt[src[ip-1]]) - c1.init(&s.bw, &s.ct, s.actualTableLog, tt[src[ip-2]]) - ip -= 2 - } - if ip&2 != 0 { - c2.encodeZero(tt[src[ip-1]]) - c1.encodeZero(tt[src[ip-2]]) - ip -= 2 - } - src = src[:ip] - - // Main compression loop. - switch { - case !s.zeroBits && s.actualTableLog <= 8: - // We can encode 4 symbols without requiring a flush. - // We do not need to check if any output is 0 bits. - for ; len(src) >= 4; src = src[:len(src)-4] { - s.bw.flush32() - v3, v2, v1, v0 := src[len(src)-4], src[len(src)-3], src[len(src)-2], src[len(src)-1] - c2.encode(tt[v0]) - c1.encode(tt[v1]) - c2.encode(tt[v2]) - c1.encode(tt[v3]) - } - case !s.zeroBits: - // We do not need to check if any output is 0 bits. - for ; len(src) >= 4; src = src[:len(src)-4] { - s.bw.flush32() - v3, v2, v1, v0 := src[len(src)-4], src[len(src)-3], src[len(src)-2], src[len(src)-1] - c2.encode(tt[v0]) - c1.encode(tt[v1]) - s.bw.flush32() - c2.encode(tt[v2]) - c1.encode(tt[v3]) - } - case s.actualTableLog <= 8: - // We can encode 4 symbols without requiring a flush - for ; len(src) >= 4; src = src[:len(src)-4] { - s.bw.flush32() - v3, v2, v1, v0 := src[len(src)-4], src[len(src)-3], src[len(src)-2], src[len(src)-1] - c2.encodeZero(tt[v0]) - c1.encodeZero(tt[v1]) - c2.encodeZero(tt[v2]) - c1.encodeZero(tt[v3]) - } - default: - for ; len(src) >= 4; src = src[:len(src)-4] { - s.bw.flush32() - v3, v2, v1, v0 := src[len(src)-4], src[len(src)-3], src[len(src)-2], src[len(src)-1] - c2.encodeZero(tt[v0]) - c1.encodeZero(tt[v1]) - s.bw.flush32() - c2.encodeZero(tt[v2]) - c1.encodeZero(tt[v3]) - } - } - - // Flush final state. - // Used to initialize state when decoding. - c2.flush(s.actualTableLog) - c1.flush(s.actualTableLog) - - s.bw.close() - return nil -} - -// writeCount will write the normalized histogram count to header. -// This is read back by readNCount. -func (s *Scratch) writeCount() error { - var ( - tableLog = s.actualTableLog - tableSize = 1 << tableLog - previous0 bool - charnum uint16 - - maxHeaderSize = ((int(s.symbolLen) * int(tableLog)) >> 3) + 3 - - // Write Table Size - bitStream = uint32(tableLog - minTablelog) - bitCount = uint(4) - remaining = int16(tableSize + 1) /* +1 for extra accuracy */ - threshold = int16(tableSize) - nbBits = uint(tableLog + 1) - ) - if cap(s.Out) < maxHeaderSize { - s.Out = make([]byte, 0, s.br.remain()+maxHeaderSize) - } - outP := uint(0) - out := s.Out[:maxHeaderSize] - - // stops at 1 - for remaining > 1 { - if previous0 { - start := charnum - for s.norm[charnum] == 0 { - charnum++ - } - for charnum >= start+24 { - start += 24 - bitStream += uint32(0xFFFF) << bitCount - out[outP] = byte(bitStream) - out[outP+1] = byte(bitStream >> 8) - outP += 2 - bitStream >>= 16 - } - for charnum >= start+3 { - start += 3 - bitStream += 3 << bitCount - bitCount += 2 - } - bitStream += uint32(charnum-start) << bitCount - bitCount += 2 - if bitCount > 16 { - out[outP] = byte(bitStream) - out[outP+1] = byte(bitStream >> 8) - outP += 2 - bitStream >>= 16 - bitCount -= 16 - } - } - - count := s.norm[charnum] - charnum++ - max := (2*threshold - 1) - remaining - if count < 0 { - remaining += count - } else { - remaining -= count - } - count++ // +1 for extra accuracy - if count >= threshold { - count += max // [0..max[ [max..threshold[ (...) [threshold+max 2*threshold[ - } - bitStream += uint32(count) << bitCount - bitCount += nbBits - if count < max { - bitCount-- - } - - previous0 = count == 1 - if remaining < 1 { - return errors.New("internal error: remaining<1") - } - for remaining < threshold { - nbBits-- - threshold >>= 1 - } - - if bitCount > 16 { - out[outP] = byte(bitStream) - out[outP+1] = byte(bitStream >> 8) - outP += 2 - bitStream >>= 16 - bitCount -= 16 - } - } - - out[outP] = byte(bitStream) - out[outP+1] = byte(bitStream >> 8) - outP += (bitCount + 7) / 8 - - if charnum > s.symbolLen { - return errors.New("internal error: charnum > s.symbolLen") - } - s.Out = out[:outP] - return nil -} - -// symbolTransform contains the state transform for a symbol. -type symbolTransform struct { - deltaFindState int32 - deltaNbBits uint32 -} - -// String prints values as a human readable string. -func (s symbolTransform) String() string { - return fmt.Sprintf("dnbits: %08x, fs:%d", s.deltaNbBits, s.deltaFindState) -} - -// cTable contains tables used for compression. -type cTable struct { - tableSymbol []byte - stateTable []uint16 - symbolTT []symbolTransform -} - -// allocCtable will allocate tables needed for compression. -// If existing tables a re big enough, they are simply re-used. -func (s *Scratch) allocCtable() { - tableSize := 1 << s.actualTableLog - // get tableSymbol that is big enough. - if cap(s.ct.tableSymbol) < tableSize { - s.ct.tableSymbol = make([]byte, tableSize) - } - s.ct.tableSymbol = s.ct.tableSymbol[:tableSize] - - ctSize := tableSize - if cap(s.ct.stateTable) < ctSize { - s.ct.stateTable = make([]uint16, ctSize) - } - s.ct.stateTable = s.ct.stateTable[:ctSize] - - if cap(s.ct.symbolTT) < 256 { - s.ct.symbolTT = make([]symbolTransform, 256) - } - s.ct.symbolTT = s.ct.symbolTT[:256] -} - -// buildCTable will populate the compression table so it is ready to be used. -func (s *Scratch) buildCTable() error { - tableSize := uint32(1 << s.actualTableLog) - highThreshold := tableSize - 1 - var cumul [maxSymbolValue + 2]int16 - - s.allocCtable() - tableSymbol := s.ct.tableSymbol[:tableSize] - // symbol start positions - { - cumul[0] = 0 - for ui, v := range s.norm[:s.symbolLen-1] { - u := byte(ui) // one less than reference - if v == -1 { - // Low proba symbol - cumul[u+1] = cumul[u] + 1 - tableSymbol[highThreshold] = u - highThreshold-- - } else { - cumul[u+1] = cumul[u] + v - } - } - // Encode last symbol separately to avoid overflowing u - u := int(s.symbolLen - 1) - v := s.norm[s.symbolLen-1] - if v == -1 { - // Low proba symbol - cumul[u+1] = cumul[u] + 1 - tableSymbol[highThreshold] = byte(u) - highThreshold-- - } else { - cumul[u+1] = cumul[u] + v - } - if uint32(cumul[s.symbolLen]) != tableSize { - return fmt.Errorf("internal error: expected cumul[s.symbolLen] (%d) == tableSize (%d)", cumul[s.symbolLen], tableSize) - } - cumul[s.symbolLen] = int16(tableSize) + 1 - } - // Spread symbols - s.zeroBits = false - { - step := tableStep(tableSize) - tableMask := tableSize - 1 - var position uint32 - // if any symbol > largeLimit, we may have 0 bits output. - largeLimit := int16(1 << (s.actualTableLog - 1)) - for ui, v := range s.norm[:s.symbolLen] { - symbol := byte(ui) - if v > largeLimit { - s.zeroBits = true - } - for nbOccurrences := int16(0); nbOccurrences < v; nbOccurrences++ { - tableSymbol[position] = symbol - position = (position + step) & tableMask - for position > highThreshold { - position = (position + step) & tableMask - } /* Low proba area */ - } - } - - // Check if we have gone through all positions - if position != 0 { - return errors.New("position!=0") - } - } - - // Build table - table := s.ct.stateTable - { - tsi := int(tableSize) - for u, v := range tableSymbol { - // TableU16 : sorted by symbol order; gives next state value - table[cumul[v]] = uint16(tsi + u) - cumul[v]++ - } - } - - // Build Symbol Transformation Table - { - total := int16(0) - symbolTT := s.ct.symbolTT[:s.symbolLen] - tableLog := s.actualTableLog - tl := (uint32(tableLog) << 16) - (1 << tableLog) - for i, v := range s.norm[:s.symbolLen] { - switch v { - case 0: - case -1, 1: - symbolTT[i].deltaNbBits = tl - symbolTT[i].deltaFindState = int32(total - 1) - total++ - default: - maxBitsOut := uint32(tableLog) - highBits(uint32(v-1)) - minStatePlus := uint32(v) << maxBitsOut - symbolTT[i].deltaNbBits = (maxBitsOut << 16) - minStatePlus - symbolTT[i].deltaFindState = int32(total - v) - total += v - } - } - if total != int16(tableSize) { - return fmt.Errorf("total mismatch %d (got) != %d (want)", total, tableSize) - } - } - return nil -} - -// countSimple will create a simple histogram in s.count. -// Returns the biggest count. -// Does not update s.clearCount. -func (s *Scratch) countSimple(in []byte) (max int) { - for _, v := range in { - s.count[v]++ - } - m, symlen := uint32(0), s.symbolLen - for i, v := range s.count[:] { - if v == 0 { - continue - } - if v > m { - m = v - } - symlen = uint16(i) + 1 - } - s.symbolLen = symlen - return int(m) -} - -// minTableLog provides the minimum logSize to safely represent a distribution. -func (s *Scratch) minTableLog() uint8 { - minBitsSrc := highBits(uint32(s.br.remain()-1)) + 1 - minBitsSymbols := highBits(uint32(s.symbolLen-1)) + 2 - if minBitsSrc < minBitsSymbols { - return uint8(minBitsSrc) - } - return uint8(minBitsSymbols) -} - -// optimalTableLog calculates and sets the optimal tableLog in s.actualTableLog -func (s *Scratch) optimalTableLog() { - tableLog := s.TableLog - minBits := s.minTableLog() - maxBitsSrc := uint8(highBits(uint32(s.br.remain()-1))) - 2 - if maxBitsSrc < tableLog { - // Accuracy can be reduced - tableLog = maxBitsSrc - } - if minBits > tableLog { - tableLog = minBits - } - // Need a minimum to safely represent all symbol values - if tableLog < minTablelog { - tableLog = minTablelog - } - if tableLog > maxTableLog { - tableLog = maxTableLog - } - s.actualTableLog = tableLog -} - -var rtbTable = [...]uint32{0, 473195, 504333, 520860, 550000, 700000, 750000, 830000} - -// normalizeCount will normalize the count of the symbols so -// the total is equal to the table size. -func (s *Scratch) normalizeCount() error { - var ( - tableLog = s.actualTableLog - scale = 62 - uint64(tableLog) - step = (1 << 62) / uint64(s.br.remain()) - vStep = uint64(1) << (scale - 20) - stillToDistribute = int16(1 << tableLog) - largest int - largestP int16 - lowThreshold = (uint32)(s.br.remain() >> tableLog) - ) - - for i, cnt := range s.count[:s.symbolLen] { - // already handled - // if (count[s] == s.length) return 0; /* rle special case */ - - if cnt == 0 { - s.norm[i] = 0 - continue - } - if cnt <= lowThreshold { - s.norm[i] = -1 - stillToDistribute-- - } else { - proba := (int16)((uint64(cnt) * step) >> scale) - if proba < 8 { - restToBeat := vStep * uint64(rtbTable[proba]) - v := uint64(cnt)*step - (uint64(proba) << scale) - if v > restToBeat { - proba++ - } - } - if proba > largestP { - largestP = proba - largest = i - } - s.norm[i] = proba - stillToDistribute -= proba - } - } - - if -stillToDistribute >= (s.norm[largest] >> 1) { - // corner case, need another normalization method - return s.normalizeCount2() - } - s.norm[largest] += stillToDistribute - return nil -} - -// Secondary normalization method. -// To be used when primary method fails. -func (s *Scratch) normalizeCount2() error { - const notYetAssigned = -2 - var ( - distributed uint32 - total = uint32(s.br.remain()) - tableLog = s.actualTableLog - lowThreshold = total >> tableLog - lowOne = (total * 3) >> (tableLog + 1) - ) - for i, cnt := range s.count[:s.symbolLen] { - if cnt == 0 { - s.norm[i] = 0 - continue - } - if cnt <= lowThreshold { - s.norm[i] = -1 - distributed++ - total -= cnt - continue - } - if cnt <= lowOne { - s.norm[i] = 1 - distributed++ - total -= cnt - continue - } - s.norm[i] = notYetAssigned - } - toDistribute := (1 << tableLog) - distributed - - if (total / toDistribute) > lowOne { - // risk of rounding to zero - lowOne = (total * 3) / (toDistribute * 2) - for i, cnt := range s.count[:s.symbolLen] { - if (s.norm[i] == notYetAssigned) && (cnt <= lowOne) { - s.norm[i] = 1 - distributed++ - total -= cnt - continue - } - } - toDistribute = (1 << tableLog) - distributed - } - if distributed == uint32(s.symbolLen)+1 { - // all values are pretty poor; - // probably incompressible data (should have already been detected); - // find max, then give all remaining points to max - var maxV int - var maxC uint32 - for i, cnt := range s.count[:s.symbolLen] { - if cnt > maxC { - maxV = i - maxC = cnt - } - } - s.norm[maxV] += int16(toDistribute) - return nil - } - - if total == 0 { - // all of the symbols were low enough for the lowOne or lowThreshold - for i := uint32(0); toDistribute > 0; i = (i + 1) % (uint32(s.symbolLen)) { - if s.norm[i] > 0 { - toDistribute-- - s.norm[i]++ - } - } - return nil - } - - var ( - vStepLog = 62 - uint64(tableLog) - mid = uint64((1 << (vStepLog - 1)) - 1) - rStep = (((1 << vStepLog) * uint64(toDistribute)) + mid) / uint64(total) // scale on remaining - tmpTotal = mid - ) - for i, cnt := range s.count[:s.symbolLen] { - if s.norm[i] == notYetAssigned { - var ( - end = tmpTotal + uint64(cnt)*rStep - sStart = uint32(tmpTotal >> vStepLog) - sEnd = uint32(end >> vStepLog) - weight = sEnd - sStart - ) - if weight < 1 { - return errors.New("weight < 1") - } - s.norm[i] = int16(weight) - tmpTotal = end - } - } - return nil -} - -// validateNorm validates the normalized histogram table. -func (s *Scratch) validateNorm() (err error) { - var total int - for _, v := range s.norm[:s.symbolLen] { - if v >= 0 { - total += int(v) - } else { - total -= int(v) - } - } - defer func() { - if err == nil { - return - } - fmt.Printf("selected TableLog: %d, Symbol length: %d\n", s.actualTableLog, s.symbolLen) - for i, v := range s.norm[:s.symbolLen] { - fmt.Printf("%3d: %5d -> %4d \n", i, s.count[i], v) - } - }() - if total != (1 << s.actualTableLog) { - return fmt.Errorf("warning: Total == %d != %d", total, 1< tablelogAbsoluteMax { - return errors.New("tableLog too large") - } - bitStream >>= 4 - bitCount := uint(4) - - s.actualTableLog = uint8(nbBits) - remaining := int32((1 << nbBits) + 1) - threshold := int32(1 << nbBits) - gotTotal := int32(0) - nbBits++ - - for remaining > 1 { - if previous0 { - n0 := charnum - for (bitStream & 0xFFFF) == 0xFFFF { - n0 += 24 - if b.off < iend-5 { - b.advance(2) - bitStream = b.Uint32() >> bitCount - } else { - bitStream >>= 16 - bitCount += 16 - } - } - for (bitStream & 3) == 3 { - n0 += 3 - bitStream >>= 2 - bitCount += 2 - } - n0 += uint16(bitStream & 3) - bitCount += 2 - if n0 > maxSymbolValue { - return errors.New("maxSymbolValue too small") - } - for charnum < n0 { - s.norm[charnum&0xff] = 0 - charnum++ - } - - if b.off <= iend-7 || b.off+int(bitCount>>3) <= iend-4 { - b.advance(bitCount >> 3) - bitCount &= 7 - bitStream = b.Uint32() >> bitCount - } else { - bitStream >>= 2 - } - } - - max := (2*(threshold) - 1) - (remaining) - var count int32 - - if (int32(bitStream) & (threshold - 1)) < max { - count = int32(bitStream) & (threshold - 1) - bitCount += nbBits - 1 - } else { - count = int32(bitStream) & (2*threshold - 1) - if count >= threshold { - count -= max - } - bitCount += nbBits - } - - count-- // extra accuracy - if count < 0 { - // -1 means +1 - remaining += count - gotTotal -= count - } else { - remaining -= count - gotTotal += count - } - s.norm[charnum&0xff] = int16(count) - charnum++ - previous0 = count == 0 - for remaining < threshold { - nbBits-- - threshold >>= 1 - } - if b.off <= iend-7 || b.off+int(bitCount>>3) <= iend-4 { - b.advance(bitCount >> 3) - bitCount &= 7 - } else { - bitCount -= (uint)(8 * (len(b.b) - 4 - b.off)) - b.off = len(b.b) - 4 - } - bitStream = b.Uint32() >> (bitCount & 31) - } - s.symbolLen = charnum - - if s.symbolLen <= 1 { - return fmt.Errorf("symbolLen (%d) too small", s.symbolLen) - } - if s.symbolLen > maxSymbolValue+1 { - return fmt.Errorf("symbolLen (%d) too big", s.symbolLen) - } - if remaining != 1 { - return fmt.Errorf("corruption detected (remaining %d != 1)", remaining) - } - if bitCount > 32 { - return fmt.Errorf("corruption detected (bitCount %d > 32)", bitCount) - } - if gotTotal != 1<> 3) - return nil -} - -// decSymbol contains information about a state entry, -// Including the state offset base, the output symbol and -// the number of bits to read for the low part of the destination state. -type decSymbol struct { - newState uint16 - symbol uint8 - nbBits uint8 -} - -// allocDtable will allocate decoding tables if they are not big enough. -func (s *Scratch) allocDtable() { - tableSize := 1 << s.actualTableLog - if cap(s.decTable) < tableSize { - s.decTable = make([]decSymbol, tableSize) - } - s.decTable = s.decTable[:tableSize] - - if cap(s.ct.tableSymbol) < 256 { - s.ct.tableSymbol = make([]byte, 256) - } - s.ct.tableSymbol = s.ct.tableSymbol[:256] - - if cap(s.ct.stateTable) < 256 { - s.ct.stateTable = make([]uint16, 256) - } - s.ct.stateTable = s.ct.stateTable[:256] -} - -// buildDtable will build the decoding table. -func (s *Scratch) buildDtable() error { - tableSize := uint32(1 << s.actualTableLog) - highThreshold := tableSize - 1 - s.allocDtable() - symbolNext := s.ct.stateTable[:256] - - // Init, lay down lowprob symbols - s.zeroBits = false - { - largeLimit := int16(1 << (s.actualTableLog - 1)) - for i, v := range s.norm[:s.symbolLen] { - if v == -1 { - s.decTable[highThreshold].symbol = uint8(i) - highThreshold-- - symbolNext[i] = 1 - } else { - if v >= largeLimit { - s.zeroBits = true - } - symbolNext[i] = uint16(v) - } - } - } - // Spread symbols - { - tableMask := tableSize - 1 - step := tableStep(tableSize) - position := uint32(0) - for ss, v := range s.norm[:s.symbolLen] { - for i := 0; i < int(v); i++ { - s.decTable[position].symbol = uint8(ss) - position = (position + step) & tableMask - for position > highThreshold { - // lowprob area - position = (position + step) & tableMask - } - } - } - if position != 0 { - // position must reach all cells once, otherwise normalizedCounter is incorrect - return errors.New("corrupted input (position != 0)") - } - } - - // Build Decoding table - { - tableSize := uint16(1 << s.actualTableLog) - for u, v := range s.decTable { - symbol := v.symbol - nextState := symbolNext[symbol] - symbolNext[symbol] = nextState + 1 - nBits := s.actualTableLog - byte(highBits(uint32(nextState))) - s.decTable[u].nbBits = nBits - newState := (nextState << nBits) - tableSize - if newState >= tableSize { - return fmt.Errorf("newState (%d) outside table size (%d)", newState, tableSize) - } - if newState == uint16(u) && nBits == 0 { - // Seems weird that this is possible with nbits > 0. - return fmt.Errorf("newState (%d) == oldState (%d) and no bits", newState, u) - } - s.decTable[u].newState = newState - } - } - return nil -} - -// decompress will decompress the bitstream. -// If the buffer is over-read an error is returned. -func (s *Scratch) decompress() error { - br := &s.bits - if err := br.init(s.br.unread()); err != nil { - return err - } - - var s1, s2 decoder - // Initialize and decode first state and symbol. - s1.init(br, s.decTable, s.actualTableLog) - s2.init(br, s.decTable, s.actualTableLog) - - // Use temp table to avoid bound checks/append penalty. - var tmp = s.ct.tableSymbol[:256] - var off uint8 - - // Main part - if !s.zeroBits { - for br.off >= 8 { - br.fillFast() - tmp[off+0] = s1.nextFast() - tmp[off+1] = s2.nextFast() - br.fillFast() - tmp[off+2] = s1.nextFast() - tmp[off+3] = s2.nextFast() - off += 4 - // When off is 0, we have overflowed and should write. - if off == 0 { - s.Out = append(s.Out, tmp...) - if len(s.Out) >= s.DecompressLimit { - return fmt.Errorf("output size (%d) > DecompressLimit (%d)", len(s.Out), s.DecompressLimit) - } - } - } - } else { - for br.off >= 8 { - br.fillFast() - tmp[off+0] = s1.next() - tmp[off+1] = s2.next() - br.fillFast() - tmp[off+2] = s1.next() - tmp[off+3] = s2.next() - off += 4 - if off == 0 { - s.Out = append(s.Out, tmp...) - // When off is 0, we have overflowed and should write. - if len(s.Out) >= s.DecompressLimit { - return fmt.Errorf("output size (%d) > DecompressLimit (%d)", len(s.Out), s.DecompressLimit) - } - } - } - } - s.Out = append(s.Out, tmp[:off]...) - - // Final bits, a bit more expensive check - for { - if s1.finished() { - s.Out = append(s.Out, s1.final(), s2.final()) - break - } - br.fill() - s.Out = append(s.Out, s1.next()) - if s2.finished() { - s.Out = append(s.Out, s2.final(), s1.final()) - break - } - s.Out = append(s.Out, s2.next()) - if len(s.Out) >= s.DecompressLimit { - return fmt.Errorf("output size (%d) > DecompressLimit (%d)", len(s.Out), s.DecompressLimit) - } - } - return br.close() -} - -// decoder keeps track of the current state and updates it from the bitstream. -type decoder struct { - state uint16 - br *bitReader - dt []decSymbol -} - -// init will initialize the decoder and read the first state from the stream. -func (d *decoder) init(in *bitReader, dt []decSymbol, tableLog uint8) { - d.dt = dt - d.br = in - d.state = in.getBits(tableLog) -} - -// next returns the next symbol and sets the next state. -// At least tablelog bits must be available in the bit reader. -func (d *decoder) next() uint8 { - n := &d.dt[d.state] - lowBits := d.br.getBits(n.nbBits) - d.state = n.newState + lowBits - return n.symbol -} - -// finished returns true if all bits have been read from the bitstream -// and the next state would require reading bits from the input. -func (d *decoder) finished() bool { - return d.br.finished() && d.dt[d.state].nbBits > 0 -} - -// final returns the current state symbol without decoding the next. -func (d *decoder) final() uint8 { - return d.dt[d.state].symbol -} - -// nextFast returns the next symbol and sets the next state. -// This can only be used if no symbols are 0 bits. -// At least tablelog bits must be available in the bit reader. -func (d *decoder) nextFast() uint8 { - n := d.dt[d.state] - lowBits := d.br.getBitsFast(n.nbBits) - d.state = n.newState + lowBits - return n.symbol -} diff --git a/vendor/github.com/klauspost/compress/fse/fse.go b/vendor/github.com/klauspost/compress/fse/fse.go deleted file mode 100644 index 535cbadfd..000000000 --- a/vendor/github.com/klauspost/compress/fse/fse.go +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright 2018 Klaus Post. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. - -// Package fse provides Finite State Entropy encoding and decoding. -// -// Finite State Entropy encoding provides a fast near-optimal symbol encoding/decoding -// for byte blocks as implemented in zstd. -// -// See https://github.com/klauspost/compress/tree/master/fse for more information. -package fse - -import ( - "errors" - "fmt" - "math/bits" -) - -const ( - /*!MEMORY_USAGE : - * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) - * Increasing memory usage improves compression ratio - * Reduced memory usage can improve speed, due to cache effect - * Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */ - maxMemoryUsage = 14 - defaultMemoryUsage = 13 - - maxTableLog = maxMemoryUsage - 2 - maxTablesize = 1 << maxTableLog - defaultTablelog = defaultMemoryUsage - 2 - minTablelog = 5 - maxSymbolValue = 255 -) - -var ( - // ErrIncompressible is returned when input is judged to be too hard to compress. - ErrIncompressible = errors.New("input is not compressible") - - // ErrUseRLE is returned from the compressor when the input is a single byte value repeated. - ErrUseRLE = errors.New("input is single value repeated") -) - -// Scratch provides temporary storage for compression and decompression. -type Scratch struct { - // Private - count [maxSymbolValue + 1]uint32 - norm [maxSymbolValue + 1]int16 - br byteReader - bits bitReader - bw bitWriter - ct cTable // Compression tables. - decTable []decSymbol // Decompression table. - maxCount int // count of the most probable symbol - - // Per block parameters. - // These can be used to override compression parameters of the block. - // Do not touch, unless you know what you are doing. - - // Out is output buffer. - // If the scratch is re-used before the caller is done processing the output, - // set this field to nil. - // Otherwise the output buffer will be re-used for next Compression/Decompression step - // and allocation will be avoided. - Out []byte - - // DecompressLimit limits the maximum decoded size acceptable. - // If > 0 decompression will stop when approximately this many bytes - // has been decoded. - // If 0, maximum size will be 2GB. - DecompressLimit int - - symbolLen uint16 // Length of active part of the symbol table. - actualTableLog uint8 // Selected tablelog. - zeroBits bool // no bits has prob > 50%. - clearCount bool // clear count - - // MaxSymbolValue will override the maximum symbol value of the next block. - MaxSymbolValue uint8 - - // TableLog will attempt to override the tablelog for the next block. - TableLog uint8 -} - -// Histogram allows to populate the histogram and skip that step in the compression, -// It otherwise allows to inspect the histogram when compression is done. -// To indicate that you have populated the histogram call HistogramFinished -// with the value of the highest populated symbol, as well as the number of entries -// in the most populated entry. These are accepted at face value. -// The returned slice will always be length 256. -func (s *Scratch) Histogram() []uint32 { - return s.count[:] -} - -// HistogramFinished can be called to indicate that the histogram has been populated. -// maxSymbol is the index of the highest set symbol of the next data segment. -// maxCount is the number of entries in the most populated entry. -// These are accepted at face value. -func (s *Scratch) HistogramFinished(maxSymbol uint8, maxCount int) { - s.maxCount = maxCount - s.symbolLen = uint16(maxSymbol) + 1 - s.clearCount = maxCount != 0 -} - -// prepare will prepare and allocate scratch tables used for both compression and decompression. -func (s *Scratch) prepare(in []byte) (*Scratch, error) { - if s == nil { - s = &Scratch{} - } - if s.MaxSymbolValue == 0 { - s.MaxSymbolValue = 255 - } - if s.TableLog == 0 { - s.TableLog = defaultTablelog - } - if s.TableLog > maxTableLog { - return nil, fmt.Errorf("tableLog (%d) > maxTableLog (%d)", s.TableLog, maxTableLog) - } - if cap(s.Out) == 0 { - s.Out = make([]byte, 0, len(in)) - } - if s.clearCount && s.maxCount == 0 { - for i := range s.count { - s.count[i] = 0 - } - s.clearCount = false - } - s.br.init(in) - if s.DecompressLimit == 0 { - // Max size 2GB. - s.DecompressLimit = (2 << 30) - 1 - } - - return s, nil -} - -// tableStep returns the next table index. -func tableStep(tableSize uint32) uint32 { - return (tableSize >> 1) + (tableSize >> 3) + 3 -} - -func highBits(val uint32) (n uint32) { - return uint32(bits.Len32(val) - 1) -} diff --git a/vendor/github.com/klauspost/compress/gen.sh b/vendor/github.com/klauspost/compress/gen.sh deleted file mode 100644 index aff942205..000000000 --- a/vendor/github.com/klauspost/compress/gen.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh - -cd s2/cmd/_s2sx/ || exit 1 -go generate . diff --git a/vendor/github.com/klauspost/compress/huff0/.gitignore b/vendor/github.com/klauspost/compress/huff0/.gitignore deleted file mode 100644 index b3d262958..000000000 --- a/vendor/github.com/klauspost/compress/huff0/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/huff0-fuzz.zip diff --git a/vendor/github.com/klauspost/compress/huff0/README.md b/vendor/github.com/klauspost/compress/huff0/README.md deleted file mode 100644 index 8b6e5c663..000000000 --- a/vendor/github.com/klauspost/compress/huff0/README.md +++ /dev/null @@ -1,89 +0,0 @@ -# Huff0 entropy compression - -This package provides Huff0 encoding and decoding as used in zstd. - -[Huff0](https://github.com/Cyan4973/FiniteStateEntropy#new-generation-entropy-coders), -a Huffman codec designed for modern CPU, featuring OoO (Out of Order) operations on multiple ALU -(Arithmetic Logic Unit), achieving extremely fast compression and decompression speeds. - -This can be used for compressing input with a lot of similar input values to the smallest number of bytes. -This does not perform any multi-byte [dictionary coding](https://en.wikipedia.org/wiki/Dictionary_coder) as LZ coders, -but it can be used as a secondary step to compressors (like Snappy) that does not do entropy encoding. - -* [Godoc documentation](https://godoc.org/github.com/klauspost/compress/huff0) - -## News - -This is used as part of the [zstandard](https://github.com/klauspost/compress/tree/master/zstd#zstd) compression and decompression package. - -This ensures that most functionality is well tested. - -# Usage - -This package provides a low level interface that allows to compress single independent blocks. - -Each block is separate, and there is no built in integrity checks. -This means that the caller should keep track of block sizes and also do checksums if needed. - -Compressing a block is done via the [`Compress1X`](https://godoc.org/github.com/klauspost/compress/huff0#Compress1X) and -[`Compress4X`](https://godoc.org/github.com/klauspost/compress/huff0#Compress4X) functions. -You must provide input and will receive the output and maybe an error. - -These error values can be returned: - -| Error | Description | -|---------------------|-----------------------------------------------------------------------------| -| `` | Everything ok, output is returned | -| `ErrIncompressible` | Returned when input is judged to be too hard to compress | -| `ErrUseRLE` | Returned from the compressor when the input is a single byte value repeated | -| `ErrTooBig` | Returned if the input block exceeds the maximum allowed size (128 Kib) | -| `(error)` | An internal error occurred. | - - -As can be seen above some of there are errors that will be returned even under normal operation so it is important to handle these. - -To reduce allocations you can provide a [`Scratch`](https://godoc.org/github.com/klauspost/compress/huff0#Scratch) object -that can be re-used for successive calls. Both compression and decompression accepts a `Scratch` object, and the same -object can be used for both. - -Be aware, that when re-using a `Scratch` object that the *output* buffer is also re-used, so if you are still using this -you must set the `Out` field in the scratch to nil. The same buffer is used for compression and decompression output. - -The `Scratch` object will retain state that allows to re-use previous tables for encoding and decoding. - -## Tables and re-use - -Huff0 allows for reusing tables from the previous block to save space if that is expected to give better/faster results. - -The Scratch object allows you to set a [`ReusePolicy`](https://godoc.org/github.com/klauspost/compress/huff0#ReusePolicy) -that controls this behaviour. See the documentation for details. This can be altered between each block. - -Do however note that this information is *not* stored in the output block and it is up to the users of the package to -record whether [`ReadTable`](https://godoc.org/github.com/klauspost/compress/huff0#ReadTable) should be called, -based on the boolean reported back from the CompressXX call. - -If you want to store the table separate from the data, you can access them as `OutData` and `OutTable` on the -[`Scratch`](https://godoc.org/github.com/klauspost/compress/huff0#Scratch) object. - -## Decompressing - -The first part of decoding is to initialize the decoding table through [`ReadTable`](https://godoc.org/github.com/klauspost/compress/huff0#ReadTable). -This will initialize the decoding tables. -You can supply the complete block to `ReadTable` and it will return the data part of the block -which can be given to the decompressor. - -Decompressing is done by calling the [`Decompress1X`](https://godoc.org/github.com/klauspost/compress/huff0#Scratch.Decompress1X) -or [`Decompress4X`](https://godoc.org/github.com/klauspost/compress/huff0#Scratch.Decompress4X) function. - -For concurrently decompressing content with a fixed table a stateless [`Decoder`](https://godoc.org/github.com/klauspost/compress/huff0#Decoder) can be requested which will remain correct as long as the scratch is unchanged. The capacity of the provided slice indicates the expected output size. - -You must provide the output from the compression stage, at exactly the size you got back. If you receive an error back -your input was likely corrupted. - -It is important to note that a successful decoding does *not* mean your output matches your original input. -There are no integrity checks, so relying on errors from the decompressor does not assure your data is valid. - -# Contributing - -Contributions are always welcome. Be aware that adding public functions will require good justification and breaking -changes will likely not be accepted. If in doubt open an issue before writing the PR. diff --git a/vendor/github.com/klauspost/compress/huff0/bitreader.go b/vendor/github.com/klauspost/compress/huff0/bitreader.go deleted file mode 100644 index e36d9742f..000000000 --- a/vendor/github.com/klauspost/compress/huff0/bitreader.go +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright 2018 Klaus Post. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. - -package huff0 - -import ( - "encoding/binary" - "errors" - "fmt" - "io" -) - -// bitReader reads a bitstream in reverse. -// The last set bit indicates the start of the stream and is used -// for aligning the input. -type bitReaderBytes struct { - in []byte - off uint // next byte to read is at in[off - 1] - value uint64 - bitsRead uint8 -} - -// init initializes and resets the bit reader. -func (b *bitReaderBytes) init(in []byte) error { - if len(in) < 1 { - return errors.New("corrupt stream: too short") - } - b.in = in - b.off = uint(len(in)) - // The highest bit of the last byte indicates where to start - v := in[len(in)-1] - if v == 0 { - return errors.New("corrupt stream, did not find end of stream") - } - b.bitsRead = 64 - b.value = 0 - if len(in) >= 8 { - b.fillFastStart() - } else { - b.fill() - b.fill() - } - b.advance(8 - uint8(highBit32(uint32(v)))) - return nil -} - -// peekBitsFast requires that at least one bit is requested every time. -// There are no checks if the buffer is filled. -func (b *bitReaderBytes) peekByteFast() uint8 { - got := uint8(b.value >> 56) - return got -} - -func (b *bitReaderBytes) advance(n uint8) { - b.bitsRead += n - b.value <<= n & 63 -} - -// fillFast() will make sure at least 32 bits are available. -// There must be at least 4 bytes available. -func (b *bitReaderBytes) fillFast() { - if b.bitsRead < 32 { - return - } - - // 2 bounds checks. - v := b.in[b.off-4 : b.off] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - b.value |= uint64(low) << (b.bitsRead - 32) - b.bitsRead -= 32 - b.off -= 4 -} - -// fillFastStart() assumes the bitReaderBytes is empty and there is at least 8 bytes to read. -func (b *bitReaderBytes) fillFastStart() { - // Do single re-slice to avoid bounds checks. - b.value = binary.LittleEndian.Uint64(b.in[b.off-8:]) - b.bitsRead = 0 - b.off -= 8 -} - -// fill() will make sure at least 32 bits are available. -func (b *bitReaderBytes) fill() { - if b.bitsRead < 32 { - return - } - if b.off > 4 { - v := b.in[b.off-4 : b.off] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - b.value |= uint64(low) << (b.bitsRead - 32) - b.bitsRead -= 32 - b.off -= 4 - return - } - for b.off > 0 { - b.value |= uint64(b.in[b.off-1]) << (b.bitsRead - 8) - b.bitsRead -= 8 - b.off-- - } -} - -// finished returns true if all bits have been read from the bit stream. -func (b *bitReaderBytes) finished() bool { - return b.off == 0 && b.bitsRead >= 64 -} - -func (b *bitReaderBytes) remaining() uint { - return b.off*8 + uint(64-b.bitsRead) -} - -// close the bitstream and returns an error if out-of-buffer reads occurred. -func (b *bitReaderBytes) close() error { - // Release reference. - b.in = nil - if b.remaining() > 0 { - return fmt.Errorf("corrupt input: %d bits remain on stream", b.remaining()) - } - if b.bitsRead > 64 { - return io.ErrUnexpectedEOF - } - return nil -} - -// bitReaderShifted reads a bitstream in reverse. -// The last set bit indicates the start of the stream and is used -// for aligning the input. -type bitReaderShifted struct { - in []byte - off uint // next byte to read is at in[off - 1] - value uint64 - bitsRead uint8 -} - -// init initializes and resets the bit reader. -func (b *bitReaderShifted) init(in []byte) error { - if len(in) < 1 { - return errors.New("corrupt stream: too short") - } - b.in = in - b.off = uint(len(in)) - // The highest bit of the last byte indicates where to start - v := in[len(in)-1] - if v == 0 { - return errors.New("corrupt stream, did not find end of stream") - } - b.bitsRead = 64 - b.value = 0 - if len(in) >= 8 { - b.fillFastStart() - } else { - b.fill() - b.fill() - } - b.advance(8 - uint8(highBit32(uint32(v)))) - return nil -} - -// peekBitsFast requires that at least one bit is requested every time. -// There are no checks if the buffer is filled. -func (b *bitReaderShifted) peekBitsFast(n uint8) uint16 { - return uint16(b.value >> ((64 - n) & 63)) -} - -func (b *bitReaderShifted) advance(n uint8) { - b.bitsRead += n - b.value <<= n & 63 -} - -// fillFast() will make sure at least 32 bits are available. -// There must be at least 4 bytes available. -func (b *bitReaderShifted) fillFast() { - if b.bitsRead < 32 { - return - } - - // 2 bounds checks. - v := b.in[b.off-4 : b.off] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - b.value |= uint64(low) << ((b.bitsRead - 32) & 63) - b.bitsRead -= 32 - b.off -= 4 -} - -// fillFastStart() assumes the bitReaderShifted is empty and there is at least 8 bytes to read. -func (b *bitReaderShifted) fillFastStart() { - // Do single re-slice to avoid bounds checks. - b.value = binary.LittleEndian.Uint64(b.in[b.off-8:]) - b.bitsRead = 0 - b.off -= 8 -} - -// fill() will make sure at least 32 bits are available. -func (b *bitReaderShifted) fill() { - if b.bitsRead < 32 { - return - } - if b.off > 4 { - v := b.in[b.off-4 : b.off] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - b.value |= uint64(low) << ((b.bitsRead - 32) & 63) - b.bitsRead -= 32 - b.off -= 4 - return - } - for b.off > 0 { - b.value |= uint64(b.in[b.off-1]) << ((b.bitsRead - 8) & 63) - b.bitsRead -= 8 - b.off-- - } -} - -func (b *bitReaderShifted) remaining() uint { - return b.off*8 + uint(64-b.bitsRead) -} - -// close the bitstream and returns an error if out-of-buffer reads occurred. -func (b *bitReaderShifted) close() error { - // Release reference. - b.in = nil - if b.remaining() > 0 { - return fmt.Errorf("corrupt input: %d bits remain on stream", b.remaining()) - } - if b.bitsRead > 64 { - return io.ErrUnexpectedEOF - } - return nil -} diff --git a/vendor/github.com/klauspost/compress/huff0/bitwriter.go b/vendor/github.com/klauspost/compress/huff0/bitwriter.go deleted file mode 100644 index 0ebc9aaac..000000000 --- a/vendor/github.com/klauspost/compress/huff0/bitwriter.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2018 Klaus Post. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. - -package huff0 - -// bitWriter will write bits. -// First bit will be LSB of the first byte of output. -type bitWriter struct { - bitContainer uint64 - nBits uint8 - out []byte -} - -// addBits16Clean will add up to 16 bits. value may not contain more set bits than indicated. -// It will not check if there is space for them, so the caller must ensure that it has flushed recently. -func (b *bitWriter) addBits16Clean(value uint16, bits uint8) { - b.bitContainer |= uint64(value) << (b.nBits & 63) - b.nBits += bits -} - -// encSymbol will add up to 16 bits. value may not contain more set bits than indicated. -// It will not check if there is space for them, so the caller must ensure that it has flushed recently. -func (b *bitWriter) encSymbol(ct cTable, symbol byte) { - enc := ct[symbol] - b.bitContainer |= uint64(enc.val) << (b.nBits & 63) - if false { - if enc.nBits == 0 { - panic("nbits 0") - } - } - b.nBits += enc.nBits -} - -// encTwoSymbols will add up to 32 bits. value may not contain more set bits than indicated. -// It will not check if there is space for them, so the caller must ensure that it has flushed recently. -func (b *bitWriter) encTwoSymbols(ct cTable, av, bv byte) { - encA := ct[av] - encB := ct[bv] - sh := b.nBits & 63 - combined := uint64(encA.val) | (uint64(encB.val) << (encA.nBits & 63)) - b.bitContainer |= combined << sh - if false { - if encA.nBits == 0 { - panic("nbitsA 0") - } - if encB.nBits == 0 { - panic("nbitsB 0") - } - } - b.nBits += encA.nBits + encB.nBits -} - -// encFourSymbols adds up to 32 bits from four symbols. -// It will not check if there is space for them, -// so the caller must ensure that b has been flushed recently. -func (b *bitWriter) encFourSymbols(encA, encB, encC, encD cTableEntry) { - bitsA := encA.nBits - bitsB := bitsA + encB.nBits - bitsC := bitsB + encC.nBits - bitsD := bitsC + encD.nBits - combined := uint64(encA.val) | - (uint64(encB.val) << (bitsA & 63)) | - (uint64(encC.val) << (bitsB & 63)) | - (uint64(encD.val) << (bitsC & 63)) - b.bitContainer |= combined << (b.nBits & 63) - b.nBits += bitsD -} - -// flush32 will flush out, so there are at least 32 bits available for writing. -func (b *bitWriter) flush32() { - if b.nBits < 32 { - return - } - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - byte(b.bitContainer>>16), - byte(b.bitContainer>>24)) - b.nBits -= 32 - b.bitContainer >>= 32 -} - -// flushAlign will flush remaining full bytes and align to next byte boundary. -func (b *bitWriter) flushAlign() { - nbBytes := (b.nBits + 7) >> 3 - for i := uint8(0); i < nbBytes; i++ { - b.out = append(b.out, byte(b.bitContainer>>(i*8))) - } - b.nBits = 0 - b.bitContainer = 0 -} - -// close will write the alignment bit and write the final byte(s) -// to the output. -func (b *bitWriter) close() { - // End mark - b.addBits16Clean(1, 1) - // flush until next byte. - b.flushAlign() -} diff --git a/vendor/github.com/klauspost/compress/huff0/bytereader.go b/vendor/github.com/klauspost/compress/huff0/bytereader.go deleted file mode 100644 index 4dcab8d23..000000000 --- a/vendor/github.com/klauspost/compress/huff0/bytereader.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2018 Klaus Post. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. - -package huff0 - -// byteReader provides a byte reader that reads -// little endian values from a byte stream. -// The input stream is manually advanced. -// The reader performs no bounds checks. -type byteReader struct { - b []byte - off int -} - -// init will initialize the reader and set the input. -func (b *byteReader) init(in []byte) { - b.b = in - b.off = 0 -} - -// Int32 returns a little endian int32 starting at current offset. -func (b byteReader) Int32() int32 { - v3 := int32(b.b[b.off+3]) - v2 := int32(b.b[b.off+2]) - v1 := int32(b.b[b.off+1]) - v0 := int32(b.b[b.off]) - return (v3 << 24) | (v2 << 16) | (v1 << 8) | v0 -} - -// Uint32 returns a little endian uint32 starting at current offset. -func (b byteReader) Uint32() uint32 { - v3 := uint32(b.b[b.off+3]) - v2 := uint32(b.b[b.off+2]) - v1 := uint32(b.b[b.off+1]) - v0 := uint32(b.b[b.off]) - return (v3 << 24) | (v2 << 16) | (v1 << 8) | v0 -} - -// remain will return the number of bytes remaining. -func (b byteReader) remain() int { - return len(b.b) - b.off -} diff --git a/vendor/github.com/klauspost/compress/huff0/compress.go b/vendor/github.com/klauspost/compress/huff0/compress.go deleted file mode 100644 index 518436cf3..000000000 --- a/vendor/github.com/klauspost/compress/huff0/compress.go +++ /dev/null @@ -1,741 +0,0 @@ -package huff0 - -import ( - "fmt" - "math" - "runtime" - "sync" -) - -// Compress1X will compress the input. -// The output can be decoded using Decompress1X. -// Supply a Scratch object. The scratch object contains state about re-use, -// So when sharing across independent encodes, be sure to set the re-use policy. -func Compress1X(in []byte, s *Scratch) (out []byte, reUsed bool, err error) { - s, err = s.prepare(in) - if err != nil { - return nil, false, err - } - return compress(in, s, s.compress1X) -} - -// Compress4X will compress the input. The input is split into 4 independent blocks -// and compressed similar to Compress1X. -// The output can be decoded using Decompress4X. -// Supply a Scratch object. The scratch object contains state about re-use, -// So when sharing across independent encodes, be sure to set the re-use policy. -func Compress4X(in []byte, s *Scratch) (out []byte, reUsed bool, err error) { - s, err = s.prepare(in) - if err != nil { - return nil, false, err - } - if false { - // TODO: compress4Xp only slightly faster. - const parallelThreshold = 8 << 10 - if len(in) < parallelThreshold || runtime.GOMAXPROCS(0) == 1 { - return compress(in, s, s.compress4X) - } - return compress(in, s, s.compress4Xp) - } - return compress(in, s, s.compress4X) -} - -func compress(in []byte, s *Scratch, compressor func(src []byte) ([]byte, error)) (out []byte, reUsed bool, err error) { - // Nuke previous table if we cannot reuse anyway. - if s.Reuse == ReusePolicyNone { - s.prevTable = s.prevTable[:0] - } - - // Create histogram, if none was provided. - maxCount := s.maxCount - var canReuse = false - if maxCount == 0 { - maxCount, canReuse = s.countSimple(in) - } else { - canReuse = s.canUseTable(s.prevTable) - } - - // We want the output size to be less than this: - wantSize := len(in) - if s.WantLogLess > 0 { - wantSize -= wantSize >> s.WantLogLess - } - - // Reset for next run. - s.clearCount = true - s.maxCount = 0 - if maxCount >= len(in) { - if maxCount > len(in) { - return nil, false, fmt.Errorf("maxCount (%d) > length (%d)", maxCount, len(in)) - } - if len(in) == 1 { - return nil, false, ErrIncompressible - } - // One symbol, use RLE - return nil, false, ErrUseRLE - } - if maxCount == 1 || maxCount < (len(in)>>7) { - // Each symbol present maximum once or too well distributed. - return nil, false, ErrIncompressible - } - if s.Reuse == ReusePolicyMust && !canReuse { - // We must reuse, but we can't. - return nil, false, ErrIncompressible - } - if (s.Reuse == ReusePolicyPrefer || s.Reuse == ReusePolicyMust) && canReuse { - keepTable := s.cTable - keepTL := s.actualTableLog - s.cTable = s.prevTable - s.actualTableLog = s.prevTableLog - s.Out, err = compressor(in) - s.cTable = keepTable - s.actualTableLog = keepTL - if err == nil && len(s.Out) < wantSize { - s.OutData = s.Out - return s.Out, true, nil - } - if s.Reuse == ReusePolicyMust { - return nil, false, ErrIncompressible - } - // Do not attempt to re-use later. - s.prevTable = s.prevTable[:0] - } - - // Calculate new table. - err = s.buildCTable() - if err != nil { - return nil, false, err - } - - if false && !s.canUseTable(s.cTable) { - panic("invalid table generated") - } - - if s.Reuse == ReusePolicyAllow && canReuse { - hSize := len(s.Out) - oldSize := s.prevTable.estimateSize(s.count[:s.symbolLen]) - newSize := s.cTable.estimateSize(s.count[:s.symbolLen]) - if oldSize <= hSize+newSize || hSize+12 >= wantSize { - // Retain cTable even if we re-use. - keepTable := s.cTable - keepTL := s.actualTableLog - - s.cTable = s.prevTable - s.actualTableLog = s.prevTableLog - s.Out, err = compressor(in) - - // Restore ctable. - s.cTable = keepTable - s.actualTableLog = keepTL - if err != nil { - return nil, false, err - } - if len(s.Out) >= wantSize { - return nil, false, ErrIncompressible - } - s.OutData = s.Out - return s.Out, true, nil - } - } - - // Use new table - err = s.cTable.write(s) - if err != nil { - s.OutTable = nil - return nil, false, err - } - s.OutTable = s.Out - - // Compress using new table - s.Out, err = compressor(in) - if err != nil { - s.OutTable = nil - return nil, false, err - } - if len(s.Out) >= wantSize { - s.OutTable = nil - return nil, false, ErrIncompressible - } - // Move current table into previous. - s.prevTable, s.prevTableLog, s.cTable = s.cTable, s.actualTableLog, s.prevTable[:0] - s.OutData = s.Out[len(s.OutTable):] - return s.Out, false, nil -} - -// EstimateSizes will estimate the data sizes -func EstimateSizes(in []byte, s *Scratch) (tableSz, dataSz, reuseSz int, err error) { - s, err = s.prepare(in) - if err != nil { - return 0, 0, 0, err - } - - // Create histogram, if none was provided. - tableSz, dataSz, reuseSz = -1, -1, -1 - maxCount := s.maxCount - var canReuse = false - if maxCount == 0 { - maxCount, canReuse = s.countSimple(in) - } else { - canReuse = s.canUseTable(s.prevTable) - } - - // We want the output size to be less than this: - wantSize := len(in) - if s.WantLogLess > 0 { - wantSize -= wantSize >> s.WantLogLess - } - - // Reset for next run. - s.clearCount = true - s.maxCount = 0 - if maxCount >= len(in) { - if maxCount > len(in) { - return 0, 0, 0, fmt.Errorf("maxCount (%d) > length (%d)", maxCount, len(in)) - } - if len(in) == 1 { - return 0, 0, 0, ErrIncompressible - } - // One symbol, use RLE - return 0, 0, 0, ErrUseRLE - } - if maxCount == 1 || maxCount < (len(in)>>7) { - // Each symbol present maximum once or too well distributed. - return 0, 0, 0, ErrIncompressible - } - - // Calculate new table. - err = s.buildCTable() - if err != nil { - return 0, 0, 0, err - } - - if false && !s.canUseTable(s.cTable) { - panic("invalid table generated") - } - - tableSz, err = s.cTable.estTableSize(s) - if err != nil { - return 0, 0, 0, err - } - if canReuse { - reuseSz = s.prevTable.estimateSize(s.count[:s.symbolLen]) - } - dataSz = s.cTable.estimateSize(s.count[:s.symbolLen]) - - // Restore - return tableSz, dataSz, reuseSz, nil -} - -func (s *Scratch) compress1X(src []byte) ([]byte, error) { - return s.compress1xDo(s.Out, src), nil -} - -func (s *Scratch) compress1xDo(dst, src []byte) []byte { - var bw = bitWriter{out: dst} - - // N is length divisible by 4. - n := len(src) - n -= n & 3 - cTable := s.cTable[:256] - - // Encode last bytes. - for i := len(src) & 3; i > 0; i-- { - bw.encSymbol(cTable, src[n+i-1]) - } - n -= 4 - if s.actualTableLog <= 8 { - for ; n >= 0; n -= 4 { - tmp := src[n : n+4] - // tmp should be len 4 - bw.flush32() - bw.encFourSymbols(cTable[tmp[3]], cTable[tmp[2]], cTable[tmp[1]], cTable[tmp[0]]) - } - } else { - for ; n >= 0; n -= 4 { - tmp := src[n : n+4] - // tmp should be len 4 - bw.flush32() - bw.encTwoSymbols(cTable, tmp[3], tmp[2]) - bw.flush32() - bw.encTwoSymbols(cTable, tmp[1], tmp[0]) - } - } - bw.close() - return bw.out -} - -var sixZeros [6]byte - -func (s *Scratch) compress4X(src []byte) ([]byte, error) { - if len(src) < 12 { - return nil, ErrIncompressible - } - segmentSize := (len(src) + 3) / 4 - - // Add placeholder for output length - offsetIdx := len(s.Out) - s.Out = append(s.Out, sixZeros[:]...) - - for i := 0; i < 4; i++ { - toDo := src - if len(toDo) > segmentSize { - toDo = toDo[:segmentSize] - } - src = src[len(toDo):] - - idx := len(s.Out) - s.Out = s.compress1xDo(s.Out, toDo) - if len(s.Out)-idx > math.MaxUint16 { - // We cannot store the size in the jump table - return nil, ErrIncompressible - } - // Write compressed length as little endian before block. - if i < 3 { - // Last length is not written. - length := len(s.Out) - idx - s.Out[i*2+offsetIdx] = byte(length) - s.Out[i*2+offsetIdx+1] = byte(length >> 8) - } - } - - return s.Out, nil -} - -// compress4Xp will compress 4 streams using separate goroutines. -func (s *Scratch) compress4Xp(src []byte) ([]byte, error) { - if len(src) < 12 { - return nil, ErrIncompressible - } - // Add placeholder for output length - s.Out = s.Out[:6] - - segmentSize := (len(src) + 3) / 4 - var wg sync.WaitGroup - wg.Add(4) - for i := 0; i < 4; i++ { - toDo := src - if len(toDo) > segmentSize { - toDo = toDo[:segmentSize] - } - src = src[len(toDo):] - - // Separate goroutine for each block. - go func(i int) { - s.tmpOut[i] = s.compress1xDo(s.tmpOut[i][:0], toDo) - wg.Done() - }(i) - } - wg.Wait() - for i := 0; i < 4; i++ { - o := s.tmpOut[i] - if len(o) > math.MaxUint16 { - // We cannot store the size in the jump table - return nil, ErrIncompressible - } - // Write compressed length as little endian before block. - if i < 3 { - // Last length is not written. - s.Out[i*2] = byte(len(o)) - s.Out[i*2+1] = byte(len(o) >> 8) - } - - // Write output. - s.Out = append(s.Out, o...) - } - return s.Out, nil -} - -// countSimple will create a simple histogram in s.count. -// Returns the biggest count. -// Does not update s.clearCount. -func (s *Scratch) countSimple(in []byte) (max int, reuse bool) { - reuse = true - for _, v := range in { - s.count[v]++ - } - m := uint32(0) - if len(s.prevTable) > 0 { - for i, v := range s.count[:] { - if v == 0 { - continue - } - if v > m { - m = v - } - s.symbolLen = uint16(i) + 1 - if i >= len(s.prevTable) { - reuse = false - } else if s.prevTable[i].nBits == 0 { - reuse = false - } - } - return int(m), reuse - } - for i, v := range s.count[:] { - if v == 0 { - continue - } - if v > m { - m = v - } - s.symbolLen = uint16(i) + 1 - } - return int(m), false -} - -func (s *Scratch) canUseTable(c cTable) bool { - if len(c) < int(s.symbolLen) { - return false - } - for i, v := range s.count[:s.symbolLen] { - if v != 0 && c[i].nBits == 0 { - return false - } - } - return true -} - -//lint:ignore U1000 used for debugging -func (s *Scratch) validateTable(c cTable) bool { - if len(c) < int(s.symbolLen) { - return false - } - for i, v := range s.count[:s.symbolLen] { - if v != 0 { - if c[i].nBits == 0 { - return false - } - if c[i].nBits > s.actualTableLog { - return false - } - } - } - return true -} - -// minTableLog provides the minimum logSize to safely represent a distribution. -func (s *Scratch) minTableLog() uint8 { - minBitsSrc := highBit32(uint32(s.br.remain())) + 1 - minBitsSymbols := highBit32(uint32(s.symbolLen-1)) + 2 - if minBitsSrc < minBitsSymbols { - return uint8(minBitsSrc) - } - return uint8(minBitsSymbols) -} - -// optimalTableLog calculates and sets the optimal tableLog in s.actualTableLog -func (s *Scratch) optimalTableLog() { - tableLog := s.TableLog - minBits := s.minTableLog() - maxBitsSrc := uint8(highBit32(uint32(s.br.remain()-1))) - 1 - if maxBitsSrc < tableLog { - // Accuracy can be reduced - tableLog = maxBitsSrc - } - if minBits > tableLog { - tableLog = minBits - } - // Need a minimum to safely represent all symbol values - if tableLog < minTablelog { - tableLog = minTablelog - } - if tableLog > tableLogMax { - tableLog = tableLogMax - } - s.actualTableLog = tableLog -} - -type cTableEntry struct { - val uint16 - nBits uint8 - // We have 8 bits extra -} - -const huffNodesMask = huffNodesLen - 1 - -func (s *Scratch) buildCTable() error { - s.optimalTableLog() - s.huffSort() - if cap(s.cTable) < maxSymbolValue+1 { - s.cTable = make([]cTableEntry, s.symbolLen, maxSymbolValue+1) - } else { - s.cTable = s.cTable[:s.symbolLen] - for i := range s.cTable { - s.cTable[i] = cTableEntry{} - } - } - - var startNode = int16(s.symbolLen) - nonNullRank := s.symbolLen - 1 - - nodeNb := startNode - huffNode := s.nodes[1 : huffNodesLen+1] - - // This overlays the slice above, but allows "-1" index lookups. - // Different from reference implementation. - huffNode0 := s.nodes[0 : huffNodesLen+1] - - for huffNode[nonNullRank].count() == 0 { - nonNullRank-- - } - - lowS := int16(nonNullRank) - nodeRoot := nodeNb + lowS - 1 - lowN := nodeNb - huffNode[nodeNb].setCount(huffNode[lowS].count() + huffNode[lowS-1].count()) - huffNode[lowS].setParent(nodeNb) - huffNode[lowS-1].setParent(nodeNb) - nodeNb++ - lowS -= 2 - for n := nodeNb; n <= nodeRoot; n++ { - huffNode[n].setCount(1 << 30) - } - // fake entry, strong barrier - huffNode0[0].setCount(1 << 31) - - // create parents - for nodeNb <= nodeRoot { - var n1, n2 int16 - if huffNode0[lowS+1].count() < huffNode0[lowN+1].count() { - n1 = lowS - lowS-- - } else { - n1 = lowN - lowN++ - } - if huffNode0[lowS+1].count() < huffNode0[lowN+1].count() { - n2 = lowS - lowS-- - } else { - n2 = lowN - lowN++ - } - - huffNode[nodeNb].setCount(huffNode0[n1+1].count() + huffNode0[n2+1].count()) - huffNode0[n1+1].setParent(nodeNb) - huffNode0[n2+1].setParent(nodeNb) - nodeNb++ - } - - // distribute weights (unlimited tree height) - huffNode[nodeRoot].setNbBits(0) - for n := nodeRoot - 1; n >= startNode; n-- { - huffNode[n].setNbBits(huffNode[huffNode[n].parent()].nbBits() + 1) - } - for n := uint16(0); n <= nonNullRank; n++ { - huffNode[n].setNbBits(huffNode[huffNode[n].parent()].nbBits() + 1) - } - s.actualTableLog = s.setMaxHeight(int(nonNullRank)) - maxNbBits := s.actualTableLog - - // fill result into tree (val, nbBits) - if maxNbBits > tableLogMax { - return fmt.Errorf("internal error: maxNbBits (%d) > tableLogMax (%d)", maxNbBits, tableLogMax) - } - var nbPerRank [tableLogMax + 1]uint16 - var valPerRank [16]uint16 - for _, v := range huffNode[:nonNullRank+1] { - nbPerRank[v.nbBits()]++ - } - // determine stating value per rank - { - min := uint16(0) - for n := maxNbBits; n > 0; n-- { - // get starting value within each rank - valPerRank[n] = min - min += nbPerRank[n] - min >>= 1 - } - } - - // push nbBits per symbol, symbol order - for _, v := range huffNode[:nonNullRank+1] { - s.cTable[v.symbol()].nBits = v.nbBits() - } - - // assign value within rank, symbol order - t := s.cTable[:s.symbolLen] - for n, val := range t { - nbits := val.nBits & 15 - v := valPerRank[nbits] - t[n].val = v - valPerRank[nbits] = v + 1 - } - - return nil -} - -// huffSort will sort symbols, decreasing order. -func (s *Scratch) huffSort() { - type rankPos struct { - base uint32 - current uint32 - } - - // Clear nodes - nodes := s.nodes[:huffNodesLen+1] - s.nodes = nodes - nodes = nodes[1 : huffNodesLen+1] - - // Sort into buckets based on length of symbol count. - var rank [32]rankPos - for _, v := range s.count[:s.symbolLen] { - r := highBit32(v+1) & 31 - rank[r].base++ - } - // maxBitLength is log2(BlockSizeMax) + 1 - const maxBitLength = 18 + 1 - for n := maxBitLength; n > 0; n-- { - rank[n-1].base += rank[n].base - } - for n := range rank[:maxBitLength] { - rank[n].current = rank[n].base - } - for n, c := range s.count[:s.symbolLen] { - r := (highBit32(c+1) + 1) & 31 - pos := rank[r].current - rank[r].current++ - prev := nodes[(pos-1)&huffNodesMask] - for pos > rank[r].base && c > prev.count() { - nodes[pos&huffNodesMask] = prev - pos-- - prev = nodes[(pos-1)&huffNodesMask] - } - nodes[pos&huffNodesMask] = makeNodeElt(c, byte(n)) - } -} - -func (s *Scratch) setMaxHeight(lastNonNull int) uint8 { - maxNbBits := s.actualTableLog - huffNode := s.nodes[1 : huffNodesLen+1] - //huffNode = huffNode[: huffNodesLen] - - largestBits := huffNode[lastNonNull].nbBits() - - // early exit : no elt > maxNbBits - if largestBits <= maxNbBits { - return largestBits - } - totalCost := int(0) - baseCost := int(1) << (largestBits - maxNbBits) - n := uint32(lastNonNull) - - for huffNode[n].nbBits() > maxNbBits { - totalCost += baseCost - (1 << (largestBits - huffNode[n].nbBits())) - huffNode[n].setNbBits(maxNbBits) - n-- - } - // n stops at huffNode[n].nbBits <= maxNbBits - - for huffNode[n].nbBits() == maxNbBits { - n-- - } - // n end at index of smallest symbol using < maxNbBits - - // renorm totalCost - totalCost >>= largestBits - maxNbBits /* note : totalCost is necessarily a multiple of baseCost */ - - // repay normalized cost - { - const noSymbol = 0xF0F0F0F0 - var rankLast [tableLogMax + 2]uint32 - - for i := range rankLast[:] { - rankLast[i] = noSymbol - } - - // Get pos of last (smallest) symbol per rank - { - currentNbBits := maxNbBits - for pos := int(n); pos >= 0; pos-- { - if huffNode[pos].nbBits() >= currentNbBits { - continue - } - currentNbBits = huffNode[pos].nbBits() // < maxNbBits - rankLast[maxNbBits-currentNbBits] = uint32(pos) - } - } - - for totalCost > 0 { - nBitsToDecrease := uint8(highBit32(uint32(totalCost))) + 1 - - for ; nBitsToDecrease > 1; nBitsToDecrease-- { - highPos := rankLast[nBitsToDecrease] - lowPos := rankLast[nBitsToDecrease-1] - if highPos == noSymbol { - continue - } - if lowPos == noSymbol { - break - } - highTotal := huffNode[highPos].count() - lowTotal := 2 * huffNode[lowPos].count() - if highTotal <= lowTotal { - break - } - } - // only triggered when no more rank 1 symbol left => find closest one (note : there is necessarily at least one !) - // HUF_MAX_TABLELOG test just to please gcc 5+; but it should not be necessary - // FIXME: try to remove - for (nBitsToDecrease <= tableLogMax) && (rankLast[nBitsToDecrease] == noSymbol) { - nBitsToDecrease++ - } - totalCost -= 1 << (nBitsToDecrease - 1) - if rankLast[nBitsToDecrease-1] == noSymbol { - // this rank is no longer empty - rankLast[nBitsToDecrease-1] = rankLast[nBitsToDecrease] - } - huffNode[rankLast[nBitsToDecrease]].setNbBits(1 + - huffNode[rankLast[nBitsToDecrease]].nbBits()) - if rankLast[nBitsToDecrease] == 0 { - /* special case, reached largest symbol */ - rankLast[nBitsToDecrease] = noSymbol - } else { - rankLast[nBitsToDecrease]-- - if huffNode[rankLast[nBitsToDecrease]].nbBits() != maxNbBits-nBitsToDecrease { - rankLast[nBitsToDecrease] = noSymbol /* this rank is now empty */ - } - } - } - - for totalCost < 0 { /* Sometimes, cost correction overshoot */ - if rankLast[1] == noSymbol { /* special case : no rank 1 symbol (using maxNbBits-1); let's create one from largest rank 0 (using maxNbBits) */ - for huffNode[n].nbBits() == maxNbBits { - n-- - } - huffNode[n+1].setNbBits(huffNode[n+1].nbBits() - 1) - rankLast[1] = n + 1 - totalCost++ - continue - } - huffNode[rankLast[1]+1].setNbBits(huffNode[rankLast[1]+1].nbBits() - 1) - rankLast[1]++ - totalCost++ - } - } - return maxNbBits -} - -// A nodeElt is the fields -// -// count uint32 -// parent uint16 -// symbol byte -// nbBits uint8 -// -// in some order, all squashed into an integer so that the compiler -// always loads and stores entire nodeElts instead of separate fields. -type nodeElt uint64 - -func makeNodeElt(count uint32, symbol byte) nodeElt { - return nodeElt(count) | nodeElt(symbol)<<48 -} - -func (e *nodeElt) count() uint32 { return uint32(*e) } -func (e *nodeElt) parent() uint16 { return uint16(*e >> 32) } -func (e *nodeElt) symbol() byte { return byte(*e >> 48) } -func (e *nodeElt) nbBits() uint8 { return uint8(*e >> 56) } - -func (e *nodeElt) setCount(c uint32) { *e = (*e)&0xffffffff00000000 | nodeElt(c) } -func (e *nodeElt) setParent(p int16) { *e = (*e)&0xffff0000ffffffff | nodeElt(uint16(p))<<32 } -func (e *nodeElt) setNbBits(n uint8) { *e = (*e)&0x00ffffffffffffff | nodeElt(n)<<56 } diff --git a/vendor/github.com/klauspost/compress/huff0/decompress.go b/vendor/github.com/klauspost/compress/huff0/decompress.go deleted file mode 100644 index 54bd08b25..000000000 --- a/vendor/github.com/klauspost/compress/huff0/decompress.go +++ /dev/null @@ -1,1167 +0,0 @@ -package huff0 - -import ( - "errors" - "fmt" - "io" - "sync" - - "github.com/klauspost/compress/fse" -) - -type dTable struct { - single []dEntrySingle -} - -// single-symbols decoding -type dEntrySingle struct { - entry uint16 -} - -// Uses special code for all tables that are < 8 bits. -const use8BitTables = true - -// ReadTable will read a table from the input. -// The size of the input may be larger than the table definition. -// Any content remaining after the table definition will be returned. -// If no Scratch is provided a new one is allocated. -// The returned Scratch can be used for encoding or decoding input using this table. -func ReadTable(in []byte, s *Scratch) (s2 *Scratch, remain []byte, err error) { - s, err = s.prepare(nil) - if err != nil { - return s, nil, err - } - if len(in) <= 1 { - return s, nil, errors.New("input too small for table") - } - iSize := in[0] - in = in[1:] - if iSize >= 128 { - // Uncompressed - oSize := iSize - 127 - iSize = (oSize + 1) / 2 - if int(iSize) > len(in) { - return s, nil, errors.New("input too small for table") - } - for n := uint8(0); n < oSize; n += 2 { - v := in[n/2] - s.huffWeight[n] = v >> 4 - s.huffWeight[n+1] = v & 15 - } - s.symbolLen = uint16(oSize) - in = in[iSize:] - } else { - if len(in) < int(iSize) { - return s, nil, fmt.Errorf("input too small for table, want %d bytes, have %d", iSize, len(in)) - } - // FSE compressed weights - s.fse.DecompressLimit = 255 - hw := s.huffWeight[:] - s.fse.Out = hw - b, err := fse.Decompress(in[:iSize], s.fse) - s.fse.Out = nil - if err != nil { - return s, nil, fmt.Errorf("fse decompress returned: %w", err) - } - if len(b) > 255 { - return s, nil, errors.New("corrupt input: output table too large") - } - s.symbolLen = uint16(len(b)) - in = in[iSize:] - } - - // collect weight stats - var rankStats [16]uint32 - weightTotal := uint32(0) - for _, v := range s.huffWeight[:s.symbolLen] { - if v > tableLogMax { - return s, nil, errors.New("corrupt input: weight too large") - } - v2 := v & 15 - rankStats[v2]++ - // (1 << (v2-1)) is slower since the compiler cannot prove that v2 isn't 0. - weightTotal += (1 << v2) >> 1 - } - if weightTotal == 0 { - return s, nil, errors.New("corrupt input: weights zero") - } - - // get last non-null symbol weight (implied, total must be 2^n) - { - tableLog := highBit32(weightTotal) + 1 - if tableLog > tableLogMax { - return s, nil, errors.New("corrupt input: tableLog too big") - } - s.actualTableLog = uint8(tableLog) - // determine last weight - { - total := uint32(1) << tableLog - rest := total - weightTotal - verif := uint32(1) << highBit32(rest) - lastWeight := highBit32(rest) + 1 - if verif != rest { - // last value must be a clean power of 2 - return s, nil, errors.New("corrupt input: last value not power of two") - } - s.huffWeight[s.symbolLen] = uint8(lastWeight) - s.symbolLen++ - rankStats[lastWeight]++ - } - } - - if (rankStats[1] < 2) || (rankStats[1]&1 != 0) { - // by construction : at least 2 elts of rank 1, must be even - return s, nil, errors.New("corrupt input: min elt size, even check failed ") - } - - // TODO: Choose between single/double symbol decoding - - // Calculate starting value for each rank - { - var nextRankStart uint32 - for n := uint8(1); n < s.actualTableLog+1; n++ { - current := nextRankStart - nextRankStart += rankStats[n] << (n - 1) - rankStats[n] = current - } - } - - // fill DTable (always full size) - tSize := 1 << tableLogMax - if len(s.dt.single) != tSize { - s.dt.single = make([]dEntrySingle, tSize) - } - cTable := s.prevTable - if cap(cTable) < maxSymbolValue+1 { - cTable = make([]cTableEntry, 0, maxSymbolValue+1) - } - cTable = cTable[:maxSymbolValue+1] - s.prevTable = cTable[:s.symbolLen] - s.prevTableLog = s.actualTableLog - - for n, w := range s.huffWeight[:s.symbolLen] { - if w == 0 { - cTable[n] = cTableEntry{ - val: 0, - nBits: 0, - } - continue - } - length := (uint32(1) << w) >> 1 - d := dEntrySingle{ - entry: uint16(s.actualTableLog+1-w) | (uint16(n) << 8), - } - - rank := &rankStats[w] - cTable[n] = cTableEntry{ - val: uint16(*rank >> (w - 1)), - nBits: uint8(d.entry), - } - - single := s.dt.single[*rank : *rank+length] - for i := range single { - single[i] = d - } - *rank += length - } - - return s, in, nil -} - -// Decompress1X will decompress a 1X encoded stream. -// The length of the supplied input must match the end of a block exactly. -// Before this is called, the table must be initialized with ReadTable unless -// the encoder re-used the table. -// deprecated: Use the stateless Decoder() to get a concurrent version. -func (s *Scratch) Decompress1X(in []byte) (out []byte, err error) { - if cap(s.Out) < s.MaxDecodedSize { - s.Out = make([]byte, s.MaxDecodedSize) - } - s.Out = s.Out[:0:s.MaxDecodedSize] - s.Out, err = s.Decoder().Decompress1X(s.Out, in) - return s.Out, err -} - -// Decompress4X will decompress a 4X encoded stream. -// Before this is called, the table must be initialized with ReadTable unless -// the encoder re-used the table. -// The length of the supplied input must match the end of a block exactly. -// The destination size of the uncompressed data must be known and provided. -// deprecated: Use the stateless Decoder() to get a concurrent version. -func (s *Scratch) Decompress4X(in []byte, dstSize int) (out []byte, err error) { - if dstSize > s.MaxDecodedSize { - return nil, ErrMaxDecodedSizeExceeded - } - if cap(s.Out) < dstSize { - s.Out = make([]byte, s.MaxDecodedSize) - } - s.Out = s.Out[:0:dstSize] - s.Out, err = s.Decoder().Decompress4X(s.Out, in) - return s.Out, err -} - -// Decoder will return a stateless decoder that can be used by multiple -// decompressors concurrently. -// Before this is called, the table must be initialized with ReadTable. -// The Decoder is still linked to the scratch buffer so that cannot be reused. -// However, it is safe to discard the scratch. -func (s *Scratch) Decoder() *Decoder { - return &Decoder{ - dt: s.dt, - actualTableLog: s.actualTableLog, - bufs: &s.decPool, - } -} - -// Decoder provides stateless decoding. -type Decoder struct { - dt dTable - actualTableLog uint8 - bufs *sync.Pool -} - -func (d *Decoder) buffer() *[4][256]byte { - buf, ok := d.bufs.Get().(*[4][256]byte) - if ok { - return buf - } - return &[4][256]byte{} -} - -// decompress1X8Bit will decompress a 1X encoded stream with tablelog <= 8. -// The cap of the output buffer will be the maximum decompressed size. -// The length of the supplied input must match the end of a block exactly. -func (d *Decoder) decompress1X8Bit(dst, src []byte) ([]byte, error) { - if d.actualTableLog == 8 { - return d.decompress1X8BitExactly(dst, src) - } - var br bitReaderBytes - err := br.init(src) - if err != nil { - return dst, err - } - maxDecodedSize := cap(dst) - dst = dst[:0] - - // Avoid bounds check by always having full sized table. - dt := d.dt.single[:256] - - // Use temp table to avoid bound checks/append penalty. - bufs := d.buffer() - buf := &bufs[0] - var off uint8 - - switch d.actualTableLog { - case 8: - const shift = 0 - for br.off >= 4 { - br.fillFast() - v := dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+0] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+1] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+2] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+3] = uint8(v.entry >> 8) - - off += 4 - if off == 0 { - if len(dst)+256 > maxDecodedSize { - br.close() - d.bufs.Put(bufs) - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:]...) - } - } - case 7: - const shift = 8 - 7 - for br.off >= 4 { - br.fillFast() - v := dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+0] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+1] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+2] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+3] = uint8(v.entry >> 8) - - off += 4 - if off == 0 { - if len(dst)+256 > maxDecodedSize { - br.close() - d.bufs.Put(bufs) - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:]...) - } - } - case 6: - const shift = 8 - 6 - for br.off >= 4 { - br.fillFast() - v := dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+0] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+1] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+2] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+3] = uint8(v.entry >> 8) - - off += 4 - if off == 0 { - if len(dst)+256 > maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:]...) - } - } - case 5: - const shift = 8 - 5 - for br.off >= 4 { - br.fillFast() - v := dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+0] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+1] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+2] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+3] = uint8(v.entry >> 8) - - off += 4 - if off == 0 { - if len(dst)+256 > maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:]...) - } - } - case 4: - const shift = 8 - 4 - for br.off >= 4 { - br.fillFast() - v := dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+0] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+1] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+2] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+3] = uint8(v.entry >> 8) - - off += 4 - if off == 0 { - if len(dst)+256 > maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:]...) - } - } - case 3: - const shift = 8 - 3 - for br.off >= 4 { - br.fillFast() - v := dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+0] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+1] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+2] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+3] = uint8(v.entry >> 8) - - off += 4 - if off == 0 { - if len(dst)+256 > maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:]...) - } - } - case 2: - const shift = 8 - 2 - for br.off >= 4 { - br.fillFast() - v := dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+0] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+1] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+2] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+3] = uint8(v.entry >> 8) - - off += 4 - if off == 0 { - if len(dst)+256 > maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:]...) - } - } - case 1: - const shift = 8 - 1 - for br.off >= 4 { - br.fillFast() - v := dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+0] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+1] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+2] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+3] = uint8(v.entry >> 8) - - off += 4 - if off == 0 { - if len(dst)+256 > maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:]...) - } - } - default: - d.bufs.Put(bufs) - return nil, fmt.Errorf("invalid tablelog: %d", d.actualTableLog) - } - - if len(dst)+int(off) > maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:off]...) - - // br < 4, so uint8 is fine - bitsLeft := int8(uint8(br.off)*8 + (64 - br.bitsRead)) - shift := (8 - d.actualTableLog) & 7 - - for bitsLeft > 0 { - if br.bitsRead >= 64-8 { - for br.off > 0 { - br.value |= uint64(br.in[br.off-1]) << (br.bitsRead - 8) - br.bitsRead -= 8 - br.off-- - } - } - if len(dst) >= maxDecodedSize { - br.close() - d.bufs.Put(bufs) - return nil, ErrMaxDecodedSizeExceeded - } - v := dt[br.peekByteFast()>>shift] - nBits := uint8(v.entry) - br.advance(nBits) - bitsLeft -= int8(nBits) - dst = append(dst, uint8(v.entry>>8)) - } - d.bufs.Put(bufs) - return dst, br.close() -} - -// decompress1X8Bit will decompress a 1X encoded stream with tablelog <= 8. -// The cap of the output buffer will be the maximum decompressed size. -// The length of the supplied input must match the end of a block exactly. -func (d *Decoder) decompress1X8BitExactly(dst, src []byte) ([]byte, error) { - var br bitReaderBytes - err := br.init(src) - if err != nil { - return dst, err - } - maxDecodedSize := cap(dst) - dst = dst[:0] - - // Avoid bounds check by always having full sized table. - dt := d.dt.single[:256] - - // Use temp table to avoid bound checks/append penalty. - bufs := d.buffer() - buf := &bufs[0] - var off uint8 - - const shift = 56 - - //fmt.Printf("mask: %b, tl:%d\n", mask, d.actualTableLog) - for br.off >= 4 { - br.fillFast() - v := dt[uint8(br.value>>shift)] - br.advance(uint8(v.entry)) - buf[off+0] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>shift)] - br.advance(uint8(v.entry)) - buf[off+1] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>shift)] - br.advance(uint8(v.entry)) - buf[off+2] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>shift)] - br.advance(uint8(v.entry)) - buf[off+3] = uint8(v.entry >> 8) - - off += 4 - if off == 0 { - if len(dst)+256 > maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:]...) - } - } - - if len(dst)+int(off) > maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:off]...) - - // br < 4, so uint8 is fine - bitsLeft := int8(uint8(br.off)*8 + (64 - br.bitsRead)) - for bitsLeft > 0 { - if br.bitsRead >= 64-8 { - for br.off > 0 { - br.value |= uint64(br.in[br.off-1]) << (br.bitsRead - 8) - br.bitsRead -= 8 - br.off-- - } - } - if len(dst) >= maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - v := dt[br.peekByteFast()] - nBits := uint8(v.entry) - br.advance(nBits) - bitsLeft -= int8(nBits) - dst = append(dst, uint8(v.entry>>8)) - } - d.bufs.Put(bufs) - return dst, br.close() -} - -// Decompress4X will decompress a 4X encoded stream. -// The length of the supplied input must match the end of a block exactly. -// The *capacity* of the dst slice must match the destination size of -// the uncompressed data exactly. -func (d *Decoder) decompress4X8bit(dst, src []byte) ([]byte, error) { - if d.actualTableLog == 8 { - return d.decompress4X8bitExactly(dst, src) - } - - var br [4]bitReaderBytes - start := 6 - for i := 0; i < 3; i++ { - length := int(src[i*2]) | (int(src[i*2+1]) << 8) - if start+length >= len(src) { - return nil, errors.New("truncated input (or invalid offset)") - } - err := br[i].init(src[start : start+length]) - if err != nil { - return nil, err - } - start += length - } - err := br[3].init(src[start:]) - if err != nil { - return nil, err - } - - // destination, offset to match first output - dstSize := cap(dst) - dst = dst[:dstSize] - out := dst - dstEvery := (dstSize + 3) / 4 - - shift := (56 + (8 - d.actualTableLog)) & 63 - - const tlSize = 1 << 8 - single := d.dt.single[:tlSize] - - // Use temp table to avoid bound checks/append penalty. - buf := d.buffer() - var off uint8 - var decoded int - - // Decode 4 values from each decoder/loop. - const bufoff = 256 - for { - if br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4 { - break - } - - { - // Interleave 2 decodes. - const stream = 0 - const stream2 = 1 - br1 := &br[stream] - br2 := &br[stream2] - br1.fillFast() - br2.fillFast() - - v := single[uint8(br1.value>>shift)].entry - v2 := single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off] = uint8(v >> 8) - buf[stream2][off] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+1] = uint8(v >> 8) - buf[stream2][off+1] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+2] = uint8(v >> 8) - buf[stream2][off+2] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+3] = uint8(v >> 8) - buf[stream2][off+3] = uint8(v2 >> 8) - } - - { - const stream = 2 - const stream2 = 3 - br1 := &br[stream] - br2 := &br[stream2] - br1.fillFast() - br2.fillFast() - - v := single[uint8(br1.value>>shift)].entry - v2 := single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off] = uint8(v >> 8) - buf[stream2][off] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+1] = uint8(v >> 8) - buf[stream2][off+1] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+2] = uint8(v >> 8) - buf[stream2][off+2] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+3] = uint8(v >> 8) - buf[stream2][off+3] = uint8(v2 >> 8) - } - - off += 4 - - if off == 0 { - if bufoff > dstEvery { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 1") - } - // There must at least be 3 buffers left. - if len(out)-bufoff < dstEvery*3 { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 2") - } - //copy(out, buf[0][:]) - //copy(out[dstEvery:], buf[1][:]) - //copy(out[dstEvery*2:], buf[2][:]) - *(*[bufoff]byte)(out) = buf[0] - *(*[bufoff]byte)(out[dstEvery:]) = buf[1] - *(*[bufoff]byte)(out[dstEvery*2:]) = buf[2] - *(*[bufoff]byte)(out[dstEvery*3:]) = buf[3] - out = out[bufoff:] - decoded += bufoff * 4 - } - } - if off > 0 { - ioff := int(off) - if len(out) < dstEvery*3+ioff { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 3") - } - copy(out, buf[0][:off]) - copy(out[dstEvery:], buf[1][:off]) - copy(out[dstEvery*2:], buf[2][:off]) - copy(out[dstEvery*3:], buf[3][:off]) - decoded += int(off) * 4 - out = out[off:] - } - - // Decode remaining. - // Decode remaining. - remainBytes := dstEvery - (decoded / 4) - for i := range br { - offset := dstEvery * i - endsAt := offset + remainBytes - if endsAt > len(out) { - endsAt = len(out) - } - br := &br[i] - bitsLeft := br.remaining() - for bitsLeft > 0 { - if br.finished() { - d.bufs.Put(buf) - return nil, io.ErrUnexpectedEOF - } - if br.bitsRead >= 56 { - if br.off >= 4 { - v := br.in[br.off-4:] - v = v[:4] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - br.value |= uint64(low) << (br.bitsRead - 32) - br.bitsRead -= 32 - br.off -= 4 - } else { - for br.off > 0 { - br.value |= uint64(br.in[br.off-1]) << (br.bitsRead - 8) - br.bitsRead -= 8 - br.off-- - } - } - } - // end inline... - if offset >= endsAt { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 4") - } - - // Read value and increment offset. - v := single[uint8(br.value>>shift)].entry - nBits := uint8(v) - br.advance(nBits) - bitsLeft -= uint(nBits) - out[offset] = uint8(v >> 8) - offset++ - } - if offset != endsAt { - d.bufs.Put(buf) - return nil, fmt.Errorf("corruption detected: short output block %d, end %d != %d", i, offset, endsAt) - } - decoded += offset - dstEvery*i - err = br.close() - if err != nil { - d.bufs.Put(buf) - return nil, err - } - } - d.bufs.Put(buf) - if dstSize != decoded { - return nil, errors.New("corruption detected: short output block") - } - return dst, nil -} - -// Decompress4X will decompress a 4X encoded stream. -// The length of the supplied input must match the end of a block exactly. -// The *capacity* of the dst slice must match the destination size of -// the uncompressed data exactly. -func (d *Decoder) decompress4X8bitExactly(dst, src []byte) ([]byte, error) { - var br [4]bitReaderBytes - start := 6 - for i := 0; i < 3; i++ { - length := int(src[i*2]) | (int(src[i*2+1]) << 8) - if start+length >= len(src) { - return nil, errors.New("truncated input (or invalid offset)") - } - err := br[i].init(src[start : start+length]) - if err != nil { - return nil, err - } - start += length - } - err := br[3].init(src[start:]) - if err != nil { - return nil, err - } - - // destination, offset to match first output - dstSize := cap(dst) - dst = dst[:dstSize] - out := dst - dstEvery := (dstSize + 3) / 4 - - const shift = 56 - const tlSize = 1 << 8 - single := d.dt.single[:tlSize] - - // Use temp table to avoid bound checks/append penalty. - buf := d.buffer() - var off uint8 - var decoded int - - // Decode 4 values from each decoder/loop. - const bufoff = 256 - for { - if br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4 { - break - } - - { - // Interleave 2 decodes. - const stream = 0 - const stream2 = 1 - br1 := &br[stream] - br2 := &br[stream2] - br1.fillFast() - br2.fillFast() - - v := single[uint8(br1.value>>shift)].entry - v2 := single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off] = uint8(v >> 8) - buf[stream2][off] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+1] = uint8(v >> 8) - buf[stream2][off+1] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+2] = uint8(v >> 8) - buf[stream2][off+2] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+3] = uint8(v >> 8) - buf[stream2][off+3] = uint8(v2 >> 8) - } - - { - const stream = 2 - const stream2 = 3 - br1 := &br[stream] - br2 := &br[stream2] - br1.fillFast() - br2.fillFast() - - v := single[uint8(br1.value>>shift)].entry - v2 := single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off] = uint8(v >> 8) - buf[stream2][off] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+1] = uint8(v >> 8) - buf[stream2][off+1] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+2] = uint8(v >> 8) - buf[stream2][off+2] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+3] = uint8(v >> 8) - buf[stream2][off+3] = uint8(v2 >> 8) - } - - off += 4 - - if off == 0 { - if bufoff > dstEvery { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 1") - } - // There must at least be 3 buffers left. - if len(out)-bufoff < dstEvery*3 { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 2") - } - - //copy(out, buf[0][:]) - //copy(out[dstEvery:], buf[1][:]) - //copy(out[dstEvery*2:], buf[2][:]) - // copy(out[dstEvery*3:], buf[3][:]) - *(*[bufoff]byte)(out) = buf[0] - *(*[bufoff]byte)(out[dstEvery:]) = buf[1] - *(*[bufoff]byte)(out[dstEvery*2:]) = buf[2] - *(*[bufoff]byte)(out[dstEvery*3:]) = buf[3] - out = out[bufoff:] - decoded += bufoff * 4 - } - } - if off > 0 { - ioff := int(off) - if len(out) < dstEvery*3+ioff { - return nil, errors.New("corruption detected: stream overrun 3") - } - copy(out, buf[0][:off]) - copy(out[dstEvery:], buf[1][:off]) - copy(out[dstEvery*2:], buf[2][:off]) - copy(out[dstEvery*3:], buf[3][:off]) - decoded += int(off) * 4 - out = out[off:] - } - - // Decode remaining. - remainBytes := dstEvery - (decoded / 4) - for i := range br { - offset := dstEvery * i - endsAt := offset + remainBytes - if endsAt > len(out) { - endsAt = len(out) - } - br := &br[i] - bitsLeft := br.remaining() - for bitsLeft > 0 { - if br.finished() { - d.bufs.Put(buf) - return nil, io.ErrUnexpectedEOF - } - if br.bitsRead >= 56 { - if br.off >= 4 { - v := br.in[br.off-4:] - v = v[:4] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - br.value |= uint64(low) << (br.bitsRead - 32) - br.bitsRead -= 32 - br.off -= 4 - } else { - for br.off > 0 { - br.value |= uint64(br.in[br.off-1]) << (br.bitsRead - 8) - br.bitsRead -= 8 - br.off-- - } - } - } - // end inline... - if offset >= endsAt { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 4") - } - - // Read value and increment offset. - v := single[br.peekByteFast()].entry - nBits := uint8(v) - br.advance(nBits) - bitsLeft -= uint(nBits) - out[offset] = uint8(v >> 8) - offset++ - } - if offset != endsAt { - d.bufs.Put(buf) - return nil, fmt.Errorf("corruption detected: short output block %d, end %d != %d", i, offset, endsAt) - } - - decoded += offset - dstEvery*i - err = br.close() - if err != nil { - d.bufs.Put(buf) - return nil, err - } - } - d.bufs.Put(buf) - if dstSize != decoded { - return nil, errors.New("corruption detected: short output block") - } - return dst, nil -} - -// matches will compare a decoding table to a coding table. -// Errors are written to the writer. -// Nothing will be written if table is ok. -func (s *Scratch) matches(ct cTable, w io.Writer) { - if s == nil || len(s.dt.single) == 0 { - return - } - dt := s.dt.single[:1<>8) == byte(sym) { - fmt.Fprintf(w, "symbol %x has decoder, but no encoder\n", sym) - errs++ - break - } - } - if errs == 0 { - broken-- - } - continue - } - // Unused bits in input - ub := tablelog - enc.nBits - top := enc.val << ub - // decoder looks at top bits. - dec := dt[top] - if uint8(dec.entry) != enc.nBits { - fmt.Fprintf(w, "symbol 0x%x bit size mismatch (enc: %d, dec:%d).\n", sym, enc.nBits, uint8(dec.entry)) - errs++ - } - if uint8(dec.entry>>8) != uint8(sym) { - fmt.Fprintf(w, "symbol 0x%x decoder output mismatch (enc: %d, dec:%d).\n", sym, sym, uint8(dec.entry>>8)) - errs++ - } - if errs > 0 { - fmt.Fprintf(w, "%d errros in base, stopping\n", errs) - continue - } - // Ensure that all combinations are covered. - for i := uint16(0); i < (1 << ub); i++ { - vval := top | i - dec := dt[vval] - if uint8(dec.entry) != enc.nBits { - fmt.Fprintf(w, "symbol 0x%x bit size mismatch (enc: %d, dec:%d).\n", vval, enc.nBits, uint8(dec.entry)) - errs++ - } - if uint8(dec.entry>>8) != uint8(sym) { - fmt.Fprintf(w, "symbol 0x%x decoder output mismatch (enc: %d, dec:%d).\n", vval, sym, uint8(dec.entry>>8)) - errs++ - } - if errs > 20 { - fmt.Fprintf(w, "%d errros, stopping\n", errs) - break - } - } - if errs == 0 { - ok++ - broken-- - } - } - if broken > 0 { - fmt.Fprintf(w, "%d broken, %d ok\n", broken, ok) - } -} diff --git a/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go b/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go deleted file mode 100644 index ba7e8e6b0..000000000 --- a/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go +++ /dev/null @@ -1,226 +0,0 @@ -//go:build amd64 && !appengine && !noasm && gc -// +build amd64,!appengine,!noasm,gc - -// This file contains the specialisation of Decoder.Decompress4X -// and Decoder.Decompress1X that use an asm implementation of thir main loops. -package huff0 - -import ( - "errors" - "fmt" - - "github.com/klauspost/compress/internal/cpuinfo" -) - -// decompress4x_main_loop_x86 is an x86 assembler implementation -// of Decompress4X when tablelog > 8. -// -//go:noescape -func decompress4x_main_loop_amd64(ctx *decompress4xContext) - -// decompress4x_8b_loop_x86 is an x86 assembler implementation -// of Decompress4X when tablelog <= 8 which decodes 4 entries -// per loop. -// -//go:noescape -func decompress4x_8b_main_loop_amd64(ctx *decompress4xContext) - -// fallback8BitSize is the size where using Go version is faster. -const fallback8BitSize = 800 - -type decompress4xContext struct { - pbr *[4]bitReaderShifted - peekBits uint8 - out *byte - dstEvery int - tbl *dEntrySingle - decoded int - limit *byte -} - -// Decompress4X will decompress a 4X encoded stream. -// The length of the supplied input must match the end of a block exactly. -// The *capacity* of the dst slice must match the destination size of -// the uncompressed data exactly. -func (d *Decoder) Decompress4X(dst, src []byte) ([]byte, error) { - if len(d.dt.single) == 0 { - return nil, errors.New("no table loaded") - } - if len(src) < 6+(4*1) { - return nil, errors.New("input too small") - } - - use8BitTables := d.actualTableLog <= 8 - if cap(dst) < fallback8BitSize && use8BitTables { - return d.decompress4X8bit(dst, src) - } - - var br [4]bitReaderShifted - // Decode "jump table" - start := 6 - for i := 0; i < 3; i++ { - length := int(src[i*2]) | (int(src[i*2+1]) << 8) - if start+length >= len(src) { - return nil, errors.New("truncated input (or invalid offset)") - } - err := br[i].init(src[start : start+length]) - if err != nil { - return nil, err - } - start += length - } - err := br[3].init(src[start:]) - if err != nil { - return nil, err - } - - // destination, offset to match first output - dstSize := cap(dst) - dst = dst[:dstSize] - out := dst - dstEvery := (dstSize + 3) / 4 - - const tlSize = 1 << tableLogMax - const tlMask = tlSize - 1 - single := d.dt.single[:tlSize] - - var decoded int - - if len(out) > 4*4 && !(br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4) { - ctx := decompress4xContext{ - pbr: &br, - peekBits: uint8((64 - d.actualTableLog) & 63), // see: bitReaderShifted.peekBitsFast() - out: &out[0], - dstEvery: dstEvery, - tbl: &single[0], - limit: &out[dstEvery-4], // Always stop decoding when first buffer gets here to avoid writing OOB on last. - } - if use8BitTables { - decompress4x_8b_main_loop_amd64(&ctx) - } else { - decompress4x_main_loop_amd64(&ctx) - } - - decoded = ctx.decoded - out = out[decoded/4:] - } - - // Decode remaining. - remainBytes := dstEvery - (decoded / 4) - for i := range br { - offset := dstEvery * i - endsAt := offset + remainBytes - if endsAt > len(out) { - endsAt = len(out) - } - br := &br[i] - bitsLeft := br.remaining() - for bitsLeft > 0 { - br.fill() - if offset >= endsAt { - return nil, errors.New("corruption detected: stream overrun 4") - } - - // Read value and increment offset. - val := br.peekBitsFast(d.actualTableLog) - v := single[val&tlMask].entry - nBits := uint8(v) - br.advance(nBits) - bitsLeft -= uint(nBits) - out[offset] = uint8(v >> 8) - offset++ - } - if offset != endsAt { - return nil, fmt.Errorf("corruption detected: short output block %d, end %d != %d", i, offset, endsAt) - } - decoded += offset - dstEvery*i - err = br.close() - if err != nil { - return nil, err - } - } - if dstSize != decoded { - return nil, errors.New("corruption detected: short output block") - } - return dst, nil -} - -// decompress4x_main_loop_x86 is an x86 assembler implementation -// of Decompress1X when tablelog > 8. -// -//go:noescape -func decompress1x_main_loop_amd64(ctx *decompress1xContext) - -// decompress4x_main_loop_x86 is an x86 with BMI2 assembler implementation -// of Decompress1X when tablelog > 8. -// -//go:noescape -func decompress1x_main_loop_bmi2(ctx *decompress1xContext) - -type decompress1xContext struct { - pbr *bitReaderShifted - peekBits uint8 - out *byte - outCap int - tbl *dEntrySingle - decoded int -} - -// Error reported by asm implementations -const error_max_decoded_size_exeeded = -1 - -// Decompress1X will decompress a 1X encoded stream. -// The cap of the output buffer will be the maximum decompressed size. -// The length of the supplied input must match the end of a block exactly. -func (d *Decoder) Decompress1X(dst, src []byte) ([]byte, error) { - if len(d.dt.single) == 0 { - return nil, errors.New("no table loaded") - } - var br bitReaderShifted - err := br.init(src) - if err != nil { - return dst, err - } - maxDecodedSize := cap(dst) - dst = dst[:maxDecodedSize] - - const tlSize = 1 << tableLogMax - const tlMask = tlSize - 1 - - if maxDecodedSize >= 4 { - ctx := decompress1xContext{ - pbr: &br, - out: &dst[0], - outCap: maxDecodedSize, - peekBits: uint8((64 - d.actualTableLog) & 63), // see: bitReaderShifted.peekBitsFast() - tbl: &d.dt.single[0], - } - - if cpuinfo.HasBMI2() { - decompress1x_main_loop_bmi2(&ctx) - } else { - decompress1x_main_loop_amd64(&ctx) - } - if ctx.decoded == error_max_decoded_size_exeeded { - return nil, ErrMaxDecodedSizeExceeded - } - - dst = dst[:ctx.decoded] - } - - // br < 8, so uint8 is fine - bitsLeft := uint8(br.off)*8 + 64 - br.bitsRead - for bitsLeft > 0 { - br.fill() - if len(dst) >= maxDecodedSize { - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - v := d.dt.single[br.peekBitsFast(d.actualTableLog)&tlMask] - nBits := uint8(v.entry) - br.advance(nBits) - bitsLeft -= nBits - dst = append(dst, uint8(v.entry>>8)) - } - return dst, br.close() -} diff --git a/vendor/github.com/klauspost/compress/huff0/decompress_amd64.s b/vendor/github.com/klauspost/compress/huff0/decompress_amd64.s deleted file mode 100644 index c4c7ab2d1..000000000 --- a/vendor/github.com/klauspost/compress/huff0/decompress_amd64.s +++ /dev/null @@ -1,830 +0,0 @@ -// Code generated by command: go run gen.go -out ../decompress_amd64.s -pkg=huff0. DO NOT EDIT. - -//go:build amd64 && !appengine && !noasm && gc - -// func decompress4x_main_loop_amd64(ctx *decompress4xContext) -TEXT ·decompress4x_main_loop_amd64(SB), $0-8 - // Preload values - MOVQ ctx+0(FP), AX - MOVBQZX 8(AX), DI - MOVQ 16(AX), BX - MOVQ 48(AX), SI - MOVQ 24(AX), R8 - MOVQ 32(AX), R9 - MOVQ (AX), R10 - - // Main loop -main_loop: - XORL DX, DX - CMPQ BX, SI - SETGE DL - - // br0.fillFast32() - MOVQ 32(R10), R11 - MOVBQZX 40(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill0 - MOVQ 24(R10), AX - SUBQ $0x20, R12 - SUBQ $0x04, AX - MOVQ (R10), R13 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (AX)(R13*1), R13 - MOVQ R12, CX - SHLQ CL, R13 - MOVQ AX, 24(R10) - ORQ R13, R11 - - // exhausted += (br0.off < 4) - CMPQ AX, $0x04 - ADCB $+0, DL - -skip_fill0: - // val0 := br0.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br0.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br0.peekTopBits(peekBits) - MOVQ DI, CX - MOVQ R11, R13 - SHRQ CL, R13 - - // v1 := table[val1&mask] - MOVW (R9)(R13*2), CX - - // br0.advance(uint8(v1.entry)) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // these two writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - MOVW AX, (BX) - - // update the bitreader structure - MOVQ R11, 32(R10) - MOVB R12, 40(R10) - - // br1.fillFast32() - MOVQ 80(R10), R11 - MOVBQZX 88(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill1 - MOVQ 72(R10), AX - SUBQ $0x20, R12 - SUBQ $0x04, AX - MOVQ 48(R10), R13 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (AX)(R13*1), R13 - MOVQ R12, CX - SHLQ CL, R13 - MOVQ AX, 72(R10) - ORQ R13, R11 - - // exhausted += (br1.off < 4) - CMPQ AX, $0x04 - ADCB $+0, DL - -skip_fill1: - // val0 := br1.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br1.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br1.peekTopBits(peekBits) - MOVQ DI, CX - MOVQ R11, R13 - SHRQ CL, R13 - - // v1 := table[val1&mask] - MOVW (R9)(R13*2), CX - - // br1.advance(uint8(v1.entry)) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // these two writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - MOVW AX, (BX)(R8*1) - - // update the bitreader structure - MOVQ R11, 80(R10) - MOVB R12, 88(R10) - - // br2.fillFast32() - MOVQ 128(R10), R11 - MOVBQZX 136(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill2 - MOVQ 120(R10), AX - SUBQ $0x20, R12 - SUBQ $0x04, AX - MOVQ 96(R10), R13 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (AX)(R13*1), R13 - MOVQ R12, CX - SHLQ CL, R13 - MOVQ AX, 120(R10) - ORQ R13, R11 - - // exhausted += (br2.off < 4) - CMPQ AX, $0x04 - ADCB $+0, DL - -skip_fill2: - // val0 := br2.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br2.peekTopBits(peekBits) - MOVQ DI, CX - MOVQ R11, R13 - SHRQ CL, R13 - - // v1 := table[val1&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v1.entry)) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // these two writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - MOVW AX, (BX)(R8*2) - - // update the bitreader structure - MOVQ R11, 128(R10) - MOVB R12, 136(R10) - - // br3.fillFast32() - MOVQ 176(R10), R11 - MOVBQZX 184(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill3 - MOVQ 168(R10), AX - SUBQ $0x20, R12 - SUBQ $0x04, AX - MOVQ 144(R10), R13 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (AX)(R13*1), R13 - MOVQ R12, CX - SHLQ CL, R13 - MOVQ AX, 168(R10) - ORQ R13, R11 - - // exhausted += (br3.off < 4) - CMPQ AX, $0x04 - ADCB $+0, DL - -skip_fill3: - // val0 := br3.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br3.peekTopBits(peekBits) - MOVQ DI, CX - MOVQ R11, R13 - SHRQ CL, R13 - - // v1 := table[val1&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v1.entry)) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // these two writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - LEAQ (R8)(R8*2), CX - MOVW AX, (BX)(CX*1) - - // update the bitreader structure - MOVQ R11, 176(R10) - MOVB R12, 184(R10) - ADDQ $0x02, BX - TESTB DL, DL - JZ main_loop - MOVQ ctx+0(FP), AX - SUBQ 16(AX), BX - SHLQ $0x02, BX - MOVQ BX, 40(AX) - RET - -// func decompress4x_8b_main_loop_amd64(ctx *decompress4xContext) -TEXT ·decompress4x_8b_main_loop_amd64(SB), $0-8 - // Preload values - MOVQ ctx+0(FP), CX - MOVBQZX 8(CX), DI - MOVQ 16(CX), BX - MOVQ 48(CX), SI - MOVQ 24(CX), R8 - MOVQ 32(CX), R9 - MOVQ (CX), R10 - - // Main loop -main_loop: - XORL DX, DX - CMPQ BX, SI - SETGE DL - - // br0.fillFast32() - MOVQ 32(R10), R11 - MOVBQZX 40(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill0 - MOVQ 24(R10), R13 - SUBQ $0x20, R12 - SUBQ $0x04, R13 - MOVQ (R10), R14 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (R13)(R14*1), R14 - MOVQ R12, CX - SHLQ CL, R14 - MOVQ R13, 24(R10) - ORQ R14, R11 - - // exhausted += (br0.off < 4) - CMPQ R13, $0x04 - ADCB $+0, DL - -skip_fill0: - // val0 := br0.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br0.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br0.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v1 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br0.advance(uint8(v1.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // val2 := br0.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v2 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br0.advance(uint8(v2.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // val3 := br0.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v3 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br0.advance(uint8(v3.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // these four writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - // out[id * dstEvery + 3] = uint8(v2.entry >> 8) - // out[id * dstEvery + 4] = uint8(v3.entry >> 8) - MOVL AX, (BX) - - // update the bitreader structure - MOVQ R11, 32(R10) - MOVB R12, 40(R10) - - // br1.fillFast32() - MOVQ 80(R10), R11 - MOVBQZX 88(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill1 - MOVQ 72(R10), R13 - SUBQ $0x20, R12 - SUBQ $0x04, R13 - MOVQ 48(R10), R14 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (R13)(R14*1), R14 - MOVQ R12, CX - SHLQ CL, R14 - MOVQ R13, 72(R10) - ORQ R14, R11 - - // exhausted += (br1.off < 4) - CMPQ R13, $0x04 - ADCB $+0, DL - -skip_fill1: - // val0 := br1.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br1.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br1.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v1 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br1.advance(uint8(v1.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // val2 := br1.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v2 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br1.advance(uint8(v2.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // val3 := br1.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v3 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br1.advance(uint8(v3.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // these four writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - // out[id * dstEvery + 3] = uint8(v2.entry >> 8) - // out[id * dstEvery + 4] = uint8(v3.entry >> 8) - MOVL AX, (BX)(R8*1) - - // update the bitreader structure - MOVQ R11, 80(R10) - MOVB R12, 88(R10) - - // br2.fillFast32() - MOVQ 128(R10), R11 - MOVBQZX 136(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill2 - MOVQ 120(R10), R13 - SUBQ $0x20, R12 - SUBQ $0x04, R13 - MOVQ 96(R10), R14 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (R13)(R14*1), R14 - MOVQ R12, CX - SHLQ CL, R14 - MOVQ R13, 120(R10) - ORQ R14, R11 - - // exhausted += (br2.off < 4) - CMPQ R13, $0x04 - ADCB $+0, DL - -skip_fill2: - // val0 := br2.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br2.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v1 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v1.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // val2 := br2.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v2 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v2.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // val3 := br2.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v3 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v3.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // these four writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - // out[id * dstEvery + 3] = uint8(v2.entry >> 8) - // out[id * dstEvery + 4] = uint8(v3.entry >> 8) - MOVL AX, (BX)(R8*2) - - // update the bitreader structure - MOVQ R11, 128(R10) - MOVB R12, 136(R10) - - // br3.fillFast32() - MOVQ 176(R10), R11 - MOVBQZX 184(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill3 - MOVQ 168(R10), R13 - SUBQ $0x20, R12 - SUBQ $0x04, R13 - MOVQ 144(R10), R14 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (R13)(R14*1), R14 - MOVQ R12, CX - SHLQ CL, R14 - MOVQ R13, 168(R10) - ORQ R14, R11 - - // exhausted += (br3.off < 4) - CMPQ R13, $0x04 - ADCB $+0, DL - -skip_fill3: - // val0 := br3.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br3.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v1 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v1.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // val2 := br3.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v2 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v2.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // val3 := br3.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v3 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v3.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // these four writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - // out[id * dstEvery + 3] = uint8(v2.entry >> 8) - // out[id * dstEvery + 4] = uint8(v3.entry >> 8) - LEAQ (R8)(R8*2), CX - MOVL AX, (BX)(CX*1) - - // update the bitreader structure - MOVQ R11, 176(R10) - MOVB R12, 184(R10) - ADDQ $0x04, BX - TESTB DL, DL - JZ main_loop - MOVQ ctx+0(FP), AX - SUBQ 16(AX), BX - SHLQ $0x02, BX - MOVQ BX, 40(AX) - RET - -// func decompress1x_main_loop_amd64(ctx *decompress1xContext) -TEXT ·decompress1x_main_loop_amd64(SB), $0-8 - MOVQ ctx+0(FP), CX - MOVQ 16(CX), DX - MOVQ 24(CX), BX - CMPQ BX, $0x04 - JB error_max_decoded_size_exceeded - LEAQ (DX)(BX*1), BX - MOVQ (CX), SI - MOVQ (SI), R8 - MOVQ 24(SI), R9 - MOVQ 32(SI), R10 - MOVBQZX 40(SI), R11 - MOVQ 32(CX), SI - MOVBQZX 8(CX), DI - JMP loop_condition - -main_loop: - // Check if we have room for 4 bytes in the output buffer - LEAQ 4(DX), CX - CMPQ CX, BX - JGE error_max_decoded_size_exceeded - - // Decode 4 values - CMPQ R11, $0x20 - JL bitReader_fillFast_1_end - SUBQ $0x20, R11 - SUBQ $0x04, R9 - MOVL (R8)(R9*1), R12 - MOVQ R11, CX - SHLQ CL, R12 - ORQ R12, R10 - -bitReader_fillFast_1_end: - MOVQ DI, CX - MOVQ R10, R12 - SHRQ CL, R12 - MOVW (SI)(R12*2), CX - MOVB CH, AL - MOVBQZX CL, CX - ADDQ CX, R11 - SHLQ CL, R10 - MOVQ DI, CX - MOVQ R10, R12 - SHRQ CL, R12 - MOVW (SI)(R12*2), CX - MOVB CH, AH - MOVBQZX CL, CX - ADDQ CX, R11 - SHLQ CL, R10 - BSWAPL AX - CMPQ R11, $0x20 - JL bitReader_fillFast_2_end - SUBQ $0x20, R11 - SUBQ $0x04, R9 - MOVL (R8)(R9*1), R12 - MOVQ R11, CX - SHLQ CL, R12 - ORQ R12, R10 - -bitReader_fillFast_2_end: - MOVQ DI, CX - MOVQ R10, R12 - SHRQ CL, R12 - MOVW (SI)(R12*2), CX - MOVB CH, AH - MOVBQZX CL, CX - ADDQ CX, R11 - SHLQ CL, R10 - MOVQ DI, CX - MOVQ R10, R12 - SHRQ CL, R12 - MOVW (SI)(R12*2), CX - MOVB CH, AL - MOVBQZX CL, CX - ADDQ CX, R11 - SHLQ CL, R10 - BSWAPL AX - - // Store the decoded values - MOVL AX, (DX) - ADDQ $0x04, DX - -loop_condition: - CMPQ R9, $0x08 - JGE main_loop - - // Update ctx structure - MOVQ ctx+0(FP), AX - SUBQ 16(AX), DX - MOVQ DX, 40(AX) - MOVQ (AX), AX - MOVQ R9, 24(AX) - MOVQ R10, 32(AX) - MOVB R11, 40(AX) - RET - - // Report error -error_max_decoded_size_exceeded: - MOVQ ctx+0(FP), AX - MOVQ $-1, CX - MOVQ CX, 40(AX) - RET - -// func decompress1x_main_loop_bmi2(ctx *decompress1xContext) -// Requires: BMI2 -TEXT ·decompress1x_main_loop_bmi2(SB), $0-8 - MOVQ ctx+0(FP), CX - MOVQ 16(CX), DX - MOVQ 24(CX), BX - CMPQ BX, $0x04 - JB error_max_decoded_size_exceeded - LEAQ (DX)(BX*1), BX - MOVQ (CX), SI - MOVQ (SI), R8 - MOVQ 24(SI), R9 - MOVQ 32(SI), R10 - MOVBQZX 40(SI), R11 - MOVQ 32(CX), SI - MOVBQZX 8(CX), DI - JMP loop_condition - -main_loop: - // Check if we have room for 4 bytes in the output buffer - LEAQ 4(DX), CX - CMPQ CX, BX - JGE error_max_decoded_size_exceeded - - // Decode 4 values - CMPQ R11, $0x20 - JL bitReader_fillFast_1_end - SUBQ $0x20, R11 - SUBQ $0x04, R9 - MOVL (R8)(R9*1), CX - SHLXQ R11, CX, CX - ORQ CX, R10 - -bitReader_fillFast_1_end: - SHRXQ DI, R10, CX - MOVW (SI)(CX*2), CX - MOVB CH, AL - MOVBQZX CL, CX - ADDQ CX, R11 - SHLXQ CX, R10, R10 - SHRXQ DI, R10, CX - MOVW (SI)(CX*2), CX - MOVB CH, AH - MOVBQZX CL, CX - ADDQ CX, R11 - SHLXQ CX, R10, R10 - BSWAPL AX - CMPQ R11, $0x20 - JL bitReader_fillFast_2_end - SUBQ $0x20, R11 - SUBQ $0x04, R9 - MOVL (R8)(R9*1), CX - SHLXQ R11, CX, CX - ORQ CX, R10 - -bitReader_fillFast_2_end: - SHRXQ DI, R10, CX - MOVW (SI)(CX*2), CX - MOVB CH, AH - MOVBQZX CL, CX - ADDQ CX, R11 - SHLXQ CX, R10, R10 - SHRXQ DI, R10, CX - MOVW (SI)(CX*2), CX - MOVB CH, AL - MOVBQZX CL, CX - ADDQ CX, R11 - SHLXQ CX, R10, R10 - BSWAPL AX - - // Store the decoded values - MOVL AX, (DX) - ADDQ $0x04, DX - -loop_condition: - CMPQ R9, $0x08 - JGE main_loop - - // Update ctx structure - MOVQ ctx+0(FP), AX - SUBQ 16(AX), DX - MOVQ DX, 40(AX) - MOVQ (AX), AX - MOVQ R9, 24(AX) - MOVQ R10, 32(AX) - MOVB R11, 40(AX) - RET - - // Report error -error_max_decoded_size_exceeded: - MOVQ ctx+0(FP), AX - MOVQ $-1, CX - MOVQ CX, 40(AX) - RET diff --git a/vendor/github.com/klauspost/compress/huff0/decompress_generic.go b/vendor/github.com/klauspost/compress/huff0/decompress_generic.go deleted file mode 100644 index 908c17de6..000000000 --- a/vendor/github.com/klauspost/compress/huff0/decompress_generic.go +++ /dev/null @@ -1,299 +0,0 @@ -//go:build !amd64 || appengine || !gc || noasm -// +build !amd64 appengine !gc noasm - -// This file contains a generic implementation of Decoder.Decompress4X. -package huff0 - -import ( - "errors" - "fmt" -) - -// Decompress4X will decompress a 4X encoded stream. -// The length of the supplied input must match the end of a block exactly. -// The *capacity* of the dst slice must match the destination size of -// the uncompressed data exactly. -func (d *Decoder) Decompress4X(dst, src []byte) ([]byte, error) { - if len(d.dt.single) == 0 { - return nil, errors.New("no table loaded") - } - if len(src) < 6+(4*1) { - return nil, errors.New("input too small") - } - if use8BitTables && d.actualTableLog <= 8 { - return d.decompress4X8bit(dst, src) - } - - var br [4]bitReaderShifted - // Decode "jump table" - start := 6 - for i := 0; i < 3; i++ { - length := int(src[i*2]) | (int(src[i*2+1]) << 8) - if start+length >= len(src) { - return nil, errors.New("truncated input (or invalid offset)") - } - err := br[i].init(src[start : start+length]) - if err != nil { - return nil, err - } - start += length - } - err := br[3].init(src[start:]) - if err != nil { - return nil, err - } - - // destination, offset to match first output - dstSize := cap(dst) - dst = dst[:dstSize] - out := dst - dstEvery := (dstSize + 3) / 4 - - const tlSize = 1 << tableLogMax - const tlMask = tlSize - 1 - single := d.dt.single[:tlSize] - - // Use temp table to avoid bound checks/append penalty. - buf := d.buffer() - var off uint8 - var decoded int - - // Decode 2 values from each decoder/loop. - const bufoff = 256 - for { - if br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4 { - break - } - - { - const stream = 0 - const stream2 = 1 - br[stream].fillFast() - br[stream2].fillFast() - - val := br[stream].peekBitsFast(d.actualTableLog) - val2 := br[stream2].peekBitsFast(d.actualTableLog) - v := single[val&tlMask] - v2 := single[val2&tlMask] - br[stream].advance(uint8(v.entry)) - br[stream2].advance(uint8(v2.entry)) - buf[stream][off] = uint8(v.entry >> 8) - buf[stream2][off] = uint8(v2.entry >> 8) - - val = br[stream].peekBitsFast(d.actualTableLog) - val2 = br[stream2].peekBitsFast(d.actualTableLog) - v = single[val&tlMask] - v2 = single[val2&tlMask] - br[stream].advance(uint8(v.entry)) - br[stream2].advance(uint8(v2.entry)) - buf[stream][off+1] = uint8(v.entry >> 8) - buf[stream2][off+1] = uint8(v2.entry >> 8) - } - - { - const stream = 2 - const stream2 = 3 - br[stream].fillFast() - br[stream2].fillFast() - - val := br[stream].peekBitsFast(d.actualTableLog) - val2 := br[stream2].peekBitsFast(d.actualTableLog) - v := single[val&tlMask] - v2 := single[val2&tlMask] - br[stream].advance(uint8(v.entry)) - br[stream2].advance(uint8(v2.entry)) - buf[stream][off] = uint8(v.entry >> 8) - buf[stream2][off] = uint8(v2.entry >> 8) - - val = br[stream].peekBitsFast(d.actualTableLog) - val2 = br[stream2].peekBitsFast(d.actualTableLog) - v = single[val&tlMask] - v2 = single[val2&tlMask] - br[stream].advance(uint8(v.entry)) - br[stream2].advance(uint8(v2.entry)) - buf[stream][off+1] = uint8(v.entry >> 8) - buf[stream2][off+1] = uint8(v2.entry >> 8) - } - - off += 2 - - if off == 0 { - if bufoff > dstEvery { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 1") - } - // There must at least be 3 buffers left. - if len(out)-bufoff < dstEvery*3 { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 2") - } - //copy(out, buf[0][:]) - //copy(out[dstEvery:], buf[1][:]) - //copy(out[dstEvery*2:], buf[2][:]) - //copy(out[dstEvery*3:], buf[3][:]) - *(*[bufoff]byte)(out) = buf[0] - *(*[bufoff]byte)(out[dstEvery:]) = buf[1] - *(*[bufoff]byte)(out[dstEvery*2:]) = buf[2] - *(*[bufoff]byte)(out[dstEvery*3:]) = buf[3] - out = out[bufoff:] - decoded += bufoff * 4 - } - } - if off > 0 { - ioff := int(off) - if len(out) < dstEvery*3+ioff { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 3") - } - copy(out, buf[0][:off]) - copy(out[dstEvery:], buf[1][:off]) - copy(out[dstEvery*2:], buf[2][:off]) - copy(out[dstEvery*3:], buf[3][:off]) - decoded += int(off) * 4 - out = out[off:] - } - - // Decode remaining. - remainBytes := dstEvery - (decoded / 4) - for i := range br { - offset := dstEvery * i - endsAt := offset + remainBytes - if endsAt > len(out) { - endsAt = len(out) - } - br := &br[i] - bitsLeft := br.remaining() - for bitsLeft > 0 { - br.fill() - if offset >= endsAt { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 4") - } - - // Read value and increment offset. - val := br.peekBitsFast(d.actualTableLog) - v := single[val&tlMask].entry - nBits := uint8(v) - br.advance(nBits) - bitsLeft -= uint(nBits) - out[offset] = uint8(v >> 8) - offset++ - } - if offset != endsAt { - d.bufs.Put(buf) - return nil, fmt.Errorf("corruption detected: short output block %d, end %d != %d", i, offset, endsAt) - } - decoded += offset - dstEvery*i - err = br.close() - if err != nil { - return nil, err - } - } - d.bufs.Put(buf) - if dstSize != decoded { - return nil, errors.New("corruption detected: short output block") - } - return dst, nil -} - -// Decompress1X will decompress a 1X encoded stream. -// The cap of the output buffer will be the maximum decompressed size. -// The length of the supplied input must match the end of a block exactly. -func (d *Decoder) Decompress1X(dst, src []byte) ([]byte, error) { - if len(d.dt.single) == 0 { - return nil, errors.New("no table loaded") - } - if use8BitTables && d.actualTableLog <= 8 { - return d.decompress1X8Bit(dst, src) - } - var br bitReaderShifted - err := br.init(src) - if err != nil { - return dst, err - } - maxDecodedSize := cap(dst) - dst = dst[:0] - - // Avoid bounds check by always having full sized table. - const tlSize = 1 << tableLogMax - const tlMask = tlSize - 1 - dt := d.dt.single[:tlSize] - - // Use temp table to avoid bound checks/append penalty. - bufs := d.buffer() - buf := &bufs[0] - var off uint8 - - for br.off >= 8 { - br.fillFast() - v := dt[br.peekBitsFast(d.actualTableLog)&tlMask] - br.advance(uint8(v.entry)) - buf[off+0] = uint8(v.entry >> 8) - - v = dt[br.peekBitsFast(d.actualTableLog)&tlMask] - br.advance(uint8(v.entry)) - buf[off+1] = uint8(v.entry >> 8) - - // Refill - br.fillFast() - - v = dt[br.peekBitsFast(d.actualTableLog)&tlMask] - br.advance(uint8(v.entry)) - buf[off+2] = uint8(v.entry >> 8) - - v = dt[br.peekBitsFast(d.actualTableLog)&tlMask] - br.advance(uint8(v.entry)) - buf[off+3] = uint8(v.entry >> 8) - - off += 4 - if off == 0 { - if len(dst)+256 > maxDecodedSize { - br.close() - d.bufs.Put(bufs) - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:]...) - } - } - - if len(dst)+int(off) > maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:off]...) - - // br < 8, so uint8 is fine - bitsLeft := uint8(br.off)*8 + 64 - br.bitsRead - for bitsLeft > 0 { - br.fill() - if false && br.bitsRead >= 32 { - if br.off >= 4 { - v := br.in[br.off-4:] - v = v[:4] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - br.value = (br.value << 32) | uint64(low) - br.bitsRead -= 32 - br.off -= 4 - } else { - for br.off > 0 { - br.value = (br.value << 8) | uint64(br.in[br.off-1]) - br.bitsRead -= 8 - br.off-- - } - } - } - if len(dst) >= maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - v := d.dt.single[br.peekBitsFast(d.actualTableLog)&tlMask] - nBits := uint8(v.entry) - br.advance(nBits) - bitsLeft -= nBits - dst = append(dst, uint8(v.entry>>8)) - } - d.bufs.Put(bufs) - return dst, br.close() -} diff --git a/vendor/github.com/klauspost/compress/huff0/huff0.go b/vendor/github.com/klauspost/compress/huff0/huff0.go deleted file mode 100644 index e8ad17ad0..000000000 --- a/vendor/github.com/klauspost/compress/huff0/huff0.go +++ /dev/null @@ -1,337 +0,0 @@ -// Package huff0 provides fast huffman encoding as used in zstd. -// -// See README.md at https://github.com/klauspost/compress/tree/master/huff0 for details. -package huff0 - -import ( - "errors" - "fmt" - "math" - "math/bits" - "sync" - - "github.com/klauspost/compress/fse" -) - -const ( - maxSymbolValue = 255 - - // zstandard limits tablelog to 11, see: - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#huffman-tree-description - tableLogMax = 11 - tableLogDefault = 11 - minTablelog = 5 - huffNodesLen = 512 - - // BlockSizeMax is maximum input size for a single block uncompressed. - BlockSizeMax = 1<<18 - 1 -) - -var ( - // ErrIncompressible is returned when input is judged to be too hard to compress. - ErrIncompressible = errors.New("input is not compressible") - - // ErrUseRLE is returned from the compressor when the input is a single byte value repeated. - ErrUseRLE = errors.New("input is single value repeated") - - // ErrTooBig is return if input is too large for a single block. - ErrTooBig = errors.New("input too big") - - // ErrMaxDecodedSizeExceeded is return if input is too large for a single block. - ErrMaxDecodedSizeExceeded = errors.New("maximum output size exceeded") -) - -type ReusePolicy uint8 - -const ( - // ReusePolicyAllow will allow reuse if it produces smaller output. - ReusePolicyAllow ReusePolicy = iota - - // ReusePolicyPrefer will re-use aggressively if possible. - // This will not check if a new table will produce smaller output, - // except if the current table is impossible to use or - // compressed output is bigger than input. - ReusePolicyPrefer - - // ReusePolicyNone will disable re-use of tables. - // This is slightly faster than ReusePolicyAllow but may produce larger output. - ReusePolicyNone - - // ReusePolicyMust must allow reuse and produce smaller output. - ReusePolicyMust -) - -type Scratch struct { - count [maxSymbolValue + 1]uint32 - - // Per block parameters. - // These can be used to override compression parameters of the block. - // Do not touch, unless you know what you are doing. - - // Out is output buffer. - // If the scratch is re-used before the caller is done processing the output, - // set this field to nil. - // Otherwise the output buffer will be re-used for next Compression/Decompression step - // and allocation will be avoided. - Out []byte - - // OutTable will contain the table data only, if a new table has been generated. - // Slice of the returned data. - OutTable []byte - - // OutData will contain the compressed data. - // Slice of the returned data. - OutData []byte - - // MaxDecodedSize will set the maximum allowed output size. - // This value will automatically be set to BlockSizeMax if not set. - // Decoders will return ErrMaxDecodedSizeExceeded is this limit is exceeded. - MaxDecodedSize int - - br byteReader - - // MaxSymbolValue will override the maximum symbol value of the next block. - MaxSymbolValue uint8 - - // TableLog will attempt to override the tablelog for the next block. - // Must be <= 11 and >= 5. - TableLog uint8 - - // Reuse will specify the reuse policy - Reuse ReusePolicy - - // WantLogLess allows to specify a log 2 reduction that should at least be achieved, - // otherwise the block will be returned as incompressible. - // The reduction should then at least be (input size >> WantLogLess) - // If WantLogLess == 0 any improvement will do. - WantLogLess uint8 - - symbolLen uint16 // Length of active part of the symbol table. - maxCount int // count of the most probable symbol - clearCount bool // clear count - actualTableLog uint8 // Selected tablelog. - prevTableLog uint8 // Tablelog for previous table - prevTable cTable // Table used for previous compression. - cTable cTable // compression table - dt dTable // decompression table - nodes []nodeElt - tmpOut [4][]byte - fse *fse.Scratch - decPool sync.Pool // *[4][256]byte buffers. - huffWeight [maxSymbolValue + 1]byte -} - -// TransferCTable will transfer the previously used compression table. -func (s *Scratch) TransferCTable(src *Scratch) { - if cap(s.prevTable) < len(src.prevTable) { - s.prevTable = make(cTable, 0, maxSymbolValue+1) - } - s.prevTable = s.prevTable[:len(src.prevTable)] - copy(s.prevTable, src.prevTable) - s.prevTableLog = src.prevTableLog -} - -func (s *Scratch) prepare(in []byte) (*Scratch, error) { - if len(in) > BlockSizeMax { - return nil, ErrTooBig - } - if s == nil { - s = &Scratch{} - } - if s.MaxSymbolValue == 0 { - s.MaxSymbolValue = maxSymbolValue - } - if s.TableLog == 0 { - s.TableLog = tableLogDefault - } - if s.TableLog > tableLogMax || s.TableLog < minTablelog { - return nil, fmt.Errorf(" invalid tableLog %d (%d -> %d)", s.TableLog, minTablelog, tableLogMax) - } - if s.MaxDecodedSize <= 0 || s.MaxDecodedSize > BlockSizeMax { - s.MaxDecodedSize = BlockSizeMax - } - if s.clearCount && s.maxCount == 0 { - for i := range s.count { - s.count[i] = 0 - } - s.clearCount = false - } - if cap(s.Out) == 0 { - s.Out = make([]byte, 0, len(in)) - } - s.Out = s.Out[:0] - - s.OutTable = nil - s.OutData = nil - if cap(s.nodes) < huffNodesLen+1 { - s.nodes = make([]nodeElt, 0, huffNodesLen+1) - } - s.nodes = s.nodes[:0] - if s.fse == nil { - s.fse = &fse.Scratch{} - } - s.br.init(in) - - return s, nil -} - -type cTable []cTableEntry - -func (c cTable) write(s *Scratch) error { - var ( - // precomputed conversion table - bitsToWeight [tableLogMax + 1]byte - huffLog = s.actualTableLog - // last weight is not saved. - maxSymbolValue = uint8(s.symbolLen - 1) - huffWeight = s.huffWeight[:256] - ) - const ( - maxFSETableLog = 6 - ) - // convert to weight - bitsToWeight[0] = 0 - for n := uint8(1); n < huffLog+1; n++ { - bitsToWeight[n] = huffLog + 1 - n - } - - // Acquire histogram for FSE. - hist := s.fse.Histogram() - hist = hist[:256] - for i := range hist[:16] { - hist[i] = 0 - } - for n := uint8(0); n < maxSymbolValue; n++ { - v := bitsToWeight[c[n].nBits] & 15 - huffWeight[n] = v - hist[v]++ - } - - // FSE compress if feasible. - if maxSymbolValue >= 2 { - huffMaxCnt := uint32(0) - huffMax := uint8(0) - for i, v := range hist[:16] { - if v == 0 { - continue - } - huffMax = byte(i) - if v > huffMaxCnt { - huffMaxCnt = v - } - } - s.fse.HistogramFinished(huffMax, int(huffMaxCnt)) - s.fse.TableLog = maxFSETableLog - b, err := fse.Compress(huffWeight[:maxSymbolValue], s.fse) - if err == nil && len(b) < int(s.symbolLen>>1) { - s.Out = append(s.Out, uint8(len(b))) - s.Out = append(s.Out, b...) - return nil - } - // Unable to compress (RLE/uncompressible) - } - // write raw values as 4-bits (max : 15) - if maxSymbolValue > (256 - 128) { - // should not happen : likely means source cannot be compressed - return ErrIncompressible - } - op := s.Out - // special case, pack weights 4 bits/weight. - op = append(op, 128|(maxSymbolValue-1)) - // be sure it doesn't cause msan issue in final combination - huffWeight[maxSymbolValue] = 0 - for n := uint16(0); n < uint16(maxSymbolValue); n += 2 { - op = append(op, (huffWeight[n]<<4)|huffWeight[n+1]) - } - s.Out = op - return nil -} - -func (c cTable) estTableSize(s *Scratch) (sz int, err error) { - var ( - // precomputed conversion table - bitsToWeight [tableLogMax + 1]byte - huffLog = s.actualTableLog - // last weight is not saved. - maxSymbolValue = uint8(s.symbolLen - 1) - huffWeight = s.huffWeight[:256] - ) - const ( - maxFSETableLog = 6 - ) - // convert to weight - bitsToWeight[0] = 0 - for n := uint8(1); n < huffLog+1; n++ { - bitsToWeight[n] = huffLog + 1 - n - } - - // Acquire histogram for FSE. - hist := s.fse.Histogram() - hist = hist[:256] - for i := range hist[:16] { - hist[i] = 0 - } - for n := uint8(0); n < maxSymbolValue; n++ { - v := bitsToWeight[c[n].nBits] & 15 - huffWeight[n] = v - hist[v]++ - } - - // FSE compress if feasible. - if maxSymbolValue >= 2 { - huffMaxCnt := uint32(0) - huffMax := uint8(0) - for i, v := range hist[:16] { - if v == 0 { - continue - } - huffMax = byte(i) - if v > huffMaxCnt { - huffMaxCnt = v - } - } - s.fse.HistogramFinished(huffMax, int(huffMaxCnt)) - s.fse.TableLog = maxFSETableLog - b, err := fse.Compress(huffWeight[:maxSymbolValue], s.fse) - if err == nil && len(b) < int(s.symbolLen>>1) { - sz += 1 + len(b) - return sz, nil - } - // Unable to compress (RLE/uncompressible) - } - // write raw values as 4-bits (max : 15) - if maxSymbolValue > (256 - 128) { - // should not happen : likely means source cannot be compressed - return 0, ErrIncompressible - } - // special case, pack weights 4 bits/weight. - sz += 1 + int(maxSymbolValue/2) - return sz, nil -} - -// estimateSize returns the estimated size in bytes of the input represented in the -// histogram supplied. -func (c cTable) estimateSize(hist []uint32) int { - nbBits := uint32(7) - for i, v := range c[:len(hist)] { - nbBits += uint32(v.nBits) * hist[i] - } - return int(nbBits >> 3) -} - -// minSize returns the minimum possible size considering the shannon limit. -func (s *Scratch) minSize(total int) int { - nbBits := float64(7) - fTotal := float64(total) - for _, v := range s.count[:s.symbolLen] { - n := float64(v) - if n > 0 { - nbBits += math.Log2(fTotal/n) * n - } - } - return int(nbBits) >> 3 -} - -func highBit32(val uint32) (n uint32) { - return uint32(bits.Len32(val) - 1) -} diff --git a/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo.go b/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo.go deleted file mode 100644 index 3954c5121..000000000 --- a/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo.go +++ /dev/null @@ -1,34 +0,0 @@ -// Package cpuinfo gives runtime info about the current CPU. -// -// This is a very limited module meant for use internally -// in this project. For more versatile solution check -// https://github.com/klauspost/cpuid. -package cpuinfo - -// HasBMI1 checks whether an x86 CPU supports the BMI1 extension. -func HasBMI1() bool { - return hasBMI1 -} - -// HasBMI2 checks whether an x86 CPU supports the BMI2 extension. -func HasBMI2() bool { - return hasBMI2 -} - -// DisableBMI2 will disable BMI2, for testing purposes. -// Call returned function to restore previous state. -func DisableBMI2() func() { - old := hasBMI2 - hasBMI2 = false - return func() { - hasBMI2 = old - } -} - -// HasBMI checks whether an x86 CPU supports both BMI1 and BMI2 extensions. -func HasBMI() bool { - return HasBMI1() && HasBMI2() -} - -var hasBMI1 bool -var hasBMI2 bool diff --git a/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.go b/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.go deleted file mode 100644 index e802579c4..000000000 --- a/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.go +++ /dev/null @@ -1,11 +0,0 @@ -//go:build amd64 && !appengine && !noasm && gc -// +build amd64,!appengine,!noasm,gc - -package cpuinfo - -// go:noescape -func x86extensions() (bmi1, bmi2 bool) - -func init() { - hasBMI1, hasBMI2 = x86extensions() -} diff --git a/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.s b/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.s deleted file mode 100644 index 4465fbe9e..000000000 --- a/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.s +++ /dev/null @@ -1,36 +0,0 @@ -// +build !appengine -// +build gc -// +build !noasm - -#include "textflag.h" -#include "funcdata.h" -#include "go_asm.h" - -TEXT ·x86extensions(SB), NOSPLIT, $0 - // 1. determine max EAX value - XORQ AX, AX - CPUID - - CMPQ AX, $7 - JB unsupported - - // 2. EAX = 7, ECX = 0 --- see Table 3-8 "Information Returned by CPUID Instruction" - MOVQ $7, AX - MOVQ $0, CX - CPUID - - BTQ $3, BX // bit 3 = BMI1 - SETCS AL - - BTQ $8, BX // bit 8 = BMI2 - SETCS AH - - MOVB AL, bmi1+0(FP) - MOVB AH, bmi2+1(FP) - RET - -unsupported: - XORQ AX, AX - MOVB AL, bmi1+0(FP) - MOVB AL, bmi2+1(FP) - RET diff --git a/vendor/github.com/klauspost/compress/internal/snapref/LICENSE b/vendor/github.com/klauspost/compress/internal/snapref/LICENSE deleted file mode 100644 index 6050c10f4..000000000 --- a/vendor/github.com/klauspost/compress/internal/snapref/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2011 The Snappy-Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/klauspost/compress/internal/snapref/decode.go b/vendor/github.com/klauspost/compress/internal/snapref/decode.go deleted file mode 100644 index 40796a49d..000000000 --- a/vendor/github.com/klauspost/compress/internal/snapref/decode.go +++ /dev/null @@ -1,264 +0,0 @@ -// Copyright 2011 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package snapref - -import ( - "encoding/binary" - "errors" - "io" -) - -var ( - // ErrCorrupt reports that the input is invalid. - ErrCorrupt = errors.New("snappy: corrupt input") - // ErrTooLarge reports that the uncompressed length is too large. - ErrTooLarge = errors.New("snappy: decoded block is too large") - // ErrUnsupported reports that the input isn't supported. - ErrUnsupported = errors.New("snappy: unsupported input") - - errUnsupportedLiteralLength = errors.New("snappy: unsupported literal length") -) - -// DecodedLen returns the length of the decoded block. -func DecodedLen(src []byte) (int, error) { - v, _, err := decodedLen(src) - return v, err -} - -// decodedLen returns the length of the decoded block and the number of bytes -// that the length header occupied. -func decodedLen(src []byte) (blockLen, headerLen int, err error) { - v, n := binary.Uvarint(src) - if n <= 0 || v > 0xffffffff { - return 0, 0, ErrCorrupt - } - - const wordSize = 32 << (^uint(0) >> 32 & 1) - if wordSize == 32 && v > 0x7fffffff { - return 0, 0, ErrTooLarge - } - return int(v), n, nil -} - -const ( - decodeErrCodeCorrupt = 1 - decodeErrCodeUnsupportedLiteralLength = 2 -) - -// Decode returns the decoded form of src. The returned slice may be a sub- -// slice of dst if dst was large enough to hold the entire decoded block. -// Otherwise, a newly allocated slice will be returned. -// -// The dst and src must not overlap. It is valid to pass a nil dst. -// -// Decode handles the Snappy block format, not the Snappy stream format. -func Decode(dst, src []byte) ([]byte, error) { - dLen, s, err := decodedLen(src) - if err != nil { - return nil, err - } - if dLen <= len(dst) { - dst = dst[:dLen] - } else { - dst = make([]byte, dLen) - } - switch decode(dst, src[s:]) { - case 0: - return dst, nil - case decodeErrCodeUnsupportedLiteralLength: - return nil, errUnsupportedLiteralLength - } - return nil, ErrCorrupt -} - -// NewReader returns a new Reader that decompresses from r, using the framing -// format described at -// https://github.com/google/snappy/blob/master/framing_format.txt -func NewReader(r io.Reader) *Reader { - return &Reader{ - r: r, - decoded: make([]byte, maxBlockSize), - buf: make([]byte, maxEncodedLenOfMaxBlockSize+checksumSize), - } -} - -// Reader is an io.Reader that can read Snappy-compressed bytes. -// -// Reader handles the Snappy stream format, not the Snappy block format. -type Reader struct { - r io.Reader - err error - decoded []byte - buf []byte - // decoded[i:j] contains decoded bytes that have not yet been passed on. - i, j int - readHeader bool -} - -// Reset discards any buffered data, resets all state, and switches the Snappy -// reader to read from r. This permits reusing a Reader rather than allocating -// a new one. -func (r *Reader) Reset(reader io.Reader) { - r.r = reader - r.err = nil - r.i = 0 - r.j = 0 - r.readHeader = false -} - -func (r *Reader) readFull(p []byte, allowEOF bool) (ok bool) { - if _, r.err = io.ReadFull(r.r, p); r.err != nil { - if r.err == io.ErrUnexpectedEOF || (r.err == io.EOF && !allowEOF) { - r.err = ErrCorrupt - } - return false - } - return true -} - -func (r *Reader) fill() error { - for r.i >= r.j { - if !r.readFull(r.buf[:4], true) { - return r.err - } - chunkType := r.buf[0] - if !r.readHeader { - if chunkType != chunkTypeStreamIdentifier { - r.err = ErrCorrupt - return r.err - } - r.readHeader = true - } - chunkLen := int(r.buf[1]) | int(r.buf[2])<<8 | int(r.buf[3])<<16 - if chunkLen > len(r.buf) { - r.err = ErrUnsupported - return r.err - } - - // The chunk types are specified at - // https://github.com/google/snappy/blob/master/framing_format.txt - switch chunkType { - case chunkTypeCompressedData: - // Section 4.2. Compressed data (chunk type 0x00). - if chunkLen < checksumSize { - r.err = ErrCorrupt - return r.err - } - buf := r.buf[:chunkLen] - if !r.readFull(buf, false) { - return r.err - } - checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 - buf = buf[checksumSize:] - - n, err := DecodedLen(buf) - if err != nil { - r.err = err - return r.err - } - if n > len(r.decoded) { - r.err = ErrCorrupt - return r.err - } - if _, err := Decode(r.decoded, buf); err != nil { - r.err = err - return r.err - } - if crc(r.decoded[:n]) != checksum { - r.err = ErrCorrupt - return r.err - } - r.i, r.j = 0, n - continue - - case chunkTypeUncompressedData: - // Section 4.3. Uncompressed data (chunk type 0x01). - if chunkLen < checksumSize { - r.err = ErrCorrupt - return r.err - } - buf := r.buf[:checksumSize] - if !r.readFull(buf, false) { - return r.err - } - checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 - // Read directly into r.decoded instead of via r.buf. - n := chunkLen - checksumSize - if n > len(r.decoded) { - r.err = ErrCorrupt - return r.err - } - if !r.readFull(r.decoded[:n], false) { - return r.err - } - if crc(r.decoded[:n]) != checksum { - r.err = ErrCorrupt - return r.err - } - r.i, r.j = 0, n - continue - - case chunkTypeStreamIdentifier: - // Section 4.1. Stream identifier (chunk type 0xff). - if chunkLen != len(magicBody) { - r.err = ErrCorrupt - return r.err - } - if !r.readFull(r.buf[:len(magicBody)], false) { - return r.err - } - for i := 0; i < len(magicBody); i++ { - if r.buf[i] != magicBody[i] { - r.err = ErrCorrupt - return r.err - } - } - continue - } - - if chunkType <= 0x7f { - // Section 4.5. Reserved unskippable chunks (chunk types 0x02-0x7f). - r.err = ErrUnsupported - return r.err - } - // Section 4.4 Padding (chunk type 0xfe). - // Section 4.6. Reserved skippable chunks (chunk types 0x80-0xfd). - if !r.readFull(r.buf[:chunkLen], false) { - return r.err - } - } - - return nil -} - -// Read satisfies the io.Reader interface. -func (r *Reader) Read(p []byte) (int, error) { - if r.err != nil { - return 0, r.err - } - - if err := r.fill(); err != nil { - return 0, err - } - - n := copy(p, r.decoded[r.i:r.j]) - r.i += n - return n, nil -} - -// ReadByte satisfies the io.ByteReader interface. -func (r *Reader) ReadByte() (byte, error) { - if r.err != nil { - return 0, r.err - } - - if err := r.fill(); err != nil { - return 0, err - } - - c := r.decoded[r.i] - r.i++ - return c, nil -} diff --git a/vendor/github.com/klauspost/compress/internal/snapref/decode_other.go b/vendor/github.com/klauspost/compress/internal/snapref/decode_other.go deleted file mode 100644 index 77395a6b8..000000000 --- a/vendor/github.com/klauspost/compress/internal/snapref/decode_other.go +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2016 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package snapref - -// decode writes the decoding of src to dst. It assumes that the varint-encoded -// length of the decompressed bytes has already been read, and that len(dst) -// equals that length. -// -// It returns 0 on success or a decodeErrCodeXxx error code on failure. -func decode(dst, src []byte) int { - var d, s, offset, length int - for s < len(src) { - switch src[s] & 0x03 { - case tagLiteral: - x := uint32(src[s] >> 2) - switch { - case x < 60: - s++ - case x == 60: - s += 2 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - x = uint32(src[s-1]) - case x == 61: - s += 3 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - x = uint32(src[s-2]) | uint32(src[s-1])<<8 - case x == 62: - s += 4 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16 - case x == 63: - s += 5 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24 - } - length = int(x) + 1 - if length <= 0 { - return decodeErrCodeUnsupportedLiteralLength - } - if length > len(dst)-d || length > len(src)-s { - return decodeErrCodeCorrupt - } - copy(dst[d:], src[s:s+length]) - d += length - s += length - continue - - case tagCopy1: - s += 2 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - length = 4 + int(src[s-2])>>2&0x7 - offset = int(uint32(src[s-2])&0xe0<<3 | uint32(src[s-1])) - - case tagCopy2: - s += 3 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - length = 1 + int(src[s-3])>>2 - offset = int(uint32(src[s-2]) | uint32(src[s-1])<<8) - - case tagCopy4: - s += 5 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - length = 1 + int(src[s-5])>>2 - offset = int(uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24) - } - - if offset <= 0 || d < offset || length > len(dst)-d { - return decodeErrCodeCorrupt - } - // Copy from an earlier sub-slice of dst to a later sub-slice. - // If no overlap, use the built-in copy: - if offset >= length { - copy(dst[d:d+length], dst[d-offset:]) - d += length - continue - } - - // Unlike the built-in copy function, this byte-by-byte copy always runs - // forwards, even if the slices overlap. Conceptually, this is: - // - // d += forwardCopy(dst[d:d+length], dst[d-offset:]) - // - // We align the slices into a and b and show the compiler they are the same size. - // This allows the loop to run without bounds checks. - a := dst[d : d+length] - b := dst[d-offset:] - b = b[:len(a)] - for i := range a { - a[i] = b[i] - } - d += length - } - if d != len(dst) { - return decodeErrCodeCorrupt - } - return 0 -} diff --git a/vendor/github.com/klauspost/compress/internal/snapref/encode.go b/vendor/github.com/klauspost/compress/internal/snapref/encode.go deleted file mode 100644 index 13c6040a5..000000000 --- a/vendor/github.com/klauspost/compress/internal/snapref/encode.go +++ /dev/null @@ -1,289 +0,0 @@ -// Copyright 2011 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package snapref - -import ( - "encoding/binary" - "errors" - "io" -) - -// Encode returns the encoded form of src. The returned slice may be a sub- -// slice of dst if dst was large enough to hold the entire encoded block. -// Otherwise, a newly allocated slice will be returned. -// -// The dst and src must not overlap. It is valid to pass a nil dst. -// -// Encode handles the Snappy block format, not the Snappy stream format. -func Encode(dst, src []byte) []byte { - if n := MaxEncodedLen(len(src)); n < 0 { - panic(ErrTooLarge) - } else if len(dst) < n { - dst = make([]byte, n) - } - - // The block starts with the varint-encoded length of the decompressed bytes. - d := binary.PutUvarint(dst, uint64(len(src))) - - for len(src) > 0 { - p := src - src = nil - if len(p) > maxBlockSize { - p, src = p[:maxBlockSize], p[maxBlockSize:] - } - if len(p) < minNonLiteralBlockSize { - d += emitLiteral(dst[d:], p) - } else { - d += encodeBlock(dst[d:], p) - } - } - return dst[:d] -} - -// inputMargin is the minimum number of extra input bytes to keep, inside -// encodeBlock's inner loop. On some architectures, this margin lets us -// implement a fast path for emitLiteral, where the copy of short (<= 16 byte) -// literals can be implemented as a single load to and store from a 16-byte -// register. That literal's actual length can be as short as 1 byte, so this -// can copy up to 15 bytes too much, but that's OK as subsequent iterations of -// the encoding loop will fix up the copy overrun, and this inputMargin ensures -// that we don't overrun the dst and src buffers. -const inputMargin = 16 - 1 - -// minNonLiteralBlockSize is the minimum size of the input to encodeBlock that -// could be encoded with a copy tag. This is the minimum with respect to the -// algorithm used by encodeBlock, not a minimum enforced by the file format. -// -// The encoded output must start with at least a 1 byte literal, as there are -// no previous bytes to copy. A minimal (1 byte) copy after that, generated -// from an emitCopy call in encodeBlock's main loop, would require at least -// another inputMargin bytes, for the reason above: we want any emitLiteral -// calls inside encodeBlock's main loop to use the fast path if possible, which -// requires being able to overrun by inputMargin bytes. Thus, -// minNonLiteralBlockSize equals 1 + 1 + inputMargin. -// -// The C++ code doesn't use this exact threshold, but it could, as discussed at -// https://groups.google.com/d/topic/snappy-compression/oGbhsdIJSJ8/discussion -// The difference between Go (2+inputMargin) and C++ (inputMargin) is purely an -// optimization. It should not affect the encoded form. This is tested by -// TestSameEncodingAsCppShortCopies. -const minNonLiteralBlockSize = 1 + 1 + inputMargin - -// MaxEncodedLen returns the maximum length of a snappy block, given its -// uncompressed length. -// -// It will return a negative value if srcLen is too large to encode. -func MaxEncodedLen(srcLen int) int { - n := uint64(srcLen) - if n > 0xffffffff { - return -1 - } - // Compressed data can be defined as: - // compressed := item* literal* - // item := literal* copy - // - // The trailing literal sequence has a space blowup of at most 62/60 - // since a literal of length 60 needs one tag byte + one extra byte - // for length information. - // - // Item blowup is trickier to measure. Suppose the "copy" op copies - // 4 bytes of data. Because of a special check in the encoding code, - // we produce a 4-byte copy only if the offset is < 65536. Therefore - // the copy op takes 3 bytes to encode, and this type of item leads - // to at most the 62/60 blowup for representing literals. - // - // Suppose the "copy" op copies 5 bytes of data. If the offset is big - // enough, it will take 5 bytes to encode the copy op. Therefore the - // worst case here is a one-byte literal followed by a five-byte copy. - // That is, 6 bytes of input turn into 7 bytes of "compressed" data. - // - // This last factor dominates the blowup, so the final estimate is: - n = 32 + n + n/6 - if n > 0xffffffff { - return -1 - } - return int(n) -} - -var errClosed = errors.New("snappy: Writer is closed") - -// NewWriter returns a new Writer that compresses to w. -// -// The Writer returned does not buffer writes. There is no need to Flush or -// Close such a Writer. -// -// Deprecated: the Writer returned is not suitable for many small writes, only -// for few large writes. Use NewBufferedWriter instead, which is efficient -// regardless of the frequency and shape of the writes, and remember to Close -// that Writer when done. -func NewWriter(w io.Writer) *Writer { - return &Writer{ - w: w, - obuf: make([]byte, obufLen), - } -} - -// NewBufferedWriter returns a new Writer that compresses to w, using the -// framing format described at -// https://github.com/google/snappy/blob/master/framing_format.txt -// -// The Writer returned buffers writes. Users must call Close to guarantee all -// data has been forwarded to the underlying io.Writer. They may also call -// Flush zero or more times before calling Close. -func NewBufferedWriter(w io.Writer) *Writer { - return &Writer{ - w: w, - ibuf: make([]byte, 0, maxBlockSize), - obuf: make([]byte, obufLen), - } -} - -// Writer is an io.Writer that can write Snappy-compressed bytes. -// -// Writer handles the Snappy stream format, not the Snappy block format. -type Writer struct { - w io.Writer - err error - - // ibuf is a buffer for the incoming (uncompressed) bytes. - // - // Its use is optional. For backwards compatibility, Writers created by the - // NewWriter function have ibuf == nil, do not buffer incoming bytes, and - // therefore do not need to be Flush'ed or Close'd. - ibuf []byte - - // obuf is a buffer for the outgoing (compressed) bytes. - obuf []byte - - // wroteStreamHeader is whether we have written the stream header. - wroteStreamHeader bool -} - -// Reset discards the writer's state and switches the Snappy writer to write to -// w. This permits reusing a Writer rather than allocating a new one. -func (w *Writer) Reset(writer io.Writer) { - w.w = writer - w.err = nil - if w.ibuf != nil { - w.ibuf = w.ibuf[:0] - } - w.wroteStreamHeader = false -} - -// Write satisfies the io.Writer interface. -func (w *Writer) Write(p []byte) (nRet int, errRet error) { - if w.ibuf == nil { - // Do not buffer incoming bytes. This does not perform or compress well - // if the caller of Writer.Write writes many small slices. This - // behavior is therefore deprecated, but still supported for backwards - // compatibility with code that doesn't explicitly Flush or Close. - return w.write(p) - } - - // The remainder of this method is based on bufio.Writer.Write from the - // standard library. - - for len(p) > (cap(w.ibuf)-len(w.ibuf)) && w.err == nil { - var n int - if len(w.ibuf) == 0 { - // Large write, empty buffer. - // Write directly from p to avoid copy. - n, _ = w.write(p) - } else { - n = copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p) - w.ibuf = w.ibuf[:len(w.ibuf)+n] - w.Flush() - } - nRet += n - p = p[n:] - } - if w.err != nil { - return nRet, w.err - } - n := copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p) - w.ibuf = w.ibuf[:len(w.ibuf)+n] - nRet += n - return nRet, nil -} - -func (w *Writer) write(p []byte) (nRet int, errRet error) { - if w.err != nil { - return 0, w.err - } - for len(p) > 0 { - obufStart := len(magicChunk) - if !w.wroteStreamHeader { - w.wroteStreamHeader = true - copy(w.obuf, magicChunk) - obufStart = 0 - } - - var uncompressed []byte - if len(p) > maxBlockSize { - uncompressed, p = p[:maxBlockSize], p[maxBlockSize:] - } else { - uncompressed, p = p, nil - } - checksum := crc(uncompressed) - - // Compress the buffer, discarding the result if the improvement - // isn't at least 12.5%. - compressed := Encode(w.obuf[obufHeaderLen:], uncompressed) - chunkType := uint8(chunkTypeCompressedData) - chunkLen := 4 + len(compressed) - obufEnd := obufHeaderLen + len(compressed) - if len(compressed) >= len(uncompressed)-len(uncompressed)/8 { - chunkType = chunkTypeUncompressedData - chunkLen = 4 + len(uncompressed) - obufEnd = obufHeaderLen - } - - // Fill in the per-chunk header that comes before the body. - w.obuf[len(magicChunk)+0] = chunkType - w.obuf[len(magicChunk)+1] = uint8(chunkLen >> 0) - w.obuf[len(magicChunk)+2] = uint8(chunkLen >> 8) - w.obuf[len(magicChunk)+3] = uint8(chunkLen >> 16) - w.obuf[len(magicChunk)+4] = uint8(checksum >> 0) - w.obuf[len(magicChunk)+5] = uint8(checksum >> 8) - w.obuf[len(magicChunk)+6] = uint8(checksum >> 16) - w.obuf[len(magicChunk)+7] = uint8(checksum >> 24) - - if _, err := w.w.Write(w.obuf[obufStart:obufEnd]); err != nil { - w.err = err - return nRet, err - } - if chunkType == chunkTypeUncompressedData { - if _, err := w.w.Write(uncompressed); err != nil { - w.err = err - return nRet, err - } - } - nRet += len(uncompressed) - } - return nRet, nil -} - -// Flush flushes the Writer to its underlying io.Writer. -func (w *Writer) Flush() error { - if w.err != nil { - return w.err - } - if len(w.ibuf) == 0 { - return nil - } - w.write(w.ibuf) - w.ibuf = w.ibuf[:0] - return w.err -} - -// Close calls Flush and then closes the Writer. -func (w *Writer) Close() error { - w.Flush() - ret := w.err - if w.err == nil { - w.err = errClosed - } - return ret -} diff --git a/vendor/github.com/klauspost/compress/internal/snapref/encode_other.go b/vendor/github.com/klauspost/compress/internal/snapref/encode_other.go deleted file mode 100644 index 2aa6a95a0..000000000 --- a/vendor/github.com/klauspost/compress/internal/snapref/encode_other.go +++ /dev/null @@ -1,250 +0,0 @@ -// Copyright 2016 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package snapref - -func load32(b []byte, i int) uint32 { - b = b[i : i+4 : len(b)] // Help the compiler eliminate bounds checks on the next line. - return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 -} - -func load64(b []byte, i int) uint64 { - b = b[i : i+8 : len(b)] // Help the compiler eliminate bounds checks on the next line. - return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | - uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 -} - -// emitLiteral writes a literal chunk and returns the number of bytes written. -// -// It assumes that: -// -// dst is long enough to hold the encoded bytes -// 1 <= len(lit) && len(lit) <= 65536 -func emitLiteral(dst, lit []byte) int { - i, n := 0, uint(len(lit)-1) - switch { - case n < 60: - dst[0] = uint8(n)<<2 | tagLiteral - i = 1 - case n < 1<<8: - dst[0] = 60<<2 | tagLiteral - dst[1] = uint8(n) - i = 2 - default: - dst[0] = 61<<2 | tagLiteral - dst[1] = uint8(n) - dst[2] = uint8(n >> 8) - i = 3 - } - return i + copy(dst[i:], lit) -} - -// emitCopy writes a copy chunk and returns the number of bytes written. -// -// It assumes that: -// -// dst is long enough to hold the encoded bytes -// 1 <= offset && offset <= 65535 -// 4 <= length && length <= 65535 -func emitCopy(dst []byte, offset, length int) int { - i := 0 - // The maximum length for a single tagCopy1 or tagCopy2 op is 64 bytes. The - // threshold for this loop is a little higher (at 68 = 64 + 4), and the - // length emitted down below is is a little lower (at 60 = 64 - 4), because - // it's shorter to encode a length 67 copy as a length 60 tagCopy2 followed - // by a length 7 tagCopy1 (which encodes as 3+2 bytes) than to encode it as - // a length 64 tagCopy2 followed by a length 3 tagCopy2 (which encodes as - // 3+3 bytes). The magic 4 in the 64±4 is because the minimum length for a - // tagCopy1 op is 4 bytes, which is why a length 3 copy has to be an - // encodes-as-3-bytes tagCopy2 instead of an encodes-as-2-bytes tagCopy1. - for length >= 68 { - // Emit a length 64 copy, encoded as 3 bytes. - dst[i+0] = 63<<2 | tagCopy2 - dst[i+1] = uint8(offset) - dst[i+2] = uint8(offset >> 8) - i += 3 - length -= 64 - } - if length > 64 { - // Emit a length 60 copy, encoded as 3 bytes. - dst[i+0] = 59<<2 | tagCopy2 - dst[i+1] = uint8(offset) - dst[i+2] = uint8(offset >> 8) - i += 3 - length -= 60 - } - if length >= 12 || offset >= 2048 { - // Emit the remaining copy, encoded as 3 bytes. - dst[i+0] = uint8(length-1)<<2 | tagCopy2 - dst[i+1] = uint8(offset) - dst[i+2] = uint8(offset >> 8) - return i + 3 - } - // Emit the remaining copy, encoded as 2 bytes. - dst[i+0] = uint8(offset>>8)<<5 | uint8(length-4)<<2 | tagCopy1 - dst[i+1] = uint8(offset) - return i + 2 -} - -func hash(u, shift uint32) uint32 { - return (u * 0x1e35a7bd) >> shift -} - -// EncodeBlockInto exposes encodeBlock but checks dst size. -func EncodeBlockInto(dst, src []byte) (d int) { - if MaxEncodedLen(len(src)) > len(dst) { - return 0 - } - - // encodeBlock breaks on too big blocks, so split. - for len(src) > 0 { - p := src - src = nil - if len(p) > maxBlockSize { - p, src = p[:maxBlockSize], p[maxBlockSize:] - } - if len(p) < minNonLiteralBlockSize { - d += emitLiteral(dst[d:], p) - } else { - d += encodeBlock(dst[d:], p) - } - } - return d -} - -// encodeBlock encodes a non-empty src to a guaranteed-large-enough dst. It -// assumes that the varint-encoded length of the decompressed bytes has already -// been written. -// -// It also assumes that: -// -// len(dst) >= MaxEncodedLen(len(src)) && -// minNonLiteralBlockSize <= len(src) && len(src) <= maxBlockSize -func encodeBlock(dst, src []byte) (d int) { - // Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive. - // The table element type is uint16, as s < sLimit and sLimit < len(src) - // and len(src) <= maxBlockSize and maxBlockSize == 65536. - const ( - maxTableSize = 1 << 14 - // tableMask is redundant, but helps the compiler eliminate bounds - // checks. - tableMask = maxTableSize - 1 - ) - shift := uint32(32 - 8) - for tableSize := 1 << 8; tableSize < maxTableSize && tableSize < len(src); tableSize *= 2 { - shift-- - } - // In Go, all array elements are zero-initialized, so there is no advantage - // to a smaller tableSize per se. However, it matches the C++ algorithm, - // and in the asm versions of this code, we can get away with zeroing only - // the first tableSize elements. - var table [maxTableSize]uint16 - - // sLimit is when to stop looking for offset/length copies. The inputMargin - // lets us use a fast path for emitLiteral in the main loop, while we are - // looking for copies. - sLimit := len(src) - inputMargin - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := 0 - - // The encoded form must start with a literal, as there are no previous - // bytes to copy, so we start looking for hash matches at s == 1. - s := 1 - nextHash := hash(load32(src, s), shift) - - for { - // Copied from the C++ snappy implementation: - // - // Heuristic match skipping: If 32 bytes are scanned with no matches - // found, start looking only at every other byte. If 32 more bytes are - // scanned (or skipped), look at every third byte, etc.. When a match - // is found, immediately go back to looking at every byte. This is a - // small loss (~5% performance, ~0.1% density) for compressible data - // due to more bookkeeping, but for non-compressible data (such as - // JPEG) it's a huge win since the compressor quickly "realizes" the - // data is incompressible and doesn't bother looking for matches - // everywhere. - // - // The "skip" variable keeps track of how many bytes there are since - // the last match; dividing it by 32 (ie. right-shifting by five) gives - // the number of bytes to move ahead for each iteration. - skip := 32 - - nextS := s - candidate := 0 - for { - s = nextS - bytesBetweenHashLookups := skip >> 5 - nextS = s + bytesBetweenHashLookups - skip += bytesBetweenHashLookups - if nextS > sLimit { - goto emitRemainder - } - candidate = int(table[nextHash&tableMask]) - table[nextHash&tableMask] = uint16(s) - nextHash = hash(load32(src, nextS), shift) - if load32(src, s) == load32(src, candidate) { - break - } - } - - // A 4-byte match has been found. We'll later see if more than 4 bytes - // match. But, prior to the match, src[nextEmit:s] are unmatched. Emit - // them as literal bytes. - d += emitLiteral(dst[d:], src[nextEmit:s]) - - // Call emitCopy, and then see if another emitCopy could be our next - // move. Repeat until we find no match for the input immediately after - // what was consumed by the last emitCopy call. - // - // If we exit this loop normally then we need to call emitLiteral next, - // though we don't yet know how big the literal will be. We handle that - // by proceeding to the next iteration of the main loop. We also can - // exit this loop via goto if we get close to exhausting the input. - for { - // Invariant: we have a 4-byte match at s, and no need to emit any - // literal bytes prior to s. - base := s - - // Extend the 4-byte match as long as possible. - // - // This is an inlined version of: - // s = extendMatch(src, candidate+4, s+4) - s += 4 - for i := candidate + 4; s < len(src) && src[i] == src[s]; i, s = i+1, s+1 { - } - - d += emitCopy(dst[d:], base-candidate, s-base) - nextEmit = s - if s >= sLimit { - goto emitRemainder - } - - // We could immediately start working at s now, but to improve - // compression we first update the hash table at s-1 and at s. If - // another emitCopy is not our next move, also calculate nextHash - // at s+1. At least on GOARCH=amd64, these three hash calculations - // are faster as one load64 call (with some shifts) instead of - // three load32 calls. - x := load64(src, s-1) - prevHash := hash(uint32(x>>0), shift) - table[prevHash&tableMask] = uint16(s - 1) - currHash := hash(uint32(x>>8), shift) - candidate = int(table[currHash&tableMask]) - table[currHash&tableMask] = uint16(s) - if uint32(x>>8) != load32(src, candidate) { - nextHash = hash(uint32(x>>16), shift) - s++ - break - } - } - } - -emitRemainder: - if nextEmit < len(src) { - d += emitLiteral(dst[d:], src[nextEmit:]) - } - return d -} diff --git a/vendor/github.com/klauspost/compress/internal/snapref/snappy.go b/vendor/github.com/klauspost/compress/internal/snapref/snappy.go deleted file mode 100644 index 34d01f4aa..000000000 --- a/vendor/github.com/klauspost/compress/internal/snapref/snappy.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2011 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package snapref implements the Snappy compression format. It aims for very -// high speeds and reasonable compression. -// -// There are actually two Snappy formats: block and stream. They are related, -// but different: trying to decompress block-compressed data as a Snappy stream -// will fail, and vice versa. The block format is the Decode and Encode -// functions and the stream format is the Reader and Writer types. -// -// The block format, the more common case, is used when the complete size (the -// number of bytes) of the original data is known upfront, at the time -// compression starts. The stream format, also known as the framing format, is -// for when that isn't always true. -// -// The canonical, C++ implementation is at https://github.com/google/snappy and -// it only implements the block format. -package snapref - -import ( - "hash/crc32" -) - -/* -Each encoded block begins with the varint-encoded length of the decoded data, -followed by a sequence of chunks. Chunks begin and end on byte boundaries. The -first byte of each chunk is broken into its 2 least and 6 most significant bits -called l and m: l ranges in [0, 4) and m ranges in [0, 64). l is the chunk tag. -Zero means a literal tag. All other values mean a copy tag. - -For literal tags: - - If m < 60, the next 1 + m bytes are literal bytes. - - Otherwise, let n be the little-endian unsigned integer denoted by the next - m - 59 bytes. The next 1 + n bytes after that are literal bytes. - -For copy tags, length bytes are copied from offset bytes ago, in the style of -Lempel-Ziv compression algorithms. In particular: - - For l == 1, the offset ranges in [0, 1<<11) and the length in [4, 12). - The length is 4 + the low 3 bits of m. The high 3 bits of m form bits 8-10 - of the offset. The next byte is bits 0-7 of the offset. - - For l == 2, the offset ranges in [0, 1<<16) and the length in [1, 65). - The length is 1 + m. The offset is the little-endian unsigned integer - denoted by the next 2 bytes. - - For l == 3, this tag is a legacy format that is no longer issued by most - encoders. Nonetheless, the offset ranges in [0, 1<<32) and the length in - [1, 65). The length is 1 + m. The offset is the little-endian unsigned - integer denoted by the next 4 bytes. -*/ -const ( - tagLiteral = 0x00 - tagCopy1 = 0x01 - tagCopy2 = 0x02 - tagCopy4 = 0x03 -) - -const ( - checksumSize = 4 - chunkHeaderSize = 4 - magicChunk = "\xff\x06\x00\x00" + magicBody - magicBody = "sNaPpY" - - // maxBlockSize is the maximum size of the input to encodeBlock. It is not - // part of the wire format per se, but some parts of the encoder assume - // that an offset fits into a uint16. - // - // Also, for the framing format (Writer type instead of Encode function), - // https://github.com/google/snappy/blob/master/framing_format.txt says - // that "the uncompressed data in a chunk must be no longer than 65536 - // bytes". - maxBlockSize = 65536 - - // maxEncodedLenOfMaxBlockSize equals MaxEncodedLen(maxBlockSize), but is - // hard coded to be a const instead of a variable, so that obufLen can also - // be a const. Their equivalence is confirmed by - // TestMaxEncodedLenOfMaxBlockSize. - maxEncodedLenOfMaxBlockSize = 76490 - - obufHeaderLen = len(magicChunk) + checksumSize + chunkHeaderSize - obufLen = obufHeaderLen + maxEncodedLenOfMaxBlockSize -) - -const ( - chunkTypeCompressedData = 0x00 - chunkTypeUncompressedData = 0x01 - chunkTypePadding = 0xfe - chunkTypeStreamIdentifier = 0xff -) - -var crcTable = crc32.MakeTable(crc32.Castagnoli) - -// crc implements the checksum specified in section 3 of -// https://github.com/google/snappy/blob/master/framing_format.txt -func crc(b []byte) uint32 { - c := crc32.Update(0, crcTable, b) - return uint32(c>>15|c<<17) + 0xa282ead8 -} diff --git a/vendor/github.com/klauspost/compress/s2sx.mod b/vendor/github.com/klauspost/compress/s2sx.mod deleted file mode 100644 index 2263853fc..000000000 --- a/vendor/github.com/klauspost/compress/s2sx.mod +++ /dev/null @@ -1,4 +0,0 @@ -module github.com/klauspost/compress - -go 1.16 - diff --git a/vendor/github.com/klauspost/compress/s2sx.sum b/vendor/github.com/klauspost/compress/s2sx.sum deleted file mode 100644 index e69de29bb..000000000 diff --git a/vendor/github.com/klauspost/compress/zstd/README.md b/vendor/github.com/klauspost/compress/zstd/README.md deleted file mode 100644 index bdd49c8b2..000000000 --- a/vendor/github.com/klauspost/compress/zstd/README.md +++ /dev/null @@ -1,441 +0,0 @@ -# zstd - -[Zstandard](https://facebook.github.io/zstd/) is a real-time compression algorithm, providing high compression ratios. -It offers a very wide range of compression / speed trade-off, while being backed by a very fast decoder. -A high performance compression algorithm is implemented. For now focused on speed. - -This package provides [compression](#Compressor) to and [decompression](#Decompressor) of Zstandard content. - -This package is pure Go and without use of "unsafe". - -The `zstd` package is provided as open source software using a Go standard license. - -Currently the package is heavily optimized for 64 bit processors and will be significantly slower on 32 bit processors. - -For seekable zstd streams, see [this excellent package](https://github.com/SaveTheRbtz/zstd-seekable-format-go). - -## Installation - -Install using `go get -u github.com/klauspost/compress`. The package is located in `github.com/klauspost/compress/zstd`. - -[![Go Reference](https://pkg.go.dev/badge/github.com/klauspost/compress/zstd.svg)](https://pkg.go.dev/github.com/klauspost/compress/zstd) - -## Compressor - -### Status: - -STABLE - there may always be subtle bugs, a wide variety of content has been tested and the library is actively -used by several projects. This library is being [fuzz-tested](https://github.com/klauspost/compress-fuzz) for all updates. - -There may still be specific combinations of data types/size/settings that could lead to edge cases, -so as always, testing is recommended. - -For now, a high speed (fastest) and medium-fast (default) compressor has been implemented. - -* The "Fastest" compression ratio is roughly equivalent to zstd level 1. -* The "Default" compression ratio is roughly equivalent to zstd level 3 (default). -* The "Better" compression ratio is roughly equivalent to zstd level 7. -* The "Best" compression ratio is roughly equivalent to zstd level 11. - -In terms of speed, it is typically 2x as fast as the stdlib deflate/gzip in its fastest mode. -The compression ratio compared to stdlib is around level 3, but usually 3x as fast. - - -### Usage - -An Encoder can be used for either compressing a stream via the -`io.WriteCloser` interface supported by the Encoder or as multiple independent -tasks via the `EncodeAll` function. -Smaller encodes are encouraged to use the EncodeAll function. -Use `NewWriter` to create a new instance that can be used for both. - -To create a writer with default options, do like this: - -```Go -// Compress input to output. -func Compress(in io.Reader, out io.Writer) error { - enc, err := zstd.NewWriter(out) - if err != nil { - return err - } - _, err = io.Copy(enc, in) - if err != nil { - enc.Close() - return err - } - return enc.Close() -} -``` - -Now you can encode by writing data to `enc`. The output will be finished writing when `Close()` is called. -Even if your encode fails, you should still call `Close()` to release any resources that may be held up. - -The above is fine for big encodes. However, whenever possible try to *reuse* the writer. - -To reuse the encoder, you can use the `Reset(io.Writer)` function to change to another output. -This will allow the encoder to reuse all resources and avoid wasteful allocations. - -Currently stream encoding has 'light' concurrency, meaning up to 2 goroutines can be working on part -of a stream. This is independent of the `WithEncoderConcurrency(n)`, but that is likely to change -in the future. So if you want to limit concurrency for future updates, specify the concurrency -you would like. - -If you would like stream encoding to be done without spawning async goroutines, use `WithEncoderConcurrency(1)` -which will compress input as each block is completed, blocking on writes until each has completed. - -You can specify your desired compression level using `WithEncoderLevel()` option. Currently only pre-defined -compression settings can be specified. - -#### Future Compatibility Guarantees - -This will be an evolving project. When using this package it is important to note that both the compression efficiency and speed may change. - -The goal will be to keep the default efficiency at the default zstd (level 3). -However the encoding should never be assumed to remain the same, -and you should not use hashes of compressed output for similarity checks. - -The Encoder can be assumed to produce the same output from the exact same code version. -However, the may be modes in the future that break this, -although they will not be enabled without an explicit option. - -This encoder is not designed to (and will probably never) output the exact same bitstream as the reference encoder. - -Also note, that the cgo decompressor currently does not [report all errors on invalid input](https://github.com/DataDog/zstd/issues/59), -[omits error checks](https://github.com/DataDog/zstd/issues/61), [ignores checksums](https://github.com/DataDog/zstd/issues/43) -and seems to ignore concatenated streams, even though [it is part of the spec](https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#frames). - -#### Blocks - -For compressing small blocks, the returned encoder has a function called `EncodeAll(src, dst []byte) []byte`. - -`EncodeAll` will encode all input in src and append it to dst. -This function can be called concurrently. -Each call will only run on a same goroutine as the caller. - -Encoded blocks can be concatenated and the result will be the combined input stream. -Data compressed with EncodeAll can be decoded with the Decoder, using either a stream or `DecodeAll`. - -Especially when encoding blocks you should take special care to reuse the encoder. -This will effectively make it run without allocations after a warmup period. -To make it run completely without allocations, supply a destination buffer with space for all content. - -```Go -import "github.com/klauspost/compress/zstd" - -// Create a writer that caches compressors. -// For this operation type we supply a nil Reader. -var encoder, _ = zstd.NewWriter(nil) - -// Compress a buffer. -// If you have a destination buffer, the allocation in the call can also be eliminated. -func Compress(src []byte) []byte { - return encoder.EncodeAll(src, make([]byte, 0, len(src))) -} -``` - -You can control the maximum number of concurrent encodes using the `WithEncoderConcurrency(n)` -option when creating the writer. - -Using the Encoder for both a stream and individual blocks concurrently is safe. - -### Performance - -I have collected some speed examples to compare speed and compression against other compressors. - -* `file` is the input file. -* `out` is the compressor used. `zskp` is this package. `zstd` is the Datadog cgo library. `gzstd/gzkp` is gzip standard and this library. -* `level` is the compression level used. For `zskp` level 1 is "fastest", level 2 is "default"; 3 is "better", 4 is "best". -* `insize`/`outsize` is the input/output size. -* `millis` is the number of milliseconds used for compression. -* `mb/s` is megabytes (2^20 bytes) per second. - -``` -Silesia Corpus: -http://sun.aei.polsl.pl/~sdeor/corpus/silesia.zip - -This package: -file out level insize outsize millis mb/s -silesia.tar zskp 1 211947520 73821326 634 318.47 -silesia.tar zskp 2 211947520 67655404 1508 133.96 -silesia.tar zskp 3 211947520 64746933 3000 67.37 -silesia.tar zskp 4 211947520 60073508 16926 11.94 - -cgo zstd: -silesia.tar zstd 1 211947520 73605392 543 371.56 -silesia.tar zstd 3 211947520 66793289 864 233.68 -silesia.tar zstd 6 211947520 62916450 1913 105.66 -silesia.tar zstd 9 211947520 60212393 5063 39.92 - -gzip, stdlib/this package: -silesia.tar gzstd 1 211947520 80007735 1498 134.87 -silesia.tar gzkp 1 211947520 80088272 1009 200.31 - -GOB stream of binary data. Highly compressible. -https://files.klauspost.com/compress/gob-stream.7z - -file out level insize outsize millis mb/s -gob-stream zskp 1 1911399616 233948096 3230 564.34 -gob-stream zskp 2 1911399616 203997694 4997 364.73 -gob-stream zskp 3 1911399616 173526523 13435 135.68 -gob-stream zskp 4 1911399616 162195235 47559 38.33 - -gob-stream zstd 1 1911399616 249810424 2637 691.26 -gob-stream zstd 3 1911399616 208192146 3490 522.31 -gob-stream zstd 6 1911399616 193632038 6687 272.56 -gob-stream zstd 9 1911399616 177620386 16175 112.70 - -gob-stream gzstd 1 1911399616 357382013 9046 201.49 -gob-stream gzkp 1 1911399616 359136669 4885 373.08 - -The test data for the Large Text Compression Benchmark is the first -10^9 bytes of the English Wikipedia dump on Mar. 3, 2006. -http://mattmahoney.net/dc/textdata.html - -file out level insize outsize millis mb/s -enwik9 zskp 1 1000000000 343833605 3687 258.64 -enwik9 zskp 2 1000000000 317001237 7672 124.29 -enwik9 zskp 3 1000000000 291915823 15923 59.89 -enwik9 zskp 4 1000000000 261710291 77697 12.27 - -enwik9 zstd 1 1000000000 358072021 3110 306.65 -enwik9 zstd 3 1000000000 313734672 4784 199.35 -enwik9 zstd 6 1000000000 295138875 10290 92.68 -enwik9 zstd 9 1000000000 278348700 28549 33.40 - -enwik9 gzstd 1 1000000000 382578136 8608 110.78 -enwik9 gzkp 1 1000000000 382781160 5628 169.45 - -Highly compressible JSON file. -https://files.klauspost.com/compress/github-june-2days-2019.json.zst - -file out level insize outsize millis mb/s -github-june-2days-2019.json zskp 1 6273951764 697439532 9789 611.17 -github-june-2days-2019.json zskp 2 6273951764 610876538 18553 322.49 -github-june-2days-2019.json zskp 3 6273951764 517662858 44186 135.41 -github-june-2days-2019.json zskp 4 6273951764 464617114 165373 36.18 - -github-june-2days-2019.json zstd 1 6273951764 766284037 8450 708.00 -github-june-2days-2019.json zstd 3 6273951764 661889476 10927 547.57 -github-june-2days-2019.json zstd 6 6273951764 642756859 22996 260.18 -github-june-2days-2019.json zstd 9 6273951764 601974523 52413 114.16 - -github-june-2days-2019.json gzstd 1 6273951764 1164397768 26793 223.32 -github-june-2days-2019.json gzkp 1 6273951764 1120631856 17693 338.16 - -VM Image, Linux mint with a few installed applications: -https://files.klauspost.com/compress/rawstudio-mint14.7z - -file out level insize outsize millis mb/s -rawstudio-mint14.tar zskp 1 8558382592 3718400221 18206 448.29 -rawstudio-mint14.tar zskp 2 8558382592 3326118337 37074 220.15 -rawstudio-mint14.tar zskp 3 8558382592 3163842361 87306 93.49 -rawstudio-mint14.tar zskp 4 8558382592 2970480650 783862 10.41 - -rawstudio-mint14.tar zstd 1 8558382592 3609250104 17136 476.27 -rawstudio-mint14.tar zstd 3 8558382592 3341679997 29262 278.92 -rawstudio-mint14.tar zstd 6 8558382592 3235846406 77904 104.77 -rawstudio-mint14.tar zstd 9 8558382592 3160778861 140946 57.91 - -rawstudio-mint14.tar gzstd 1 8558382592 3926234992 51345 158.96 -rawstudio-mint14.tar gzkp 1 8558382592 3960117298 36722 222.26 - -CSV data: -https://files.klauspost.com/compress/nyc-taxi-data-10M.csv.zst - -file out level insize outsize millis mb/s -nyc-taxi-data-10M.csv zskp 1 3325605752 641319332 9462 335.17 -nyc-taxi-data-10M.csv zskp 2 3325605752 588976126 17570 180.50 -nyc-taxi-data-10M.csv zskp 3 3325605752 529329260 32432 97.79 -nyc-taxi-data-10M.csv zskp 4 3325605752 474949772 138025 22.98 - -nyc-taxi-data-10M.csv zstd 1 3325605752 687399637 8233 385.18 -nyc-taxi-data-10M.csv zstd 3 3325605752 598514411 10065 315.07 -nyc-taxi-data-10M.csv zstd 6 3325605752 570522953 20038 158.27 -nyc-taxi-data-10M.csv zstd 9 3325605752 517554797 64565 49.12 - -nyc-taxi-data-10M.csv gzstd 1 3325605752 928654908 21270 149.11 -nyc-taxi-data-10M.csv gzkp 1 3325605752 922273214 13929 227.68 -``` - -## Decompressor - -Staus: STABLE - there may still be subtle bugs, but a wide variety of content has been tested. - -This library is being continuously [fuzz-tested](https://github.com/klauspost/compress-fuzz), -kindly supplied by [fuzzit.dev](https://fuzzit.dev/). -The main purpose of the fuzz testing is to ensure that it is not possible to crash the decoder, -or run it past its limits with ANY input provided. - -### Usage - -The package has been designed for two main usages, big streams of data and smaller in-memory buffers. -There are two main usages of the package for these. Both of them are accessed by creating a `Decoder`. - -For streaming use a simple setup could look like this: - -```Go -import "github.com/klauspost/compress/zstd" - -func Decompress(in io.Reader, out io.Writer) error { - d, err := zstd.NewReader(in) - if err != nil { - return err - } - defer d.Close() - - // Copy content... - _, err = io.Copy(out, d) - return err -} -``` - -It is important to use the "Close" function when you no longer need the Reader to stop running goroutines, -when running with default settings. -Goroutines will exit once an error has been returned, including `io.EOF` at the end of a stream. - -Streams are decoded concurrently in 4 asynchronous stages to give the best possible throughput. -However, if you prefer synchronous decompression, use `WithDecoderConcurrency(1)` which will decompress data -as it is being requested only. - -For decoding buffers, it could look something like this: - -```Go -import "github.com/klauspost/compress/zstd" - -// Create a reader that caches decompressors. -// For this operation type we supply a nil Reader. -var decoder, _ = zstd.NewReader(nil, zstd.WithDecoderConcurrency(0)) - -// Decompress a buffer. We don't supply a destination buffer, -// so it will be allocated by the decoder. -func Decompress(src []byte) ([]byte, error) { - return decoder.DecodeAll(src, nil) -} -``` - -Both of these cases should provide the functionality needed. -The decoder can be used for *concurrent* decompression of multiple buffers. -By default 4 decompressors will be created. - -It will only allow a certain number of concurrent operations to run. -To tweak that yourself use the `WithDecoderConcurrency(n)` option when creating the decoder. -It is possible to use `WithDecoderConcurrency(0)` to create GOMAXPROCS decoders. - -### Dictionaries - -Data compressed with [dictionaries](https://github.com/facebook/zstd#the-case-for-small-data-compression) can be decompressed. - -Dictionaries are added individually to Decoders. -Dictionaries are generated by the `zstd --train` command and contains an initial state for the decoder. -To add a dictionary use the `WithDecoderDicts(dicts ...[]byte)` option with the dictionary data. -Several dictionaries can be added at once. - -The dictionary will be used automatically for the data that specifies them. -A re-used Decoder will still contain the dictionaries registered. - -When registering multiple dictionaries with the same ID, the last one will be used. - -It is possible to use dictionaries when compressing data. - -To enable a dictionary use `WithEncoderDict(dict []byte)`. Here only one dictionary will be used -and it will likely be used even if it doesn't improve compression. - -The used dictionary must be used to decompress the content. - -For any real gains, the dictionary should be built with similar data. -If an unsuitable dictionary is used the output may be slightly larger than using no dictionary. -Use the [zstd commandline tool](https://github.com/facebook/zstd/releases) to build a dictionary from sample data. -For information see [zstd dictionary information](https://github.com/facebook/zstd#the-case-for-small-data-compression). - -For now there is a fixed startup performance penalty for compressing content with dictionaries. -This will likely be improved over time. Just be aware to test performance when implementing. - -### Allocation-less operation - -The decoder has been designed to operate without allocations after a warmup. - -This means that you should *store* the decoder for best performance. -To re-use a stream decoder, use the `Reset(r io.Reader) error` to switch to another stream. -A decoder can safely be re-used even if the previous stream failed. - -To release the resources, you must call the `Close()` function on a decoder. -After this it can *no longer be reused*, but all running goroutines will be stopped. -So you *must* use this if you will no longer need the Reader. - -For decompressing smaller buffers a single decoder can be used. -When decoding buffers, you can supply a destination slice with length 0 and your expected capacity. -In this case no unneeded allocations should be made. - -### Concurrency - -The buffer decoder does everything on the same goroutine and does nothing concurrently. -It can however decode several buffers concurrently. Use `WithDecoderConcurrency(n)` to limit that. - -The stream decoder will create goroutines that: - -1) Reads input and splits the input into blocks. -2) Decompression of literals. -3) Decompression of sequences. -4) Reconstruction of output stream. - -So effectively this also means the decoder will "read ahead" and prepare data to always be available for output. - -The concurrency level will, for streams, determine how many blocks ahead the compression will start. - -Since "blocks" are quite dependent on the output of the previous block stream decoding will only have limited concurrency. - -In practice this means that concurrency is often limited to utilizing about 3 cores effectively. - -### Benchmarks - -The first two are streaming decodes and the last are smaller inputs. - -Running on AMD Ryzen 9 3950X 16-Core Processor. AMD64 assembly used. - -``` -BenchmarkDecoderSilesia-32 5 206878840 ns/op 1024.50 MB/s 49808 B/op 43 allocs/op -BenchmarkDecoderEnwik9-32 1 1271809000 ns/op 786.28 MB/s 72048 B/op 52 allocs/op - -Concurrent blocks, performance: - -BenchmarkDecoder_DecodeAllParallel/kppkn.gtb.zst-32 67356 17857 ns/op 10321.96 MB/s 22.48 pct 102 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/geo.protodata.zst-32 266656 4421 ns/op 26823.21 MB/s 11.89 pct 19 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/plrabn12.txt.zst-32 20992 56842 ns/op 8477.17 MB/s 39.90 pct 754 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/lcet10.txt.zst-32 27456 43932 ns/op 9714.01 MB/s 33.27 pct 524 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/asyoulik.txt.zst-32 78432 15047 ns/op 8319.15 MB/s 40.34 pct 66 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/alice29.txt.zst-32 65800 18436 ns/op 8249.63 MB/s 37.75 pct 88 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/html_x_4.zst-32 102993 11523 ns/op 35546.09 MB/s 3.637 pct 143 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/paper-100k.pdf.zst-32 1000000 1070 ns/op 95720.98 MB/s 80.53 pct 3 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/fireworks.jpeg.zst-32 749802 1752 ns/op 70272.35 MB/s 100.0 pct 5 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/urls.10K.zst-32 22640 52934 ns/op 13263.37 MB/s 26.25 pct 1014 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/html.zst-32 226412 5232 ns/op 19572.27 MB/s 14.49 pct 20 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/comp-data.bin.zst-32 923041 1276 ns/op 3194.71 MB/s 31.26 pct 0 B/op 0 allocs/op -``` - -This reflects the performance around May 2022, but this may be out of date. - -## Zstd inside ZIP files - -It is possible to use zstandard to compress individual files inside zip archives. -While this isn't widely supported it can be useful for internal files. - -To support the compression and decompression of these files you must register a compressor and decompressor. - -It is highly recommended registering the (de)compressors on individual zip Reader/Writer and NOT -use the global registration functions. The main reason for this is that 2 registrations from -different packages will result in a panic. - -It is a good idea to only have a single compressor and decompressor, since they can be used for multiple zip -files concurrently, and using a single instance will allow reusing some resources. - -See [this example](https://pkg.go.dev/github.com/klauspost/compress/zstd#example-ZipCompressor) for -how to compress and decompress files inside zip archives. - -# Contributions - -Contributions are always welcome. -For new features/fixes, remember to add tests and for performance enhancements include benchmarks. - -For general feedback and experience reports, feel free to open an issue or write me on [Twitter](https://twitter.com/sh0dan). - -This package includes the excellent [`github.com/cespare/xxhash`](https://github.com/cespare/xxhash) package Copyright (c) 2016 Caleb Spare. diff --git a/vendor/github.com/klauspost/compress/zstd/bitreader.go b/vendor/github.com/klauspost/compress/zstd/bitreader.go deleted file mode 100644 index 25ca98394..000000000 --- a/vendor/github.com/klauspost/compress/zstd/bitreader.go +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "encoding/binary" - "errors" - "fmt" - "io" - "math/bits" -) - -// bitReader reads a bitstream in reverse. -// The last set bit indicates the start of the stream and is used -// for aligning the input. -type bitReader struct { - in []byte - value uint64 // Maybe use [16]byte, but shifting is awkward. - bitsRead uint8 -} - -// init initializes and resets the bit reader. -func (b *bitReader) init(in []byte) error { - if len(in) < 1 { - return errors.New("corrupt stream: too short") - } - b.in = in - // The highest bit of the last byte indicates where to start - v := in[len(in)-1] - if v == 0 { - return errors.New("corrupt stream, did not find end of stream") - } - b.bitsRead = 64 - b.value = 0 - if len(in) >= 8 { - b.fillFastStart() - } else { - b.fill() - b.fill() - } - b.bitsRead += 8 - uint8(highBits(uint32(v))) - return nil -} - -// getBits will return n bits. n can be 0. -func (b *bitReader) getBits(n uint8) int { - if n == 0 /*|| b.bitsRead >= 64 */ { - return 0 - } - return int(b.get32BitsFast(n)) -} - -// get32BitsFast requires that at least one bit is requested every time. -// There are no checks if the buffer is filled. -func (b *bitReader) get32BitsFast(n uint8) uint32 { - const regMask = 64 - 1 - v := uint32((b.value << (b.bitsRead & regMask)) >> ((regMask + 1 - n) & regMask)) - b.bitsRead += n - return v -} - -// fillFast() will make sure at least 32 bits are available. -// There must be at least 4 bytes available. -func (b *bitReader) fillFast() { - if b.bitsRead < 32 { - return - } - v := b.in[len(b.in)-4:] - b.in = b.in[:len(b.in)-4] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - b.value = (b.value << 32) | uint64(low) - b.bitsRead -= 32 -} - -// fillFastStart() assumes the bitreader is empty and there is at least 8 bytes to read. -func (b *bitReader) fillFastStart() { - v := b.in[len(b.in)-8:] - b.in = b.in[:len(b.in)-8] - b.value = binary.LittleEndian.Uint64(v) - b.bitsRead = 0 -} - -// fill() will make sure at least 32 bits are available. -func (b *bitReader) fill() { - if b.bitsRead < 32 { - return - } - if len(b.in) >= 4 { - v := b.in[len(b.in)-4:] - b.in = b.in[:len(b.in)-4] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - b.value = (b.value << 32) | uint64(low) - b.bitsRead -= 32 - return - } - - b.bitsRead -= uint8(8 * len(b.in)) - for len(b.in) > 0 { - b.value = (b.value << 8) | uint64(b.in[len(b.in)-1]) - b.in = b.in[:len(b.in)-1] - } -} - -// finished returns true if all bits have been read from the bit stream. -func (b *bitReader) finished() bool { - return len(b.in) == 0 && b.bitsRead >= 64 -} - -// overread returns true if more bits have been requested than is on the stream. -func (b *bitReader) overread() bool { - return b.bitsRead > 64 -} - -// remain returns the number of bits remaining. -func (b *bitReader) remain() uint { - return 8*uint(len(b.in)) + 64 - uint(b.bitsRead) -} - -// close the bitstream and returns an error if out-of-buffer reads occurred. -func (b *bitReader) close() error { - // Release reference. - b.in = nil - if !b.finished() { - return fmt.Errorf("%d extra bits on block, should be 0", b.remain()) - } - if b.bitsRead > 64 { - return io.ErrUnexpectedEOF - } - return nil -} - -func highBits(val uint32) (n uint32) { - return uint32(bits.Len32(val) - 1) -} diff --git a/vendor/github.com/klauspost/compress/zstd/bitwriter.go b/vendor/github.com/klauspost/compress/zstd/bitwriter.go deleted file mode 100644 index 1952f175b..000000000 --- a/vendor/github.com/klauspost/compress/zstd/bitwriter.go +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright 2018 Klaus Post. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. - -package zstd - -// bitWriter will write bits. -// First bit will be LSB of the first byte of output. -type bitWriter struct { - bitContainer uint64 - nBits uint8 - out []byte -} - -// bitMask16 is bitmasks. Has extra to avoid bounds check. -var bitMask16 = [32]uint16{ - 0, 1, 3, 7, 0xF, 0x1F, - 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, - 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, 0xFFFF, - 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, - 0xFFFF, 0xFFFF} /* up to 16 bits */ - -var bitMask32 = [32]uint32{ - 0, 1, 3, 7, 0xF, 0x1F, 0x3F, 0x7F, 0xFF, - 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, - 0x1ffff, 0x3ffff, 0x7FFFF, 0xfFFFF, 0x1fFFFF, 0x3fFFFF, 0x7fFFFF, 0xffFFFF, - 0x1ffFFFF, 0x3ffFFFF, 0x7ffFFFF, 0xfffFFFF, 0x1fffFFFF, 0x3fffFFFF, 0x7fffFFFF, -} // up to 32 bits - -// addBits16NC will add up to 16 bits. -// It will not check if there is space for them, -// so the caller must ensure that it has flushed recently. -func (b *bitWriter) addBits16NC(value uint16, bits uint8) { - b.bitContainer |= uint64(value&bitMask16[bits&31]) << (b.nBits & 63) - b.nBits += bits -} - -// addBits32NC will add up to 31 bits. -// It will not check if there is space for them, -// so the caller must ensure that it has flushed recently. -func (b *bitWriter) addBits32NC(value uint32, bits uint8) { - b.bitContainer |= uint64(value&bitMask32[bits&31]) << (b.nBits & 63) - b.nBits += bits -} - -// addBits64NC will add up to 64 bits. -// There must be space for 32 bits. -func (b *bitWriter) addBits64NC(value uint64, bits uint8) { - if bits <= 31 { - b.addBits32Clean(uint32(value), bits) - return - } - b.addBits32Clean(uint32(value), 32) - b.flush32() - b.addBits32Clean(uint32(value>>32), bits-32) -} - -// addBits32Clean will add up to 32 bits. -// It will not check if there is space for them. -// The input must not contain more bits than specified. -func (b *bitWriter) addBits32Clean(value uint32, bits uint8) { - b.bitContainer |= uint64(value) << (b.nBits & 63) - b.nBits += bits -} - -// addBits16Clean will add up to 16 bits. value may not contain more set bits than indicated. -// It will not check if there is space for them, so the caller must ensure that it has flushed recently. -func (b *bitWriter) addBits16Clean(value uint16, bits uint8) { - b.bitContainer |= uint64(value) << (b.nBits & 63) - b.nBits += bits -} - -// flush32 will flush out, so there are at least 32 bits available for writing. -func (b *bitWriter) flush32() { - if b.nBits < 32 { - return - } - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - byte(b.bitContainer>>16), - byte(b.bitContainer>>24)) - b.nBits -= 32 - b.bitContainer >>= 32 -} - -// flushAlign will flush remaining full bytes and align to next byte boundary. -func (b *bitWriter) flushAlign() { - nbBytes := (b.nBits + 7) >> 3 - for i := uint8(0); i < nbBytes; i++ { - b.out = append(b.out, byte(b.bitContainer>>(i*8))) - } - b.nBits = 0 - b.bitContainer = 0 -} - -// close will write the alignment bit and write the final byte(s) -// to the output. -func (b *bitWriter) close() { - // End mark - b.addBits16Clean(1, 1) - // flush until next byte. - b.flushAlign() -} - -// reset and continue writing by appending to out. -func (b *bitWriter) reset(out []byte) { - b.bitContainer = 0 - b.nBits = 0 - b.out = out -} diff --git a/vendor/github.com/klauspost/compress/zstd/blockdec.go b/vendor/github.com/klauspost/compress/zstd/blockdec.go deleted file mode 100644 index 9f17ce601..000000000 --- a/vendor/github.com/klauspost/compress/zstd/blockdec.go +++ /dev/null @@ -1,726 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "bytes" - "encoding/binary" - "errors" - "fmt" - "hash/crc32" - "io" - "os" - "path/filepath" - "sync" - - "github.com/klauspost/compress/huff0" - "github.com/klauspost/compress/zstd/internal/xxhash" -) - -type blockType uint8 - -//go:generate stringer -type=blockType,literalsBlockType,seqCompMode,tableIndex - -const ( - blockTypeRaw blockType = iota - blockTypeRLE - blockTypeCompressed - blockTypeReserved -) - -type literalsBlockType uint8 - -const ( - literalsBlockRaw literalsBlockType = iota - literalsBlockRLE - literalsBlockCompressed - literalsBlockTreeless -) - -const ( - // maxCompressedBlockSize is the biggest allowed compressed block size (128KB) - maxCompressedBlockSize = 128 << 10 - - compressedBlockOverAlloc = 16 - maxCompressedBlockSizeAlloc = 128<<10 + compressedBlockOverAlloc - - // Maximum possible block size (all Raw+Uncompressed). - maxBlockSize = (1 << 21) - 1 - - maxMatchLen = 131074 - maxSequences = 0x7f00 + 0xffff - - // We support slightly less than the reference decoder to be able to - // use ints on 32 bit archs. - maxOffsetBits = 30 -) - -var ( - huffDecoderPool = sync.Pool{New: func() interface{} { - return &huff0.Scratch{} - }} - - fseDecoderPool = sync.Pool{New: func() interface{} { - return &fseDecoder{} - }} -) - -type blockDec struct { - // Raw source data of the block. - data []byte - dataStorage []byte - - // Destination of the decoded data. - dst []byte - - // Buffer for literals data. - literalBuf []byte - - // Window size of the block. - WindowSize uint64 - - err error - - // Check against this crc, if hasCRC is true. - checkCRC uint32 - hasCRC bool - - // Frame to use for singlethreaded decoding. - // Should not be used by the decoder itself since parent may be another frame. - localFrame *frameDec - - sequence []seqVals - - async struct { - newHist *history - literals []byte - seqData []byte - seqSize int // Size of uncompressed sequences - fcs uint64 - } - - // Block is RLE, this is the size. - RLESize uint32 - - Type blockType - - // Is this the last block of a frame? - Last bool - - // Use less memory - lowMem bool -} - -func (b *blockDec) String() string { - if b == nil { - return "" - } - return fmt.Sprintf("Steam Size: %d, Type: %v, Last: %t, Window: %d", len(b.data), b.Type, b.Last, b.WindowSize) -} - -func newBlockDec(lowMem bool) *blockDec { - b := blockDec{ - lowMem: lowMem, - } - return &b -} - -// reset will reset the block. -// Input must be a start of a block and will be at the end of the block when returned. -func (b *blockDec) reset(br byteBuffer, windowSize uint64) error { - b.WindowSize = windowSize - tmp, err := br.readSmall(3) - if err != nil { - println("Reading block header:", err) - return err - } - bh := uint32(tmp[0]) | (uint32(tmp[1]) << 8) | (uint32(tmp[2]) << 16) - b.Last = bh&1 != 0 - b.Type = blockType((bh >> 1) & 3) - // find size. - cSize := int(bh >> 3) - maxSize := maxCompressedBlockSizeAlloc - switch b.Type { - case blockTypeReserved: - return ErrReservedBlockType - case blockTypeRLE: - if cSize > maxCompressedBlockSize || cSize > int(b.WindowSize) { - if debugDecoder { - printf("rle block too big: csize:%d block: %+v\n", uint64(cSize), b) - } - return ErrWindowSizeExceeded - } - b.RLESize = uint32(cSize) - if b.lowMem { - maxSize = cSize - } - cSize = 1 - case blockTypeCompressed: - if debugDecoder { - println("Data size on stream:", cSize) - } - b.RLESize = 0 - maxSize = maxCompressedBlockSizeAlloc - if windowSize < maxCompressedBlockSize && b.lowMem { - maxSize = int(windowSize) + compressedBlockOverAlloc - } - if cSize > maxCompressedBlockSize || uint64(cSize) > b.WindowSize { - if debugDecoder { - printf("compressed block too big: csize:%d block: %+v\n", uint64(cSize), b) - } - return ErrCompressedSizeTooBig - } - // Empty compressed blocks must at least be 2 bytes - // for Literals_Block_Type and one for Sequences_Section_Header. - if cSize < 2 { - return ErrBlockTooSmall - } - case blockTypeRaw: - if cSize > maxCompressedBlockSize || cSize > int(b.WindowSize) { - if debugDecoder { - printf("rle block too big: csize:%d block: %+v\n", uint64(cSize), b) - } - return ErrWindowSizeExceeded - } - - b.RLESize = 0 - // We do not need a destination for raw blocks. - maxSize = -1 - default: - panic("Invalid block type") - } - - // Read block data. - if _, ok := br.(*byteBuf); !ok && cap(b.dataStorage) < cSize { - // byteBuf doesn't need a destination buffer. - if b.lowMem || cSize > maxCompressedBlockSize { - b.dataStorage = make([]byte, 0, cSize+compressedBlockOverAlloc) - } else { - b.dataStorage = make([]byte, 0, maxCompressedBlockSizeAlloc) - } - } - b.data, err = br.readBig(cSize, b.dataStorage) - if err != nil { - if debugDecoder { - println("Reading block:", err, "(", cSize, ")", len(b.data)) - printf("%T", br) - } - return err - } - if cap(b.dst) <= maxSize { - b.dst = make([]byte, 0, maxSize+1) - } - return nil -} - -// sendEOF will make the decoder send EOF on this frame. -func (b *blockDec) sendErr(err error) { - b.Last = true - b.Type = blockTypeReserved - b.err = err -} - -// Close will release resources. -// Closed blockDec cannot be reset. -func (b *blockDec) Close() { -} - -// decodeBuf -func (b *blockDec) decodeBuf(hist *history) error { - switch b.Type { - case blockTypeRLE: - if cap(b.dst) < int(b.RLESize) { - if b.lowMem { - b.dst = make([]byte, b.RLESize) - } else { - b.dst = make([]byte, maxCompressedBlockSize) - } - } - b.dst = b.dst[:b.RLESize] - v := b.data[0] - for i := range b.dst { - b.dst[i] = v - } - hist.appendKeep(b.dst) - return nil - case blockTypeRaw: - hist.appendKeep(b.data) - return nil - case blockTypeCompressed: - saved := b.dst - // Append directly to history - if hist.ignoreBuffer == 0 { - b.dst = hist.b - hist.b = nil - } else { - b.dst = b.dst[:0] - } - err := b.decodeCompressed(hist) - if debugDecoder { - println("Decompressed to total", len(b.dst), "bytes, hash:", xxhash.Sum64(b.dst), "error:", err) - } - if hist.ignoreBuffer == 0 { - hist.b = b.dst - b.dst = saved - } else { - hist.appendKeep(b.dst) - } - return err - case blockTypeReserved: - // Used for returning errors. - return b.err - default: - panic("Invalid block type") - } -} - -func (b *blockDec) decodeLiterals(in []byte, hist *history) (remain []byte, err error) { - // There must be at least one byte for Literals_Block_Type and one for Sequences_Section_Header - if len(in) < 2 { - return in, ErrBlockTooSmall - } - - litType := literalsBlockType(in[0] & 3) - var litRegenSize int - var litCompSize int - sizeFormat := (in[0] >> 2) & 3 - var fourStreams bool - var literals []byte - switch litType { - case literalsBlockRaw, literalsBlockRLE: - switch sizeFormat { - case 0, 2: - // Regenerated_Size uses 5 bits (0-31). Literals_Section_Header uses 1 byte. - litRegenSize = int(in[0] >> 3) - in = in[1:] - case 1: - // Regenerated_Size uses 12 bits (0-4095). Literals_Section_Header uses 2 bytes. - litRegenSize = int(in[0]>>4) + (int(in[1]) << 4) - in = in[2:] - case 3: - // Regenerated_Size uses 20 bits (0-1048575). Literals_Section_Header uses 3 bytes. - if len(in) < 3 { - println("too small: litType:", litType, " sizeFormat", sizeFormat, len(in)) - return in, ErrBlockTooSmall - } - litRegenSize = int(in[0]>>4) + (int(in[1]) << 4) + (int(in[2]) << 12) - in = in[3:] - } - case literalsBlockCompressed, literalsBlockTreeless: - switch sizeFormat { - case 0, 1: - // Both Regenerated_Size and Compressed_Size use 10 bits (0-1023). - if len(in) < 3 { - println("too small: litType:", litType, " sizeFormat", sizeFormat, len(in)) - return in, ErrBlockTooSmall - } - n := uint64(in[0]>>4) + (uint64(in[1]) << 4) + (uint64(in[2]) << 12) - litRegenSize = int(n & 1023) - litCompSize = int(n >> 10) - fourStreams = sizeFormat == 1 - in = in[3:] - case 2: - fourStreams = true - if len(in) < 4 { - println("too small: litType:", litType, " sizeFormat", sizeFormat, len(in)) - return in, ErrBlockTooSmall - } - n := uint64(in[0]>>4) + (uint64(in[1]) << 4) + (uint64(in[2]) << 12) + (uint64(in[3]) << 20) - litRegenSize = int(n & 16383) - litCompSize = int(n >> 14) - in = in[4:] - case 3: - fourStreams = true - if len(in) < 5 { - println("too small: litType:", litType, " sizeFormat", sizeFormat, len(in)) - return in, ErrBlockTooSmall - } - n := uint64(in[0]>>4) + (uint64(in[1]) << 4) + (uint64(in[2]) << 12) + (uint64(in[3]) << 20) + (uint64(in[4]) << 28) - litRegenSize = int(n & 262143) - litCompSize = int(n >> 18) - in = in[5:] - } - } - if debugDecoder { - println("literals type:", litType, "litRegenSize:", litRegenSize, "litCompSize:", litCompSize, "sizeFormat:", sizeFormat, "4X:", fourStreams) - } - if litRegenSize > int(b.WindowSize) || litRegenSize > maxCompressedBlockSize { - return in, ErrWindowSizeExceeded - } - - switch litType { - case literalsBlockRaw: - if len(in) < litRegenSize { - println("too small: litType:", litType, " sizeFormat", sizeFormat, "remain:", len(in), "want:", litRegenSize) - return in, ErrBlockTooSmall - } - literals = in[:litRegenSize] - in = in[litRegenSize:] - //printf("Found %d uncompressed literals\n", litRegenSize) - case literalsBlockRLE: - if len(in) < 1 { - println("too small: litType:", litType, " sizeFormat", sizeFormat, "remain:", len(in), "want:", 1) - return in, ErrBlockTooSmall - } - if cap(b.literalBuf) < litRegenSize { - if b.lowMem { - b.literalBuf = make([]byte, litRegenSize, litRegenSize+compressedBlockOverAlloc) - } else { - b.literalBuf = make([]byte, litRegenSize, maxCompressedBlockSize+compressedBlockOverAlloc) - } - } - literals = b.literalBuf[:litRegenSize] - v := in[0] - for i := range literals { - literals[i] = v - } - in = in[1:] - if debugDecoder { - printf("Found %d RLE compressed literals\n", litRegenSize) - } - case literalsBlockTreeless: - if len(in) < litCompSize { - println("too small: litType:", litType, " sizeFormat", sizeFormat, "remain:", len(in), "want:", litCompSize) - return in, ErrBlockTooSmall - } - // Store compressed literals, so we defer decoding until we get history. - literals = in[:litCompSize] - in = in[litCompSize:] - if debugDecoder { - printf("Found %d compressed literals\n", litCompSize) - } - huff := hist.huffTree - if huff == nil { - return in, errors.New("literal block was treeless, but no history was defined") - } - // Ensure we have space to store it. - if cap(b.literalBuf) < litRegenSize { - if b.lowMem { - b.literalBuf = make([]byte, 0, litRegenSize+compressedBlockOverAlloc) - } else { - b.literalBuf = make([]byte, 0, maxCompressedBlockSize+compressedBlockOverAlloc) - } - } - var err error - // Use our out buffer. - huff.MaxDecodedSize = litRegenSize - if fourStreams { - literals, err = huff.Decoder().Decompress4X(b.literalBuf[:0:litRegenSize], literals) - } else { - literals, err = huff.Decoder().Decompress1X(b.literalBuf[:0:litRegenSize], literals) - } - // Make sure we don't leak our literals buffer - if err != nil { - println("decompressing literals:", err) - return in, err - } - if len(literals) != litRegenSize { - return in, fmt.Errorf("literal output size mismatch want %d, got %d", litRegenSize, len(literals)) - } - - case literalsBlockCompressed: - if len(in) < litCompSize { - println("too small: litType:", litType, " sizeFormat", sizeFormat, "remain:", len(in), "want:", litCompSize) - return in, ErrBlockTooSmall - } - literals = in[:litCompSize] - in = in[litCompSize:] - // Ensure we have space to store it. - if cap(b.literalBuf) < litRegenSize { - if b.lowMem { - b.literalBuf = make([]byte, 0, litRegenSize+compressedBlockOverAlloc) - } else { - b.literalBuf = make([]byte, 0, maxCompressedBlockSize+compressedBlockOverAlloc) - } - } - huff := hist.huffTree - if huff == nil || (hist.dict != nil && huff == hist.dict.litEnc) { - huff = huffDecoderPool.Get().(*huff0.Scratch) - if huff == nil { - huff = &huff0.Scratch{} - } - } - var err error - if debugDecoder { - println("huff table input:", len(literals), "CRC:", crc32.ChecksumIEEE(literals)) - } - huff, literals, err = huff0.ReadTable(literals, huff) - if err != nil { - println("reading huffman table:", err) - return in, err - } - hist.huffTree = huff - huff.MaxDecodedSize = litRegenSize - // Use our out buffer. - if fourStreams { - literals, err = huff.Decoder().Decompress4X(b.literalBuf[:0:litRegenSize], literals) - } else { - literals, err = huff.Decoder().Decompress1X(b.literalBuf[:0:litRegenSize], literals) - } - if err != nil { - println("decoding compressed literals:", err) - return in, err - } - // Make sure we don't leak our literals buffer - if len(literals) != litRegenSize { - return in, fmt.Errorf("literal output size mismatch want %d, got %d", litRegenSize, len(literals)) - } - // Re-cap to get extra size. - literals = b.literalBuf[:len(literals)] - if debugDecoder { - printf("Decompressed %d literals into %d bytes\n", litCompSize, litRegenSize) - } - } - hist.decoders.literals = literals - return in, nil -} - -// decodeCompressed will start decompressing a block. -func (b *blockDec) decodeCompressed(hist *history) error { - in := b.data - in, err := b.decodeLiterals(in, hist) - if err != nil { - return err - } - err = b.prepareSequences(in, hist) - if err != nil { - return err - } - if hist.decoders.nSeqs == 0 { - b.dst = append(b.dst, hist.decoders.literals...) - return nil - } - before := len(hist.decoders.out) - err = hist.decoders.decodeSync(hist.b[hist.ignoreBuffer:]) - if err != nil { - return err - } - if hist.decoders.maxSyncLen > 0 { - hist.decoders.maxSyncLen += uint64(before) - hist.decoders.maxSyncLen -= uint64(len(hist.decoders.out)) - } - b.dst = hist.decoders.out - hist.recentOffsets = hist.decoders.prevOffset - return nil -} - -func (b *blockDec) prepareSequences(in []byte, hist *history) (err error) { - if debugDecoder { - printf("prepareSequences: %d byte(s) input\n", len(in)) - } - // Decode Sequences - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#sequences-section - if len(in) < 1 { - return ErrBlockTooSmall - } - var nSeqs int - seqHeader := in[0] - switch { - case seqHeader < 128: - nSeqs = int(seqHeader) - in = in[1:] - case seqHeader < 255: - if len(in) < 2 { - return ErrBlockTooSmall - } - nSeqs = int(seqHeader-128)<<8 | int(in[1]) - in = in[2:] - case seqHeader == 255: - if len(in) < 3 { - return ErrBlockTooSmall - } - nSeqs = 0x7f00 + int(in[1]) + (int(in[2]) << 8) - in = in[3:] - } - if nSeqs == 0 && len(in) != 0 { - // When no sequences, there should not be any more data... - if debugDecoder { - printf("prepareSequences: 0 sequences, but %d byte(s) left on stream\n", len(in)) - } - return ErrUnexpectedBlockSize - } - - var seqs = &hist.decoders - seqs.nSeqs = nSeqs - if nSeqs > 0 { - if len(in) < 1 { - return ErrBlockTooSmall - } - br := byteReader{b: in, off: 0} - compMode := br.Uint8() - br.advance(1) - if debugDecoder { - printf("Compression modes: 0b%b", compMode) - } - for i := uint(0); i < 3; i++ { - mode := seqCompMode((compMode >> (6 - i*2)) & 3) - if debugDecoder { - println("Table", tableIndex(i), "is", mode) - } - var seq *sequenceDec - switch tableIndex(i) { - case tableLiteralLengths: - seq = &seqs.litLengths - case tableOffsets: - seq = &seqs.offsets - case tableMatchLengths: - seq = &seqs.matchLengths - default: - panic("unknown table") - } - switch mode { - case compModePredefined: - if seq.fse != nil && !seq.fse.preDefined { - fseDecoderPool.Put(seq.fse) - } - seq.fse = &fsePredef[i] - case compModeRLE: - if br.remain() < 1 { - return ErrBlockTooSmall - } - v := br.Uint8() - br.advance(1) - if seq.fse == nil || seq.fse.preDefined { - seq.fse = fseDecoderPool.Get().(*fseDecoder) - } - symb, err := decSymbolValue(v, symbolTableX[i]) - if err != nil { - printf("RLE Transform table (%v) error: %v", tableIndex(i), err) - return err - } - seq.fse.setRLE(symb) - if debugDecoder { - printf("RLE set to 0x%x, code: %v", symb, v) - } - case compModeFSE: - println("Reading table for", tableIndex(i)) - if seq.fse == nil || seq.fse.preDefined { - seq.fse = fseDecoderPool.Get().(*fseDecoder) - } - err := seq.fse.readNCount(&br, uint16(maxTableSymbol[i])) - if err != nil { - println("Read table error:", err) - return err - } - err = seq.fse.transform(symbolTableX[i]) - if err != nil { - println("Transform table error:", err) - return err - } - if debugDecoder { - println("Read table ok", "symbolLen:", seq.fse.symbolLen) - } - case compModeRepeat: - seq.repeat = true - } - if br.overread() { - return io.ErrUnexpectedEOF - } - } - in = br.unread() - } - if debugDecoder { - println("Literals:", len(seqs.literals), "hash:", xxhash.Sum64(seqs.literals), "and", seqs.nSeqs, "sequences.") - } - - if nSeqs == 0 { - if len(b.sequence) > 0 { - b.sequence = b.sequence[:0] - } - return nil - } - br := seqs.br - if br == nil { - br = &bitReader{} - } - if err := br.init(in); err != nil { - return err - } - - if err := seqs.initialize(br, hist, b.dst); err != nil { - println("initializing sequences:", err) - return err - } - // Extract blocks... - if false && hist.dict == nil { - fatalErr := func(err error) { - if err != nil { - panic(err) - } - } - fn := fmt.Sprintf("n-%d-lits-%d-prev-%d-%d-%d-win-%d.blk", hist.decoders.nSeqs, len(hist.decoders.literals), hist.recentOffsets[0], hist.recentOffsets[1], hist.recentOffsets[2], hist.windowSize) - var buf bytes.Buffer - fatalErr(binary.Write(&buf, binary.LittleEndian, hist.decoders.litLengths.fse)) - fatalErr(binary.Write(&buf, binary.LittleEndian, hist.decoders.matchLengths.fse)) - fatalErr(binary.Write(&buf, binary.LittleEndian, hist.decoders.offsets.fse)) - buf.Write(in) - os.WriteFile(filepath.Join("testdata", "seqs", fn), buf.Bytes(), os.ModePerm) - } - - return nil -} - -func (b *blockDec) decodeSequences(hist *history) error { - if cap(b.sequence) < hist.decoders.nSeqs { - if b.lowMem { - b.sequence = make([]seqVals, 0, hist.decoders.nSeqs) - } else { - b.sequence = make([]seqVals, 0, 0x7F00+0xffff) - } - } - b.sequence = b.sequence[:hist.decoders.nSeqs] - if hist.decoders.nSeqs == 0 { - hist.decoders.seqSize = len(hist.decoders.literals) - return nil - } - hist.decoders.windowSize = hist.windowSize - hist.decoders.prevOffset = hist.recentOffsets - - err := hist.decoders.decode(b.sequence) - hist.recentOffsets = hist.decoders.prevOffset - return err -} - -func (b *blockDec) executeSequences(hist *history) error { - hbytes := hist.b - if len(hbytes) > hist.windowSize { - hbytes = hbytes[len(hbytes)-hist.windowSize:] - // We do not need history anymore. - if hist.dict != nil { - hist.dict.content = nil - } - } - hist.decoders.windowSize = hist.windowSize - hist.decoders.out = b.dst[:0] - err := hist.decoders.execute(b.sequence, hbytes) - if err != nil { - return err - } - return b.updateHistory(hist) -} - -func (b *blockDec) updateHistory(hist *history) error { - if len(b.data) > maxCompressedBlockSize { - return fmt.Errorf("compressed block size too large (%d)", len(b.data)) - } - // Set output and release references. - b.dst = hist.decoders.out - hist.recentOffsets = hist.decoders.prevOffset - - if b.Last { - // if last block we don't care about history. - println("Last block, no history returned") - hist.b = hist.b[:0] - return nil - } else { - hist.append(b.dst) - if debugDecoder { - println("Finished block with ", len(b.sequence), "sequences. Added", len(b.dst), "to history, now length", len(hist.b)) - } - } - hist.decoders.out, hist.decoders.literals = nil, nil - - return nil -} diff --git a/vendor/github.com/klauspost/compress/zstd/blockenc.go b/vendor/github.com/klauspost/compress/zstd/blockenc.go deleted file mode 100644 index 2cfe925ad..000000000 --- a/vendor/github.com/klauspost/compress/zstd/blockenc.go +++ /dev/null @@ -1,889 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "errors" - "fmt" - "math" - "math/bits" - - "github.com/klauspost/compress/huff0" -) - -type blockEnc struct { - size int - literals []byte - sequences []seq - coders seqCoders - litEnc *huff0.Scratch - dictLitEnc *huff0.Scratch - wr bitWriter - - extraLits int - output []byte - recentOffsets [3]uint32 - prevRecentOffsets [3]uint32 - - last bool - lowMem bool -} - -// init should be used once the block has been created. -// If called more than once, the effect is the same as calling reset. -func (b *blockEnc) init() { - if b.lowMem { - // 1K literals - if cap(b.literals) < 1<<10 { - b.literals = make([]byte, 0, 1<<10) - } - const defSeqs = 20 - if cap(b.sequences) < defSeqs { - b.sequences = make([]seq, 0, defSeqs) - } - // 1K - if cap(b.output) < 1<<10 { - b.output = make([]byte, 0, 1<<10) - } - } else { - if cap(b.literals) < maxCompressedBlockSize { - b.literals = make([]byte, 0, maxCompressedBlockSize) - } - const defSeqs = 2000 - if cap(b.sequences) < defSeqs { - b.sequences = make([]seq, 0, defSeqs) - } - if cap(b.output) < maxCompressedBlockSize { - b.output = make([]byte, 0, maxCompressedBlockSize) - } - } - - if b.coders.mlEnc == nil { - b.coders.mlEnc = &fseEncoder{} - b.coders.mlPrev = &fseEncoder{} - b.coders.ofEnc = &fseEncoder{} - b.coders.ofPrev = &fseEncoder{} - b.coders.llEnc = &fseEncoder{} - b.coders.llPrev = &fseEncoder{} - } - b.litEnc = &huff0.Scratch{WantLogLess: 4} - b.reset(nil) -} - -// initNewEncode can be used to reset offsets and encoders to the initial state. -func (b *blockEnc) initNewEncode() { - b.recentOffsets = [3]uint32{1, 4, 8} - b.litEnc.Reuse = huff0.ReusePolicyNone - b.coders.setPrev(nil, nil, nil) -} - -// reset will reset the block for a new encode, but in the same stream, -// meaning that state will be carried over, but the block content is reset. -// If a previous block is provided, the recent offsets are carried over. -func (b *blockEnc) reset(prev *blockEnc) { - b.extraLits = 0 - b.literals = b.literals[:0] - b.size = 0 - b.sequences = b.sequences[:0] - b.output = b.output[:0] - b.last = false - if prev != nil { - b.recentOffsets = prev.prevRecentOffsets - } - b.dictLitEnc = nil -} - -// reset will reset the block for a new encode, but in the same stream, -// meaning that state will be carried over, but the block content is reset. -// If a previous block is provided, the recent offsets are carried over. -func (b *blockEnc) swapEncoders(prev *blockEnc) { - b.coders.swap(&prev.coders) - b.litEnc, prev.litEnc = prev.litEnc, b.litEnc -} - -// blockHeader contains the information for a block header. -type blockHeader uint32 - -// setLast sets the 'last' indicator on a block. -func (h *blockHeader) setLast(b bool) { - if b { - *h = *h | 1 - } else { - const mask = (1 << 24) - 2 - *h = *h & mask - } -} - -// setSize will store the compressed size of a block. -func (h *blockHeader) setSize(v uint32) { - const mask = 7 - *h = (*h)&mask | blockHeader(v<<3) -} - -// setType sets the block type. -func (h *blockHeader) setType(t blockType) { - const mask = 1 | (((1 << 24) - 1) ^ 7) - *h = (*h & mask) | blockHeader(t<<1) -} - -// appendTo will append the block header to a slice. -func (h blockHeader) appendTo(b []byte) []byte { - return append(b, uint8(h), uint8(h>>8), uint8(h>>16)) -} - -// String returns a string representation of the block. -func (h blockHeader) String() string { - return fmt.Sprintf("Type: %d, Size: %d, Last:%t", (h>>1)&3, h>>3, h&1 == 1) -} - -// literalsHeader contains literals header information. -type literalsHeader uint64 - -// setType can be used to set the type of literal block. -func (h *literalsHeader) setType(t literalsBlockType) { - const mask = math.MaxUint64 - 3 - *h = (*h & mask) | literalsHeader(t) -} - -// setSize can be used to set a single size, for uncompressed and RLE content. -func (h *literalsHeader) setSize(regenLen int) { - inBits := bits.Len32(uint32(regenLen)) - // Only retain 2 bits - const mask = 3 - lh := uint64(*h & mask) - switch { - case inBits < 5: - lh |= (uint64(regenLen) << 3) | (1 << 60) - if debugEncoder { - got := int(lh>>3) & 0xff - if got != regenLen { - panic(fmt.Sprint("litRegenSize = ", regenLen, "(want) != ", got, "(got)")) - } - } - case inBits < 12: - lh |= (1 << 2) | (uint64(regenLen) << 4) | (2 << 60) - case inBits < 20: - lh |= (3 << 2) | (uint64(regenLen) << 4) | (3 << 60) - default: - panic(fmt.Errorf("internal error: block too big (%d)", regenLen)) - } - *h = literalsHeader(lh) -} - -// setSizes will set the size of a compressed literals section and the input length. -func (h *literalsHeader) setSizes(compLen, inLen int, single bool) { - compBits, inBits := bits.Len32(uint32(compLen)), bits.Len32(uint32(inLen)) - // Only retain 2 bits - const mask = 3 - lh := uint64(*h & mask) - switch { - case compBits <= 10 && inBits <= 10: - if !single { - lh |= 1 << 2 - } - lh |= (uint64(inLen) << 4) | (uint64(compLen) << (10 + 4)) | (3 << 60) - if debugEncoder { - const mmask = (1 << 24) - 1 - n := (lh >> 4) & mmask - if int(n&1023) != inLen { - panic(fmt.Sprint("regensize:", int(n&1023), "!=", inLen, inBits)) - } - if int(n>>10) != compLen { - panic(fmt.Sprint("compsize:", int(n>>10), "!=", compLen, compBits)) - } - } - case compBits <= 14 && inBits <= 14: - lh |= (2 << 2) | (uint64(inLen) << 4) | (uint64(compLen) << (14 + 4)) | (4 << 60) - if single { - panic("single stream used with more than 10 bits length.") - } - case compBits <= 18 && inBits <= 18: - lh |= (3 << 2) | (uint64(inLen) << 4) | (uint64(compLen) << (18 + 4)) | (5 << 60) - if single { - panic("single stream used with more than 10 bits length.") - } - default: - panic("internal error: block too big") - } - *h = literalsHeader(lh) -} - -// appendTo will append the literals header to a byte slice. -func (h literalsHeader) appendTo(b []byte) []byte { - size := uint8(h >> 60) - switch size { - case 1: - b = append(b, uint8(h)) - case 2: - b = append(b, uint8(h), uint8(h>>8)) - case 3: - b = append(b, uint8(h), uint8(h>>8), uint8(h>>16)) - case 4: - b = append(b, uint8(h), uint8(h>>8), uint8(h>>16), uint8(h>>24)) - case 5: - b = append(b, uint8(h), uint8(h>>8), uint8(h>>16), uint8(h>>24), uint8(h>>32)) - default: - panic(fmt.Errorf("internal error: literalsHeader has invalid size (%d)", size)) - } - return b -} - -// size returns the output size with currently set values. -func (h literalsHeader) size() int { - return int(h >> 60) -} - -func (h literalsHeader) String() string { - return fmt.Sprintf("Type: %d, SizeFormat: %d, Size: 0x%d, Bytes:%d", literalsBlockType(h&3), (h>>2)&3, h&((1<<60)-1)>>4, h>>60) -} - -// pushOffsets will push the recent offsets to the backup store. -func (b *blockEnc) pushOffsets() { - b.prevRecentOffsets = b.recentOffsets -} - -// pushOffsets will push the recent offsets to the backup store. -func (b *blockEnc) popOffsets() { - b.recentOffsets = b.prevRecentOffsets -} - -// matchOffset will adjust recent offsets and return the adjusted one, -// if it matches a previous offset. -func (b *blockEnc) matchOffset(offset, lits uint32) uint32 { - // Check if offset is one of the recent offsets. - // Adjusts the output offset accordingly. - // Gives a tiny bit of compression, typically around 1%. - if true { - if lits > 0 { - switch offset { - case b.recentOffsets[0]: - offset = 1 - case b.recentOffsets[1]: - b.recentOffsets[1] = b.recentOffsets[0] - b.recentOffsets[0] = offset - offset = 2 - case b.recentOffsets[2]: - b.recentOffsets[2] = b.recentOffsets[1] - b.recentOffsets[1] = b.recentOffsets[0] - b.recentOffsets[0] = offset - offset = 3 - default: - b.recentOffsets[2] = b.recentOffsets[1] - b.recentOffsets[1] = b.recentOffsets[0] - b.recentOffsets[0] = offset - offset += 3 - } - } else { - switch offset { - case b.recentOffsets[1]: - b.recentOffsets[1] = b.recentOffsets[0] - b.recentOffsets[0] = offset - offset = 1 - case b.recentOffsets[2]: - b.recentOffsets[2] = b.recentOffsets[1] - b.recentOffsets[1] = b.recentOffsets[0] - b.recentOffsets[0] = offset - offset = 2 - case b.recentOffsets[0] - 1: - b.recentOffsets[2] = b.recentOffsets[1] - b.recentOffsets[1] = b.recentOffsets[0] - b.recentOffsets[0] = offset - offset = 3 - default: - b.recentOffsets[2] = b.recentOffsets[1] - b.recentOffsets[1] = b.recentOffsets[0] - b.recentOffsets[0] = offset - offset += 3 - } - } - } else { - offset += 3 - } - return offset -} - -// encodeRaw can be used to set the output to a raw representation of supplied bytes. -func (b *blockEnc) encodeRaw(a []byte) { - var bh blockHeader - bh.setLast(b.last) - bh.setSize(uint32(len(a))) - bh.setType(blockTypeRaw) - b.output = bh.appendTo(b.output[:0]) - b.output = append(b.output, a...) - if debugEncoder { - println("Adding RAW block, length", len(a), "last:", b.last) - } -} - -// encodeRaw can be used to set the output to a raw representation of supplied bytes. -func (b *blockEnc) encodeRawTo(dst, src []byte) []byte { - var bh blockHeader - bh.setLast(b.last) - bh.setSize(uint32(len(src))) - bh.setType(blockTypeRaw) - dst = bh.appendTo(dst) - dst = append(dst, src...) - if debugEncoder { - println("Adding RAW block, length", len(src), "last:", b.last) - } - return dst -} - -// encodeLits can be used if the block is only litLen. -func (b *blockEnc) encodeLits(lits []byte, raw bool) error { - var bh blockHeader - bh.setLast(b.last) - bh.setSize(uint32(len(lits))) - - // Don't compress extremely small blocks - if len(lits) < 8 || (len(lits) < 32 && b.dictLitEnc == nil) || raw { - if debugEncoder { - println("Adding RAW block, length", len(lits), "last:", b.last) - } - bh.setType(blockTypeRaw) - b.output = bh.appendTo(b.output) - b.output = append(b.output, lits...) - return nil - } - - var ( - out []byte - reUsed, single bool - err error - ) - if b.dictLitEnc != nil { - b.litEnc.TransferCTable(b.dictLitEnc) - b.litEnc.Reuse = huff0.ReusePolicyAllow - b.dictLitEnc = nil - } - if len(lits) >= 1024 { - // Use 4 Streams. - out, reUsed, err = huff0.Compress4X(lits, b.litEnc) - } else if len(lits) > 16 { - // Use 1 stream - single = true - out, reUsed, err = huff0.Compress1X(lits, b.litEnc) - } else { - err = huff0.ErrIncompressible - } - if err == nil && len(out)+5 > len(lits) { - // If we are close, we may still be worse or equal to raw. - var lh literalsHeader - lh.setSizes(len(out), len(lits), single) - if len(out)+lh.size() >= len(lits) { - err = huff0.ErrIncompressible - } - } - switch err { - case huff0.ErrIncompressible: - if debugEncoder { - println("Adding RAW block, length", len(lits), "last:", b.last) - } - bh.setType(blockTypeRaw) - b.output = bh.appendTo(b.output) - b.output = append(b.output, lits...) - return nil - case huff0.ErrUseRLE: - if debugEncoder { - println("Adding RLE block, length", len(lits)) - } - bh.setType(blockTypeRLE) - b.output = bh.appendTo(b.output) - b.output = append(b.output, lits[0]) - return nil - case nil: - default: - return err - } - // Compressed... - // Now, allow reuse - b.litEnc.Reuse = huff0.ReusePolicyAllow - bh.setType(blockTypeCompressed) - var lh literalsHeader - if reUsed { - if debugEncoder { - println("Reused tree, compressed to", len(out)) - } - lh.setType(literalsBlockTreeless) - } else { - if debugEncoder { - println("New tree, compressed to", len(out), "tree size:", len(b.litEnc.OutTable)) - } - lh.setType(literalsBlockCompressed) - } - // Set sizes - lh.setSizes(len(out), len(lits), single) - bh.setSize(uint32(len(out) + lh.size() + 1)) - - // Write block headers. - b.output = bh.appendTo(b.output) - b.output = lh.appendTo(b.output) - // Add compressed data. - b.output = append(b.output, out...) - // No sequences. - b.output = append(b.output, 0) - return nil -} - -// fuzzFseEncoder can be used to fuzz the FSE encoder. -func fuzzFseEncoder(data []byte) int { - if len(data) > maxSequences || len(data) < 2 { - return 0 - } - enc := fseEncoder{} - hist := enc.Histogram() - maxSym := uint8(0) - for i, v := range data { - v = v & 63 - data[i] = v - hist[v]++ - if v > maxSym { - maxSym = v - } - } - if maxSym == 0 { - // All 0 - return 0 - } - maxCount := func(a []uint32) int { - var max uint32 - for _, v := range a { - if v > max { - max = v - } - } - return int(max) - } - cnt := maxCount(hist[:maxSym]) - if cnt == len(data) { - // RLE - return 0 - } - enc.HistogramFinished(maxSym, cnt) - err := enc.normalizeCount(len(data)) - if err != nil { - return 0 - } - _, err = enc.writeCount(nil) - if err != nil { - panic(err) - } - return 1 -} - -// encode will encode the block and append the output in b.output. -// Previous offset codes must be pushed if more blocks are expected. -func (b *blockEnc) encode(org []byte, raw, rawAllLits bool) error { - if len(b.sequences) == 0 { - return b.encodeLits(b.literals, rawAllLits) - } - // We want some difference to at least account for the headers. - saved := b.size - len(b.literals) - (b.size >> 6) - if saved < 16 { - if org == nil { - return errIncompressible - } - b.popOffsets() - return b.encodeLits(org, rawAllLits) - } - - var bh blockHeader - var lh literalsHeader - bh.setLast(b.last) - bh.setType(blockTypeCompressed) - // Store offset of the block header. Needed when we know the size. - bhOffset := len(b.output) - b.output = bh.appendTo(b.output) - - var ( - out []byte - reUsed, single bool - err error - ) - if b.dictLitEnc != nil { - b.litEnc.TransferCTable(b.dictLitEnc) - b.litEnc.Reuse = huff0.ReusePolicyAllow - b.dictLitEnc = nil - } - if len(b.literals) >= 1024 && !raw { - // Use 4 Streams. - out, reUsed, err = huff0.Compress4X(b.literals, b.litEnc) - } else if len(b.literals) > 16 && !raw { - // Use 1 stream - single = true - out, reUsed, err = huff0.Compress1X(b.literals, b.litEnc) - } else { - err = huff0.ErrIncompressible - } - - if err == nil && len(out)+5 > len(b.literals) { - // If we are close, we may still be worse or equal to raw. - var lh literalsHeader - lh.setSize(len(b.literals)) - szRaw := lh.size() - lh.setSizes(len(out), len(b.literals), single) - szComp := lh.size() - if len(out)+szComp >= len(b.literals)+szRaw { - err = huff0.ErrIncompressible - } - } - switch err { - case huff0.ErrIncompressible: - lh.setType(literalsBlockRaw) - lh.setSize(len(b.literals)) - b.output = lh.appendTo(b.output) - b.output = append(b.output, b.literals...) - if debugEncoder { - println("Adding literals RAW, length", len(b.literals)) - } - case huff0.ErrUseRLE: - lh.setType(literalsBlockRLE) - lh.setSize(len(b.literals)) - b.output = lh.appendTo(b.output) - b.output = append(b.output, b.literals[0]) - if debugEncoder { - println("Adding literals RLE") - } - case nil: - // Compressed litLen... - if reUsed { - if debugEncoder { - println("reused tree") - } - lh.setType(literalsBlockTreeless) - } else { - if debugEncoder { - println("new tree, size:", len(b.litEnc.OutTable)) - } - lh.setType(literalsBlockCompressed) - if debugEncoder { - _, _, err := huff0.ReadTable(out, nil) - if err != nil { - panic(err) - } - } - } - lh.setSizes(len(out), len(b.literals), single) - if debugEncoder { - printf("Compressed %d literals to %d bytes", len(b.literals), len(out)) - println("Adding literal header:", lh) - } - b.output = lh.appendTo(b.output) - b.output = append(b.output, out...) - b.litEnc.Reuse = huff0.ReusePolicyAllow - if debugEncoder { - println("Adding literals compressed") - } - default: - if debugEncoder { - println("Adding literals ERROR:", err) - } - return err - } - // Sequence compression - - // Write the number of sequences - switch { - case len(b.sequences) < 128: - b.output = append(b.output, uint8(len(b.sequences))) - case len(b.sequences) < 0x7f00: // TODO: this could be wrong - n := len(b.sequences) - b.output = append(b.output, 128+uint8(n>>8), uint8(n)) - default: - n := len(b.sequences) - 0x7f00 - b.output = append(b.output, 255, uint8(n), uint8(n>>8)) - } - if debugEncoder { - println("Encoding", len(b.sequences), "sequences") - } - b.genCodes() - llEnc := b.coders.llEnc - ofEnc := b.coders.ofEnc - mlEnc := b.coders.mlEnc - err = llEnc.normalizeCount(len(b.sequences)) - if err != nil { - return err - } - err = ofEnc.normalizeCount(len(b.sequences)) - if err != nil { - return err - } - err = mlEnc.normalizeCount(len(b.sequences)) - if err != nil { - return err - } - - // Choose the best compression mode for each type. - // Will evaluate the new vs predefined and previous. - chooseComp := func(cur, prev, preDef *fseEncoder) (*fseEncoder, seqCompMode) { - // See if predefined/previous is better - hist := cur.count[:cur.symbolLen] - nSize := cur.approxSize(hist) + cur.maxHeaderSize() - predefSize := preDef.approxSize(hist) - prevSize := prev.approxSize(hist) - - // Add a small penalty for new encoders. - // Don't bother with extremely small (<2 byte gains). - nSize = nSize + (nSize+2*8*16)>>4 - switch { - case predefSize <= prevSize && predefSize <= nSize || forcePreDef: - if debugEncoder { - println("Using predefined", predefSize>>3, "<=", nSize>>3) - } - return preDef, compModePredefined - case prevSize <= nSize: - if debugEncoder { - println("Using previous", prevSize>>3, "<=", nSize>>3) - } - return prev, compModeRepeat - default: - if debugEncoder { - println("Using new, predef", predefSize>>3, ". previous:", prevSize>>3, ">", nSize>>3, "header max:", cur.maxHeaderSize()>>3, "bytes") - println("tl:", cur.actualTableLog, "symbolLen:", cur.symbolLen, "norm:", cur.norm[:cur.symbolLen], "hist", cur.count[:cur.symbolLen]) - } - return cur, compModeFSE - } - } - - // Write compression mode - var mode uint8 - if llEnc.useRLE { - mode |= uint8(compModeRLE) << 6 - llEnc.setRLE(b.sequences[0].llCode) - if debugEncoder { - println("llEnc.useRLE") - } - } else { - var m seqCompMode - llEnc, m = chooseComp(llEnc, b.coders.llPrev, &fsePredefEnc[tableLiteralLengths]) - mode |= uint8(m) << 6 - } - if ofEnc.useRLE { - mode |= uint8(compModeRLE) << 4 - ofEnc.setRLE(b.sequences[0].ofCode) - if debugEncoder { - println("ofEnc.useRLE") - } - } else { - var m seqCompMode - ofEnc, m = chooseComp(ofEnc, b.coders.ofPrev, &fsePredefEnc[tableOffsets]) - mode |= uint8(m) << 4 - } - - if mlEnc.useRLE { - mode |= uint8(compModeRLE) << 2 - mlEnc.setRLE(b.sequences[0].mlCode) - if debugEncoder { - println("mlEnc.useRLE, code: ", b.sequences[0].mlCode, "value", b.sequences[0].matchLen) - } - } else { - var m seqCompMode - mlEnc, m = chooseComp(mlEnc, b.coders.mlPrev, &fsePredefEnc[tableMatchLengths]) - mode |= uint8(m) << 2 - } - b.output = append(b.output, mode) - if debugEncoder { - printf("Compression modes: 0b%b", mode) - } - b.output, err = llEnc.writeCount(b.output) - if err != nil { - return err - } - start := len(b.output) - b.output, err = ofEnc.writeCount(b.output) - if err != nil { - return err - } - if false { - println("block:", b.output[start:], "tablelog", ofEnc.actualTableLog, "maxcount:", ofEnc.maxCount) - fmt.Printf("selected TableLog: %d, Symbol length: %d\n", ofEnc.actualTableLog, ofEnc.symbolLen) - for i, v := range ofEnc.norm[:ofEnc.symbolLen] { - fmt.Printf("%3d: %5d -> %4d \n", i, ofEnc.count[i], v) - } - } - b.output, err = mlEnc.writeCount(b.output) - if err != nil { - return err - } - - // Maybe in block? - wr := &b.wr - wr.reset(b.output) - - var ll, of, ml cState - - // Current sequence - seq := len(b.sequences) - 1 - s := b.sequences[seq] - llEnc.setBits(llBitsTable[:]) - mlEnc.setBits(mlBitsTable[:]) - ofEnc.setBits(nil) - - llTT, ofTT, mlTT := llEnc.ct.symbolTT[:256], ofEnc.ct.symbolTT[:256], mlEnc.ct.symbolTT[:256] - - // We have 3 bounds checks here (and in the loop). - // Since we are iterating backwards it is kinda hard to avoid. - llB, ofB, mlB := llTT[s.llCode], ofTT[s.ofCode], mlTT[s.mlCode] - ll.init(wr, &llEnc.ct, llB) - of.init(wr, &ofEnc.ct, ofB) - wr.flush32() - ml.init(wr, &mlEnc.ct, mlB) - - // Each of these lookups also generates a bounds check. - wr.addBits32NC(s.litLen, llB.outBits) - wr.addBits32NC(s.matchLen, mlB.outBits) - wr.flush32() - wr.addBits32NC(s.offset, ofB.outBits) - if debugSequences { - println("Encoded seq", seq, s, "codes:", s.llCode, s.mlCode, s.ofCode, "states:", ll.state, ml.state, of.state, "bits:", llB, mlB, ofB) - } - seq-- - // Store sequences in reverse... - for seq >= 0 { - s = b.sequences[seq] - - ofB := ofTT[s.ofCode] - wr.flush32() // tablelog max is below 8 for each, so it will fill max 24 bits. - //of.encode(ofB) - nbBitsOut := (uint32(of.state) + ofB.deltaNbBits) >> 16 - dstState := int32(of.state>>(nbBitsOut&15)) + int32(ofB.deltaFindState) - wr.addBits16NC(of.state, uint8(nbBitsOut)) - of.state = of.stateTable[dstState] - - // Accumulate extra bits. - outBits := ofB.outBits & 31 - extraBits := uint64(s.offset & bitMask32[outBits]) - extraBitsN := outBits - - mlB := mlTT[s.mlCode] - //ml.encode(mlB) - nbBitsOut = (uint32(ml.state) + mlB.deltaNbBits) >> 16 - dstState = int32(ml.state>>(nbBitsOut&15)) + int32(mlB.deltaFindState) - wr.addBits16NC(ml.state, uint8(nbBitsOut)) - ml.state = ml.stateTable[dstState] - - outBits = mlB.outBits & 31 - extraBits = extraBits<> 16 - dstState = int32(ll.state>>(nbBitsOut&15)) + int32(llB.deltaFindState) - wr.addBits16NC(ll.state, uint8(nbBitsOut)) - ll.state = ll.stateTable[dstState] - - outBits = llB.outBits & 31 - extraBits = extraBits<= b.size { - // Discard and encode as raw block. - b.output = b.encodeRawTo(b.output[:bhOffset], org) - b.popOffsets() - b.litEnc.Reuse = huff0.ReusePolicyNone - return nil - } - - // Size is output minus block header. - bh.setSize(uint32(len(b.output)-bhOffset) - 3) - if debugEncoder { - println("Rewriting block header", bh) - } - _ = bh.appendTo(b.output[bhOffset:bhOffset]) - b.coders.setPrev(llEnc, mlEnc, ofEnc) - return nil -} - -var errIncompressible = errors.New("incompressible") - -func (b *blockEnc) genCodes() { - if len(b.sequences) == 0 { - // nothing to do - return - } - if len(b.sequences) > math.MaxUint16 { - panic("can only encode up to 64K sequences") - } - // No bounds checks after here: - llH := b.coders.llEnc.Histogram() - ofH := b.coders.ofEnc.Histogram() - mlH := b.coders.mlEnc.Histogram() - for i := range llH { - llH[i] = 0 - } - for i := range ofH { - ofH[i] = 0 - } - for i := range mlH { - mlH[i] = 0 - } - - var llMax, ofMax, mlMax uint8 - for i := range b.sequences { - seq := &b.sequences[i] - v := llCode(seq.litLen) - seq.llCode = v - llH[v]++ - if v > llMax { - llMax = v - } - - v = ofCode(seq.offset) - seq.ofCode = v - ofH[v]++ - if v > ofMax { - ofMax = v - } - - v = mlCode(seq.matchLen) - seq.mlCode = v - mlH[v]++ - if v > mlMax { - mlMax = v - if debugAsserts && mlMax > maxMatchLengthSymbol { - panic(fmt.Errorf("mlMax > maxMatchLengthSymbol (%d), matchlen: %d", mlMax, seq.matchLen)) - } - } - } - maxCount := func(a []uint32) int { - var max uint32 - for _, v := range a { - if v > max { - max = v - } - } - return int(max) - } - if debugAsserts && mlMax > maxMatchLengthSymbol { - panic(fmt.Errorf("mlMax > maxMatchLengthSymbol (%d)", mlMax)) - } - if debugAsserts && ofMax > maxOffsetBits { - panic(fmt.Errorf("ofMax > maxOffsetBits (%d)", ofMax)) - } - if debugAsserts && llMax > maxLiteralLengthSymbol { - panic(fmt.Errorf("llMax > maxLiteralLengthSymbol (%d)", llMax)) - } - - b.coders.mlEnc.HistogramFinished(mlMax, maxCount(mlH[:mlMax+1])) - b.coders.ofEnc.HistogramFinished(ofMax, maxCount(ofH[:ofMax+1])) - b.coders.llEnc.HistogramFinished(llMax, maxCount(llH[:llMax+1])) -} diff --git a/vendor/github.com/klauspost/compress/zstd/blocktype_string.go b/vendor/github.com/klauspost/compress/zstd/blocktype_string.go deleted file mode 100644 index 01a01e486..000000000 --- a/vendor/github.com/klauspost/compress/zstd/blocktype_string.go +++ /dev/null @@ -1,85 +0,0 @@ -// Code generated by "stringer -type=blockType,literalsBlockType,seqCompMode,tableIndex"; DO NOT EDIT. - -package zstd - -import "strconv" - -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[blockTypeRaw-0] - _ = x[blockTypeRLE-1] - _ = x[blockTypeCompressed-2] - _ = x[blockTypeReserved-3] -} - -const _blockType_name = "blockTypeRawblockTypeRLEblockTypeCompressedblockTypeReserved" - -var _blockType_index = [...]uint8{0, 12, 24, 43, 60} - -func (i blockType) String() string { - if i >= blockType(len(_blockType_index)-1) { - return "blockType(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _blockType_name[_blockType_index[i]:_blockType_index[i+1]] -} -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[literalsBlockRaw-0] - _ = x[literalsBlockRLE-1] - _ = x[literalsBlockCompressed-2] - _ = x[literalsBlockTreeless-3] -} - -const _literalsBlockType_name = "literalsBlockRawliteralsBlockRLEliteralsBlockCompressedliteralsBlockTreeless" - -var _literalsBlockType_index = [...]uint8{0, 16, 32, 55, 76} - -func (i literalsBlockType) String() string { - if i >= literalsBlockType(len(_literalsBlockType_index)-1) { - return "literalsBlockType(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _literalsBlockType_name[_literalsBlockType_index[i]:_literalsBlockType_index[i+1]] -} -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[compModePredefined-0] - _ = x[compModeRLE-1] - _ = x[compModeFSE-2] - _ = x[compModeRepeat-3] -} - -const _seqCompMode_name = "compModePredefinedcompModeRLEcompModeFSEcompModeRepeat" - -var _seqCompMode_index = [...]uint8{0, 18, 29, 40, 54} - -func (i seqCompMode) String() string { - if i >= seqCompMode(len(_seqCompMode_index)-1) { - return "seqCompMode(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _seqCompMode_name[_seqCompMode_index[i]:_seqCompMode_index[i+1]] -} -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[tableLiteralLengths-0] - _ = x[tableOffsets-1] - _ = x[tableMatchLengths-2] -} - -const _tableIndex_name = "tableLiteralLengthstableOffsetstableMatchLengths" - -var _tableIndex_index = [...]uint8{0, 19, 31, 48} - -func (i tableIndex) String() string { - if i >= tableIndex(len(_tableIndex_index)-1) { - return "tableIndex(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _tableIndex_name[_tableIndex_index[i]:_tableIndex_index[i+1]] -} diff --git a/vendor/github.com/klauspost/compress/zstd/bytebuf.go b/vendor/github.com/klauspost/compress/zstd/bytebuf.go deleted file mode 100644 index 55a388553..000000000 --- a/vendor/github.com/klauspost/compress/zstd/bytebuf.go +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "fmt" - "io" -) - -type byteBuffer interface { - // Read up to 8 bytes. - // Returns io.ErrUnexpectedEOF if this cannot be satisfied. - readSmall(n int) ([]byte, error) - - // Read >8 bytes. - // MAY use the destination slice. - readBig(n int, dst []byte) ([]byte, error) - - // Read a single byte. - readByte() (byte, error) - - // Skip n bytes. - skipN(n int64) error -} - -// in-memory buffer -type byteBuf []byte - -func (b *byteBuf) readSmall(n int) ([]byte, error) { - if debugAsserts && n > 8 { - panic(fmt.Errorf("small read > 8 (%d). use readBig", n)) - } - bb := *b - if len(bb) < n { - return nil, io.ErrUnexpectedEOF - } - r := bb[:n] - *b = bb[n:] - return r, nil -} - -func (b *byteBuf) readBig(n int, dst []byte) ([]byte, error) { - bb := *b - if len(bb) < n { - return nil, io.ErrUnexpectedEOF - } - r := bb[:n] - *b = bb[n:] - return r, nil -} - -func (b *byteBuf) readByte() (byte, error) { - bb := *b - if len(bb) < 1 { - return 0, io.ErrUnexpectedEOF - } - r := bb[0] - *b = bb[1:] - return r, nil -} - -func (b *byteBuf) skipN(n int64) error { - bb := *b - if n < 0 { - return fmt.Errorf("negative skip (%d) requested", n) - } - if int64(len(bb)) < n { - return io.ErrUnexpectedEOF - } - *b = bb[n:] - return nil -} - -// wrapper around a reader. -type readerWrapper struct { - r io.Reader - tmp [8]byte -} - -func (r *readerWrapper) readSmall(n int) ([]byte, error) { - if debugAsserts && n > 8 { - panic(fmt.Errorf("small read > 8 (%d). use readBig", n)) - } - n2, err := io.ReadFull(r.r, r.tmp[:n]) - // We only really care about the actual bytes read. - if err != nil { - if err == io.EOF { - return nil, io.ErrUnexpectedEOF - } - if debugDecoder { - println("readSmall: got", n2, "want", n, "err", err) - } - return nil, err - } - return r.tmp[:n], nil -} - -func (r *readerWrapper) readBig(n int, dst []byte) ([]byte, error) { - if cap(dst) < n { - dst = make([]byte, n) - } - n2, err := io.ReadFull(r.r, dst[:n]) - if err == io.EOF && n > 0 { - err = io.ErrUnexpectedEOF - } - return dst[:n2], err -} - -func (r *readerWrapper) readByte() (byte, error) { - n2, err := io.ReadFull(r.r, r.tmp[:1]) - if err != nil { - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - return 0, err - } - if n2 != 1 { - return 0, io.ErrUnexpectedEOF - } - return r.tmp[0], nil -} - -func (r *readerWrapper) skipN(n int64) error { - n2, err := io.CopyN(io.Discard, r.r, n) - if n2 != n { - err = io.ErrUnexpectedEOF - } - return err -} diff --git a/vendor/github.com/klauspost/compress/zstd/bytereader.go b/vendor/github.com/klauspost/compress/zstd/bytereader.go deleted file mode 100644 index 0e59a242d..000000000 --- a/vendor/github.com/klauspost/compress/zstd/bytereader.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -// byteReader provides a byte reader that reads -// little endian values from a byte stream. -// The input stream is manually advanced. -// The reader performs no bounds checks. -type byteReader struct { - b []byte - off int -} - -// advance the stream b n bytes. -func (b *byteReader) advance(n uint) { - b.off += int(n) -} - -// overread returns whether we have advanced too far. -func (b *byteReader) overread() bool { - return b.off > len(b.b) -} - -// Int32 returns a little endian int32 starting at current offset. -func (b byteReader) Int32() int32 { - b2 := b.b[b.off:] - b2 = b2[:4] - v3 := int32(b2[3]) - v2 := int32(b2[2]) - v1 := int32(b2[1]) - v0 := int32(b2[0]) - return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24) -} - -// Uint8 returns the next byte -func (b *byteReader) Uint8() uint8 { - v := b.b[b.off] - return v -} - -// Uint32 returns a little endian uint32 starting at current offset. -func (b byteReader) Uint32() uint32 { - if r := b.remain(); r < 4 { - // Very rare - v := uint32(0) - for i := 1; i <= r; i++ { - v = (v << 8) | uint32(b.b[len(b.b)-i]) - } - return v - } - b2 := b.b[b.off:] - b2 = b2[:4] - v3 := uint32(b2[3]) - v2 := uint32(b2[2]) - v1 := uint32(b2[1]) - v0 := uint32(b2[0]) - return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24) -} - -// Uint32NC returns a little endian uint32 starting at current offset. -// The caller must be sure if there are at least 4 bytes left. -func (b byteReader) Uint32NC() uint32 { - b2 := b.b[b.off:] - b2 = b2[:4] - v3 := uint32(b2[3]) - v2 := uint32(b2[2]) - v1 := uint32(b2[1]) - v0 := uint32(b2[0]) - return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24) -} - -// unread returns the unread portion of the input. -func (b byteReader) unread() []byte { - return b.b[b.off:] -} - -// remain will return the number of bytes remaining. -func (b byteReader) remain() int { - return len(b.b) - b.off -} diff --git a/vendor/github.com/klauspost/compress/zstd/decodeheader.go b/vendor/github.com/klauspost/compress/zstd/decodeheader.go deleted file mode 100644 index f6a240970..000000000 --- a/vendor/github.com/klauspost/compress/zstd/decodeheader.go +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright 2020+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. - -package zstd - -import ( - "encoding/binary" - "errors" - "io" -) - -// HeaderMaxSize is the maximum size of a Frame and Block Header. -// If less is sent to Header.Decode it *may* still contain enough information. -const HeaderMaxSize = 14 + 3 - -// Header contains information about the first frame and block within that. -type Header struct { - // SingleSegment specifies whether the data is to be decompressed into a - // single contiguous memory segment. - // It implies that WindowSize is invalid and that FrameContentSize is valid. - SingleSegment bool - - // WindowSize is the window of data to keep while decoding. - // Will only be set if SingleSegment is false. - WindowSize uint64 - - // Dictionary ID. - // If 0, no dictionary. - DictionaryID uint32 - - // HasFCS specifies whether FrameContentSize has a valid value. - HasFCS bool - - // FrameContentSize is the expected uncompressed size of the entire frame. - FrameContentSize uint64 - - // Skippable will be true if the frame is meant to be skipped. - // This implies that FirstBlock.OK is false. - Skippable bool - - // SkippableID is the user-specific ID for the skippable frame. - // Valid values are between 0 to 15, inclusive. - SkippableID int - - // SkippableSize is the length of the user data to skip following - // the header. - SkippableSize uint32 - - // HeaderSize is the raw size of the frame header. - // - // For normal frames, it includes the size of the magic number and - // the size of the header (per section 3.1.1.1). - // It does not include the size for any data blocks (section 3.1.1.2) nor - // the size for the trailing content checksum. - // - // For skippable frames, this counts the size of the magic number - // along with the size of the size field of the payload. - // It does not include the size of the skippable payload itself. - // The total frame size is the HeaderSize plus the SkippableSize. - HeaderSize int - - // First block information. - FirstBlock struct { - // OK will be set if first block could be decoded. - OK bool - - // Is this the last block of a frame? - Last bool - - // Is the data compressed? - // If true CompressedSize will be populated. - // Unfortunately DecompressedSize cannot be determined - // without decoding the blocks. - Compressed bool - - // DecompressedSize is the expected decompressed size of the block. - // Will be 0 if it cannot be determined. - DecompressedSize int - - // CompressedSize of the data in the block. - // Does not include the block header. - // Will be equal to DecompressedSize if not Compressed. - CompressedSize int - } - - // If set there is a checksum present for the block content. - // The checksum field at the end is always 4 bytes long. - HasCheckSum bool -} - -// Decode the header from the beginning of the stream. -// This will decode the frame header and the first block header if enough bytes are provided. -// It is recommended to provide at least HeaderMaxSize bytes. -// If the frame header cannot be read an error will be returned. -// If there isn't enough input, io.ErrUnexpectedEOF is returned. -// The FirstBlock.OK will indicate if enough information was available to decode the first block header. -func (h *Header) Decode(in []byte) error { - *h = Header{} - if len(in) < 4 { - return io.ErrUnexpectedEOF - } - h.HeaderSize += 4 - b, in := in[:4], in[4:] - if string(b) != frameMagic { - if string(b[1:4]) != skippableFrameMagic || b[0]&0xf0 != 0x50 { - return ErrMagicMismatch - } - if len(in) < 4 { - return io.ErrUnexpectedEOF - } - h.HeaderSize += 4 - h.Skippable = true - h.SkippableID = int(b[0] & 0xf) - h.SkippableSize = binary.LittleEndian.Uint32(in) - return nil - } - - // Read Window_Descriptor - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#window_descriptor - if len(in) < 1 { - return io.ErrUnexpectedEOF - } - fhd, in := in[0], in[1:] - h.HeaderSize++ - h.SingleSegment = fhd&(1<<5) != 0 - h.HasCheckSum = fhd&(1<<2) != 0 - if fhd&(1<<3) != 0 { - return errors.New("reserved bit set on frame header") - } - - if !h.SingleSegment { - if len(in) < 1 { - return io.ErrUnexpectedEOF - } - var wd byte - wd, in = in[0], in[1:] - h.HeaderSize++ - windowLog := 10 + (wd >> 3) - windowBase := uint64(1) << windowLog - windowAdd := (windowBase / 8) * uint64(wd&0x7) - h.WindowSize = windowBase + windowAdd - } - - // Read Dictionary_ID - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#dictionary_id - if size := fhd & 3; size != 0 { - if size == 3 { - size = 4 - } - if len(in) < int(size) { - return io.ErrUnexpectedEOF - } - b, in = in[:size], in[size:] - h.HeaderSize += int(size) - switch len(b) { - case 1: - h.DictionaryID = uint32(b[0]) - case 2: - h.DictionaryID = uint32(b[0]) | (uint32(b[1]) << 8) - case 4: - h.DictionaryID = uint32(b[0]) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24) - } - } - - // Read Frame_Content_Size - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#frame_content_size - var fcsSize int - v := fhd >> 6 - switch v { - case 0: - if h.SingleSegment { - fcsSize = 1 - } - default: - fcsSize = 1 << v - } - - if fcsSize > 0 { - h.HasFCS = true - if len(in) < fcsSize { - return io.ErrUnexpectedEOF - } - b, in = in[:fcsSize], in[fcsSize:] - h.HeaderSize += int(fcsSize) - switch len(b) { - case 1: - h.FrameContentSize = uint64(b[0]) - case 2: - // When FCS_Field_Size is 2, the offset of 256 is added. - h.FrameContentSize = uint64(b[0]) | (uint64(b[1]) << 8) + 256 - case 4: - h.FrameContentSize = uint64(b[0]) | (uint64(b[1]) << 8) | (uint64(b[2]) << 16) | (uint64(b[3]) << 24) - case 8: - d1 := uint32(b[0]) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24) - d2 := uint32(b[4]) | (uint32(b[5]) << 8) | (uint32(b[6]) << 16) | (uint32(b[7]) << 24) - h.FrameContentSize = uint64(d1) | (uint64(d2) << 32) - } - } - - // Frame Header done, we will not fail from now on. - if len(in) < 3 { - return nil - } - tmp := in[:3] - bh := uint32(tmp[0]) | (uint32(tmp[1]) << 8) | (uint32(tmp[2]) << 16) - h.FirstBlock.Last = bh&1 != 0 - blockType := blockType((bh >> 1) & 3) - // find size. - cSize := int(bh >> 3) - switch blockType { - case blockTypeReserved: - return nil - case blockTypeRLE: - h.FirstBlock.Compressed = true - h.FirstBlock.DecompressedSize = cSize - h.FirstBlock.CompressedSize = 1 - case blockTypeCompressed: - h.FirstBlock.Compressed = true - h.FirstBlock.CompressedSize = cSize - case blockTypeRaw: - h.FirstBlock.DecompressedSize = cSize - h.FirstBlock.CompressedSize = cSize - default: - panic("Invalid block type") - } - - h.FirstBlock.OK = true - return nil -} diff --git a/vendor/github.com/klauspost/compress/zstd/decoder.go b/vendor/github.com/klauspost/compress/zstd/decoder.go deleted file mode 100644 index f04aaa21e..000000000 --- a/vendor/github.com/klauspost/compress/zstd/decoder.go +++ /dev/null @@ -1,948 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "context" - "encoding/binary" - "io" - "sync" - - "github.com/klauspost/compress/zstd/internal/xxhash" -) - -// Decoder provides decoding of zstandard streams. -// The decoder has been designed to operate without allocations after a warmup. -// This means that you should store the decoder for best performance. -// To re-use a stream decoder, use the Reset(r io.Reader) error to switch to another stream. -// A decoder can safely be re-used even if the previous stream failed. -// To release the resources, you must call the Close() function on a decoder. -type Decoder struct { - o decoderOptions - - // Unreferenced decoders, ready for use. - decoders chan *blockDec - - // Current read position used for Reader functionality. - current decoderState - - // sync stream decoding - syncStream struct { - decodedFrame uint64 - br readerWrapper - enabled bool - inFrame bool - dstBuf []byte - } - - frame *frameDec - - // Custom dictionaries. - dicts map[uint32]*dict - - // streamWg is the waitgroup for all streams - streamWg sync.WaitGroup -} - -// decoderState is used for maintaining state when the decoder -// is used for streaming. -type decoderState struct { - // current block being written to stream. - decodeOutput - - // output in order to be written to stream. - output chan decodeOutput - - // cancel remaining output. - cancel context.CancelFunc - - // crc of current frame - crc *xxhash.Digest - - flushed bool -} - -var ( - // Check the interfaces we want to support. - _ = io.WriterTo(&Decoder{}) - _ = io.Reader(&Decoder{}) -) - -// NewReader creates a new decoder. -// A nil Reader can be provided in which case Reset can be used to start a decode. -// -// A Decoder can be used in two modes: -// -// 1) As a stream, or -// 2) For stateless decoding using DecodeAll. -// -// Only a single stream can be decoded concurrently, but the same decoder -// can run multiple concurrent stateless decodes. It is even possible to -// use stateless decodes while a stream is being decoded. -// -// The Reset function can be used to initiate a new stream, which is will considerably -// reduce the allocations normally caused by NewReader. -func NewReader(r io.Reader, opts ...DOption) (*Decoder, error) { - initPredefined() - var d Decoder - d.o.setDefault() - for _, o := range opts { - err := o(&d.o) - if err != nil { - return nil, err - } - } - d.current.crc = xxhash.New() - d.current.flushed = true - - if r == nil { - d.current.err = ErrDecoderNilInput - } - - // Transfer option dicts. - d.dicts = make(map[uint32]*dict, len(d.o.dicts)) - for _, dc := range d.o.dicts { - d.dicts[dc.id] = dc - } - d.o.dicts = nil - - // Create decoders - d.decoders = make(chan *blockDec, d.o.concurrent) - for i := 0; i < d.o.concurrent; i++ { - dec := newBlockDec(d.o.lowMem) - dec.localFrame = newFrameDec(d.o) - d.decoders <- dec - } - - if r == nil { - return &d, nil - } - return &d, d.Reset(r) -} - -// Read bytes from the decompressed stream into p. -// Returns the number of bytes written and any error that occurred. -// When the stream is done, io.EOF will be returned. -func (d *Decoder) Read(p []byte) (int, error) { - var n int - for { - if len(d.current.b) > 0 { - filled := copy(p, d.current.b) - p = p[filled:] - d.current.b = d.current.b[filled:] - n += filled - } - if len(p) == 0 { - break - } - if len(d.current.b) == 0 { - // We have an error and no more data - if d.current.err != nil { - break - } - if !d.nextBlock(n == 0) { - return n, d.current.err - } - } - } - if len(d.current.b) > 0 { - if debugDecoder { - println("returning", n, "still bytes left:", len(d.current.b)) - } - // Only return error at end of block - return n, nil - } - if d.current.err != nil { - d.drainOutput() - } - if debugDecoder { - println("returning", n, d.current.err, len(d.decoders)) - } - return n, d.current.err -} - -// Reset will reset the decoder the supplied stream after the current has finished processing. -// Note that this functionality cannot be used after Close has been called. -// Reset can be called with a nil reader to release references to the previous reader. -// After being called with a nil reader, no other operations than Reset or DecodeAll or Close -// should be used. -func (d *Decoder) Reset(r io.Reader) error { - if d.current.err == ErrDecoderClosed { - return d.current.err - } - - d.drainOutput() - - d.syncStream.br.r = nil - if r == nil { - d.current.err = ErrDecoderNilInput - if len(d.current.b) > 0 { - d.current.b = d.current.b[:0] - } - d.current.flushed = true - return nil - } - - // If bytes buffer and < 5MB, do sync decoding anyway. - if bb, ok := r.(byter); ok && bb.Len() < d.o.decodeBufsBelow && !d.o.limitToCap { - bb2 := bb - if debugDecoder { - println("*bytes.Buffer detected, doing sync decode, len:", bb.Len()) - } - b := bb2.Bytes() - var dst []byte - if cap(d.syncStream.dstBuf) > 0 { - dst = d.syncStream.dstBuf[:0] - } - - dst, err := d.DecodeAll(b, dst) - if err == nil { - err = io.EOF - } - // Save output buffer - d.syncStream.dstBuf = dst - d.current.b = dst - d.current.err = err - d.current.flushed = true - if debugDecoder { - println("sync decode to", len(dst), "bytes, err:", err) - } - return nil - } - // Remove current block. - d.stashDecoder() - d.current.decodeOutput = decodeOutput{} - d.current.err = nil - d.current.flushed = false - d.current.d = nil - d.syncStream.dstBuf = nil - - // Ensure no-one else is still running... - d.streamWg.Wait() - if d.frame == nil { - d.frame = newFrameDec(d.o) - } - - if d.o.concurrent == 1 { - return d.startSyncDecoder(r) - } - - d.current.output = make(chan decodeOutput, d.o.concurrent) - ctx, cancel := context.WithCancel(context.Background()) - d.current.cancel = cancel - d.streamWg.Add(1) - go d.startStreamDecoder(ctx, r, d.current.output) - - return nil -} - -// drainOutput will drain the output until errEndOfStream is sent. -func (d *Decoder) drainOutput() { - if d.current.cancel != nil { - if debugDecoder { - println("cancelling current") - } - d.current.cancel() - d.current.cancel = nil - } - if d.current.d != nil { - if debugDecoder { - printf("re-adding current decoder %p, decoders: %d", d.current.d, len(d.decoders)) - } - d.decoders <- d.current.d - d.current.d = nil - d.current.b = nil - } - if d.current.output == nil || d.current.flushed { - println("current already flushed") - return - } - for v := range d.current.output { - if v.d != nil { - if debugDecoder { - printf("re-adding decoder %p", v.d) - } - d.decoders <- v.d - } - } - d.current.output = nil - d.current.flushed = true -} - -// WriteTo writes data to w until there's no more data to write or when an error occurs. -// The return value n is the number of bytes written. -// Any error encountered during the write is also returned. -func (d *Decoder) WriteTo(w io.Writer) (int64, error) { - var n int64 - for { - if len(d.current.b) > 0 { - n2, err2 := w.Write(d.current.b) - n += int64(n2) - if err2 != nil && (d.current.err == nil || d.current.err == io.EOF) { - d.current.err = err2 - } else if n2 != len(d.current.b) { - d.current.err = io.ErrShortWrite - } - } - if d.current.err != nil { - break - } - d.nextBlock(true) - } - err := d.current.err - if err != nil { - d.drainOutput() - } - if err == io.EOF { - err = nil - } - return n, err -} - -// DecodeAll allows stateless decoding of a blob of bytes. -// Output will be appended to dst, so if the destination size is known -// you can pre-allocate the destination slice to avoid allocations. -// DecodeAll can be used concurrently. -// The Decoder concurrency limits will be respected. -func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) { - if d.decoders == nil { - return dst, ErrDecoderClosed - } - - // Grab a block decoder and frame decoder. - block := <-d.decoders - frame := block.localFrame - initialSize := len(dst) - defer func() { - if debugDecoder { - printf("re-adding decoder: %p", block) - } - frame.rawInput = nil - frame.bBuf = nil - if frame.history.decoders.br != nil { - frame.history.decoders.br.in = nil - } - d.decoders <- block - }() - frame.bBuf = input - - for { - frame.history.reset() - err := frame.reset(&frame.bBuf) - if err != nil { - if err == io.EOF { - if debugDecoder { - println("frame reset return EOF") - } - return dst, nil - } - return dst, err - } - if err = d.setDict(frame); err != nil { - return nil, err - } - if frame.WindowSize > d.o.maxWindowSize { - if debugDecoder { - println("window size exceeded:", frame.WindowSize, ">", d.o.maxWindowSize) - } - return dst, ErrWindowSizeExceeded - } - if frame.FrameContentSize != fcsUnknown { - if frame.FrameContentSize > d.o.maxDecodedSize-uint64(len(dst)-initialSize) { - if debugDecoder { - println("decoder size exceeded; fcs:", frame.FrameContentSize, "> mcs:", d.o.maxDecodedSize-uint64(len(dst)-initialSize), "len:", len(dst)) - } - return dst, ErrDecoderSizeExceeded - } - if d.o.limitToCap && frame.FrameContentSize > uint64(cap(dst)-len(dst)) { - if debugDecoder { - println("decoder size exceeded; fcs:", frame.FrameContentSize, "> (cap-len)", cap(dst)-len(dst)) - } - return dst, ErrDecoderSizeExceeded - } - if cap(dst)-len(dst) < int(frame.FrameContentSize) { - dst2 := make([]byte, len(dst), len(dst)+int(frame.FrameContentSize)+compressedBlockOverAlloc) - copy(dst2, dst) - dst = dst2 - } - } - - if cap(dst) == 0 && !d.o.limitToCap { - // Allocate len(input) * 2 by default if nothing is provided - // and we didn't get frame content size. - size := len(input) * 2 - // Cap to 1 MB. - if size > 1<<20 { - size = 1 << 20 - } - if uint64(size) > d.o.maxDecodedSize { - size = int(d.o.maxDecodedSize) - } - dst = make([]byte, 0, size) - } - - dst, err = frame.runDecoder(dst, block) - if err != nil { - return dst, err - } - if uint64(len(dst)-initialSize) > d.o.maxDecodedSize { - return dst, ErrDecoderSizeExceeded - } - if len(frame.bBuf) == 0 { - if debugDecoder { - println("frame dbuf empty") - } - break - } - } - return dst, nil -} - -// nextBlock returns the next block. -// If an error occurs d.err will be set. -// Optionally the function can block for new output. -// If non-blocking mode is used the returned boolean will be false -// if no data was available without blocking. -func (d *Decoder) nextBlock(blocking bool) (ok bool) { - if d.current.err != nil { - // Keep error state. - return false - } - d.current.b = d.current.b[:0] - - // SYNC: - if d.syncStream.enabled { - if !blocking { - return false - } - ok = d.nextBlockSync() - if !ok { - d.stashDecoder() - } - return ok - } - - //ASYNC: - d.stashDecoder() - if blocking { - d.current.decodeOutput, ok = <-d.current.output - } else { - select { - case d.current.decodeOutput, ok = <-d.current.output: - default: - return false - } - } - if !ok { - // This should not happen, so signal error state... - d.current.err = io.ErrUnexpectedEOF - return false - } - next := d.current.decodeOutput - if next.d != nil && next.d.async.newHist != nil { - d.current.crc.Reset() - } - if debugDecoder { - var tmp [4]byte - binary.LittleEndian.PutUint32(tmp[:], uint32(xxhash.Sum64(next.b))) - println("got", len(d.current.b), "bytes, error:", d.current.err, "data crc:", tmp) - } - - if d.o.ignoreChecksum { - return true - } - - if len(next.b) > 0 { - d.current.crc.Write(next.b) - } - if next.err == nil && next.d != nil && next.d.hasCRC { - got := uint32(d.current.crc.Sum64()) - if got != next.d.checkCRC { - if debugDecoder { - printf("CRC Check Failed: %08x (got) != %08x (on stream)\n", got, next.d.checkCRC) - } - d.current.err = ErrCRCMismatch - } else { - if debugDecoder { - printf("CRC ok %08x\n", got) - } - } - } - - return true -} - -func (d *Decoder) nextBlockSync() (ok bool) { - if d.current.d == nil { - d.current.d = <-d.decoders - } - for len(d.current.b) == 0 { - if !d.syncStream.inFrame { - d.frame.history.reset() - d.current.err = d.frame.reset(&d.syncStream.br) - if d.current.err == nil { - d.current.err = d.setDict(d.frame) - } - if d.current.err != nil { - return false - } - if d.frame.WindowSize > d.o.maxDecodedSize || d.frame.WindowSize > d.o.maxWindowSize { - d.current.err = ErrDecoderSizeExceeded - return false - } - - d.syncStream.decodedFrame = 0 - d.syncStream.inFrame = true - } - d.current.err = d.frame.next(d.current.d) - if d.current.err != nil { - return false - } - d.frame.history.ensureBlock() - if debugDecoder { - println("History trimmed:", len(d.frame.history.b), "decoded already:", d.syncStream.decodedFrame) - } - histBefore := len(d.frame.history.b) - d.current.err = d.current.d.decodeBuf(&d.frame.history) - - if d.current.err != nil { - println("error after:", d.current.err) - return false - } - d.current.b = d.frame.history.b[histBefore:] - if debugDecoder { - println("history after:", len(d.frame.history.b)) - } - - // Check frame size (before CRC) - d.syncStream.decodedFrame += uint64(len(d.current.b)) - if d.syncStream.decodedFrame > d.frame.FrameContentSize { - if debugDecoder { - printf("DecodedFrame (%d) > FrameContentSize (%d)\n", d.syncStream.decodedFrame, d.frame.FrameContentSize) - } - d.current.err = ErrFrameSizeExceeded - return false - } - - // Check FCS - if d.current.d.Last && d.frame.FrameContentSize != fcsUnknown && d.syncStream.decodedFrame != d.frame.FrameContentSize { - if debugDecoder { - printf("DecodedFrame (%d) != FrameContentSize (%d)\n", d.syncStream.decodedFrame, d.frame.FrameContentSize) - } - d.current.err = ErrFrameSizeMismatch - return false - } - - // Update/Check CRC - if d.frame.HasCheckSum { - if !d.o.ignoreChecksum { - d.frame.crc.Write(d.current.b) - } - if d.current.d.Last { - if !d.o.ignoreChecksum { - d.current.err = d.frame.checkCRC() - } else { - d.current.err = d.frame.consumeCRC() - } - if d.current.err != nil { - println("CRC error:", d.current.err) - return false - } - } - } - d.syncStream.inFrame = !d.current.d.Last - } - return true -} - -func (d *Decoder) stashDecoder() { - if d.current.d != nil { - if debugDecoder { - printf("re-adding current decoder %p", d.current.d) - } - d.decoders <- d.current.d - d.current.d = nil - } -} - -// Close will release all resources. -// It is NOT possible to reuse the decoder after this. -func (d *Decoder) Close() { - if d.current.err == ErrDecoderClosed { - return - } - d.drainOutput() - if d.current.cancel != nil { - d.current.cancel() - d.streamWg.Wait() - d.current.cancel = nil - } - if d.decoders != nil { - close(d.decoders) - for dec := range d.decoders { - dec.Close() - } - d.decoders = nil - } - if d.current.d != nil { - d.current.d.Close() - d.current.d = nil - } - d.current.err = ErrDecoderClosed -} - -// IOReadCloser returns the decoder as an io.ReadCloser for convenience. -// Any changes to the decoder will be reflected, so the returned ReadCloser -// can be reused along with the decoder. -// io.WriterTo is also supported by the returned ReadCloser. -func (d *Decoder) IOReadCloser() io.ReadCloser { - return closeWrapper{d: d} -} - -// closeWrapper wraps a function call as a closer. -type closeWrapper struct { - d *Decoder -} - -// WriteTo forwards WriteTo calls to the decoder. -func (c closeWrapper) WriteTo(w io.Writer) (n int64, err error) { - return c.d.WriteTo(w) -} - -// Read forwards read calls to the decoder. -func (c closeWrapper) Read(p []byte) (n int, err error) { - return c.d.Read(p) -} - -// Close closes the decoder. -func (c closeWrapper) Close() error { - c.d.Close() - return nil -} - -type decodeOutput struct { - d *blockDec - b []byte - err error -} - -func (d *Decoder) startSyncDecoder(r io.Reader) error { - d.frame.history.reset() - d.syncStream.br = readerWrapper{r: r} - d.syncStream.inFrame = false - d.syncStream.enabled = true - d.syncStream.decodedFrame = 0 - return nil -} - -// Create Decoder: -// ASYNC: -// Spawn 3 go routines. -// 0: Read frames and decode block literals. -// 1: Decode sequences. -// 2: Execute sequences, send to output. -func (d *Decoder) startStreamDecoder(ctx context.Context, r io.Reader, output chan decodeOutput) { - defer d.streamWg.Done() - br := readerWrapper{r: r} - - var seqDecode = make(chan *blockDec, d.o.concurrent) - var seqExecute = make(chan *blockDec, d.o.concurrent) - - // Async 1: Decode sequences... - go func() { - var hist history - var hasErr bool - - for block := range seqDecode { - if hasErr { - if block != nil { - seqExecute <- block - } - continue - } - if block.async.newHist != nil { - if debugDecoder { - println("Async 1: new history, recent:", block.async.newHist.recentOffsets) - } - hist.reset() - hist.decoders = block.async.newHist.decoders - hist.recentOffsets = block.async.newHist.recentOffsets - hist.windowSize = block.async.newHist.windowSize - if block.async.newHist.dict != nil { - hist.setDict(block.async.newHist.dict) - } - } - if block.err != nil || block.Type != blockTypeCompressed { - hasErr = block.err != nil - seqExecute <- block - continue - } - - hist.decoders.literals = block.async.literals - block.err = block.prepareSequences(block.async.seqData, &hist) - if debugDecoder && block.err != nil { - println("prepareSequences returned:", block.err) - } - hasErr = block.err != nil - if block.err == nil { - block.err = block.decodeSequences(&hist) - if debugDecoder && block.err != nil { - println("decodeSequences returned:", block.err) - } - hasErr = block.err != nil - // block.async.sequence = hist.decoders.seq[:hist.decoders.nSeqs] - block.async.seqSize = hist.decoders.seqSize - } - seqExecute <- block - } - close(seqExecute) - hist.reset() - }() - - var wg sync.WaitGroup - wg.Add(1) - - // Async 3: Execute sequences... - frameHistCache := d.frame.history.b - go func() { - var hist history - var decodedFrame uint64 - var fcs uint64 - var hasErr bool - for block := range seqExecute { - out := decodeOutput{err: block.err, d: block} - if block.err != nil || hasErr { - hasErr = true - output <- out - continue - } - if block.async.newHist != nil { - if debugDecoder { - println("Async 2: new history") - } - hist.reset() - hist.windowSize = block.async.newHist.windowSize - hist.allocFrameBuffer = block.async.newHist.allocFrameBuffer - if block.async.newHist.dict != nil { - hist.setDict(block.async.newHist.dict) - } - - if cap(hist.b) < hist.allocFrameBuffer { - if cap(frameHistCache) >= hist.allocFrameBuffer { - hist.b = frameHistCache - } else { - hist.b = make([]byte, 0, hist.allocFrameBuffer) - println("Alloc history sized", hist.allocFrameBuffer) - } - } - hist.b = hist.b[:0] - fcs = block.async.fcs - decodedFrame = 0 - } - do := decodeOutput{err: block.err, d: block} - switch block.Type { - case blockTypeRLE: - if debugDecoder { - println("add rle block length:", block.RLESize) - } - - if cap(block.dst) < int(block.RLESize) { - if block.lowMem { - block.dst = make([]byte, block.RLESize) - } else { - block.dst = make([]byte, maxCompressedBlockSize) - } - } - block.dst = block.dst[:block.RLESize] - v := block.data[0] - for i := range block.dst { - block.dst[i] = v - } - hist.append(block.dst) - do.b = block.dst - case blockTypeRaw: - if debugDecoder { - println("add raw block length:", len(block.data)) - } - hist.append(block.data) - do.b = block.data - case blockTypeCompressed: - if debugDecoder { - println("execute with history length:", len(hist.b), "window:", hist.windowSize) - } - hist.decoders.seqSize = block.async.seqSize - hist.decoders.literals = block.async.literals - do.err = block.executeSequences(&hist) - hasErr = do.err != nil - if debugDecoder && hasErr { - println("executeSequences returned:", do.err) - } - do.b = block.dst - } - if !hasErr { - decodedFrame += uint64(len(do.b)) - if decodedFrame > fcs { - println("fcs exceeded", block.Last, fcs, decodedFrame) - do.err = ErrFrameSizeExceeded - hasErr = true - } else if block.Last && fcs != fcsUnknown && decodedFrame != fcs { - do.err = ErrFrameSizeMismatch - hasErr = true - } else { - if debugDecoder { - println("fcs ok", block.Last, fcs, decodedFrame) - } - } - } - output <- do - } - close(output) - frameHistCache = hist.b - wg.Done() - if debugDecoder { - println("decoder goroutines finished") - } - hist.reset() - }() - - var hist history -decodeStream: - for { - var hasErr bool - hist.reset() - decodeBlock := func(block *blockDec) { - if hasErr { - if block != nil { - seqDecode <- block - } - return - } - if block.err != nil || block.Type != blockTypeCompressed { - hasErr = block.err != nil - seqDecode <- block - return - } - - remain, err := block.decodeLiterals(block.data, &hist) - block.err = err - hasErr = block.err != nil - if err == nil { - block.async.literals = hist.decoders.literals - block.async.seqData = remain - } else if debugDecoder { - println("decodeLiterals error:", err) - } - seqDecode <- block - } - frame := d.frame - if debugDecoder { - println("New frame...") - } - var historySent bool - frame.history.reset() - err := frame.reset(&br) - if debugDecoder && err != nil { - println("Frame decoder returned", err) - } - if err == nil { - err = d.setDict(frame) - } - if err == nil && d.frame.WindowSize > d.o.maxWindowSize { - if debugDecoder { - println("decoder size exceeded, fws:", d.frame.WindowSize, "> mws:", d.o.maxWindowSize) - } - - err = ErrDecoderSizeExceeded - } - if err != nil { - select { - case <-ctx.Done(): - case dec := <-d.decoders: - dec.sendErr(err) - decodeBlock(dec) - } - break decodeStream - } - - // Go through all blocks of the frame. - for { - var dec *blockDec - select { - case <-ctx.Done(): - break decodeStream - case dec = <-d.decoders: - // Once we have a decoder, we MUST return it. - } - err := frame.next(dec) - if !historySent { - h := frame.history - if debugDecoder { - println("Alloc History:", h.allocFrameBuffer) - } - hist.reset() - if h.dict != nil { - hist.setDict(h.dict) - } - dec.async.newHist = &h - dec.async.fcs = frame.FrameContentSize - historySent = true - } else { - dec.async.newHist = nil - } - if debugDecoder && err != nil { - println("next block returned error:", err) - } - dec.err = err - dec.hasCRC = false - if dec.Last && frame.HasCheckSum && err == nil { - crc, err := frame.rawInput.readSmall(4) - if len(crc) < 4 { - if err == nil { - err = io.ErrUnexpectedEOF - - } - println("CRC missing?", err) - dec.err = err - } else { - dec.checkCRC = binary.LittleEndian.Uint32(crc) - dec.hasCRC = true - if debugDecoder { - printf("found crc to check: %08x\n", dec.checkCRC) - } - } - } - err = dec.err - last := dec.Last - decodeBlock(dec) - if err != nil { - break decodeStream - } - if last { - break - } - } - } - close(seqDecode) - wg.Wait() - hist.reset() - d.frame.history.b = frameHistCache -} - -func (d *Decoder) setDict(frame *frameDec) (err error) { - dict, ok := d.dicts[frame.DictionaryID] - if ok { - if debugDecoder { - println("setting dict", frame.DictionaryID) - } - frame.history.setDict(dict) - } else if frame.DictionaryID != 0 { - // A zero or missing dictionary id is ambiguous: - // either dictionary zero, or no dictionary. In particular, - // zstd --patch-from uses this id for the source file, - // so only return an error if the dictionary id is not zero. - err = ErrUnknownDictionary - } - return err -} diff --git a/vendor/github.com/klauspost/compress/zstd/decoder_options.go b/vendor/github.com/klauspost/compress/zstd/decoder_options.go deleted file mode 100644 index 774c5f00f..000000000 --- a/vendor/github.com/klauspost/compress/zstd/decoder_options.go +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "errors" - "fmt" - "math/bits" - "runtime" -) - -// DOption is an option for creating a decoder. -type DOption func(*decoderOptions) error - -// options retains accumulated state of multiple options. -type decoderOptions struct { - lowMem bool - concurrent int - maxDecodedSize uint64 - maxWindowSize uint64 - dicts []*dict - ignoreChecksum bool - limitToCap bool - decodeBufsBelow int -} - -func (o *decoderOptions) setDefault() { - *o = decoderOptions{ - // use less ram: true for now, but may change. - lowMem: true, - concurrent: runtime.GOMAXPROCS(0), - maxWindowSize: MaxWindowSize, - decodeBufsBelow: 128 << 10, - } - if o.concurrent > 4 { - o.concurrent = 4 - } - o.maxDecodedSize = 64 << 30 -} - -// WithDecoderLowmem will set whether to use a lower amount of memory, -// but possibly have to allocate more while running. -func WithDecoderLowmem(b bool) DOption { - return func(o *decoderOptions) error { o.lowMem = b; return nil } -} - -// WithDecoderConcurrency sets the number of created decoders. -// When decoding block with DecodeAll, this will limit the number -// of possible concurrently running decodes. -// When decoding streams, this will limit the number of -// inflight blocks. -// When decoding streams and setting maximum to 1, -// no async decoding will be done. -// When a value of 0 is provided GOMAXPROCS will be used. -// By default this will be set to 4 or GOMAXPROCS, whatever is lower. -func WithDecoderConcurrency(n int) DOption { - return func(o *decoderOptions) error { - if n < 0 { - return errors.New("concurrency must be at least 1") - } - if n == 0 { - o.concurrent = runtime.GOMAXPROCS(0) - } else { - o.concurrent = n - } - return nil - } -} - -// WithDecoderMaxMemory allows to set a maximum decoded size for in-memory -// non-streaming operations or maximum window size for streaming operations. -// This can be used to control memory usage of potentially hostile content. -// Maximum is 1 << 63 bytes. Default is 64GiB. -func WithDecoderMaxMemory(n uint64) DOption { - return func(o *decoderOptions) error { - if n == 0 { - return errors.New("WithDecoderMaxMemory must be at least 1") - } - if n > 1<<63 { - return errors.New("WithDecoderMaxmemory must be less than 1 << 63") - } - o.maxDecodedSize = n - return nil - } -} - -// WithDecoderDicts allows to register one or more dictionaries for the decoder. -// -// Each slice in dict must be in the [dictionary format] produced by -// "zstd --train" from the Zstandard reference implementation. -// -// If several dictionaries with the same ID are provided, the last one will be used. -// -// [dictionary format]: https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#dictionary-format -func WithDecoderDicts(dicts ...[]byte) DOption { - return func(o *decoderOptions) error { - for _, b := range dicts { - d, err := loadDict(b) - if err != nil { - return err - } - o.dicts = append(o.dicts, d) - } - return nil - } -} - -// WithDecoderDictRaw registers a dictionary that may be used by the decoder. -// The slice content can be arbitrary data. -func WithDecoderDictRaw(id uint32, content []byte) DOption { - return func(o *decoderOptions) error { - if bits.UintSize > 32 && uint(len(content)) > dictMaxLength { - return fmt.Errorf("dictionary of size %d > 2GiB too large", len(content)) - } - o.dicts = append(o.dicts, &dict{id: id, content: content, offsets: [3]int{1, 4, 8}}) - return nil - } -} - -// WithDecoderMaxWindow allows to set a maximum window size for decodes. -// This allows rejecting packets that will cause big memory usage. -// The Decoder will likely allocate more memory based on the WithDecoderLowmem setting. -// If WithDecoderMaxMemory is set to a lower value, that will be used. -// Default is 512MB, Maximum is ~3.75 TB as per zstandard spec. -func WithDecoderMaxWindow(size uint64) DOption { - return func(o *decoderOptions) error { - if size < MinWindowSize { - return errors.New("WithMaxWindowSize must be at least 1KB, 1024 bytes") - } - if size > (1<<41)+7*(1<<38) { - return errors.New("WithMaxWindowSize must be less than (1<<41) + 7*(1<<38) ~ 3.75TB") - } - o.maxWindowSize = size - return nil - } -} - -// WithDecodeAllCapLimit will limit DecodeAll to decoding cap(dst)-len(dst) bytes, -// or any size set in WithDecoderMaxMemory. -// This can be used to limit decoding to a specific maximum output size. -// Disabled by default. -func WithDecodeAllCapLimit(b bool) DOption { - return func(o *decoderOptions) error { - o.limitToCap = b - return nil - } -} - -// WithDecodeBuffersBelow will fully decode readers that have a -// `Bytes() []byte` and `Len() int` interface similar to bytes.Buffer. -// This typically uses less allocations but will have the full decompressed object in memory. -// Note that DecodeAllCapLimit will disable this, as well as giving a size of 0 or less. -// Default is 128KiB. -func WithDecodeBuffersBelow(size int) DOption { - return func(o *decoderOptions) error { - o.decodeBufsBelow = size - return nil - } -} - -// IgnoreChecksum allows to forcibly ignore checksum checking. -func IgnoreChecksum(b bool) DOption { - return func(o *decoderOptions) error { - o.ignoreChecksum = b - return nil - } -} diff --git a/vendor/github.com/klauspost/compress/zstd/dict.go b/vendor/github.com/klauspost/compress/zstd/dict.go deleted file mode 100644 index 8d5567fe6..000000000 --- a/vendor/github.com/klauspost/compress/zstd/dict.go +++ /dev/null @@ -1,534 +0,0 @@ -package zstd - -import ( - "bytes" - "encoding/binary" - "errors" - "fmt" - "io" - "math" - "sort" - - "github.com/klauspost/compress/huff0" -) - -type dict struct { - id uint32 - - litEnc *huff0.Scratch - llDec, ofDec, mlDec sequenceDec - offsets [3]int - content []byte -} - -const dictMagic = "\x37\xa4\x30\xec" - -// Maximum dictionary size for the reference implementation (1.5.3) is 2 GiB. -const dictMaxLength = 1 << 31 - -// ID returns the dictionary id or 0 if d is nil. -func (d *dict) ID() uint32 { - if d == nil { - return 0 - } - return d.id -} - -// ContentSize returns the dictionary content size or 0 if d is nil. -func (d *dict) ContentSize() int { - if d == nil { - return 0 - } - return len(d.content) -} - -// Content returns the dictionary content. -func (d *dict) Content() []byte { - if d == nil { - return nil - } - return d.content -} - -// Offsets returns the initial offsets. -func (d *dict) Offsets() [3]int { - if d == nil { - return [3]int{} - } - return d.offsets -} - -// LitEncoder returns the literal encoder. -func (d *dict) LitEncoder() *huff0.Scratch { - if d == nil { - return nil - } - return d.litEnc -} - -// Load a dictionary as described in -// https://github.com/facebook/zstd/blob/master/doc/zstd_compression_format.md#dictionary-format -func loadDict(b []byte) (*dict, error) { - // Check static field size. - if len(b) <= 8+(3*4) { - return nil, io.ErrUnexpectedEOF - } - d := dict{ - llDec: sequenceDec{fse: &fseDecoder{}}, - ofDec: sequenceDec{fse: &fseDecoder{}}, - mlDec: sequenceDec{fse: &fseDecoder{}}, - } - if string(b[:4]) != dictMagic { - return nil, ErrMagicMismatch - } - d.id = binary.LittleEndian.Uint32(b[4:8]) - if d.id == 0 { - return nil, errors.New("dictionaries cannot have ID 0") - } - - // Read literal table - var err error - d.litEnc, b, err = huff0.ReadTable(b[8:], nil) - if err != nil { - return nil, fmt.Errorf("loading literal table: %w", err) - } - d.litEnc.Reuse = huff0.ReusePolicyMust - - br := byteReader{ - b: b, - off: 0, - } - readDec := func(i tableIndex, dec *fseDecoder) error { - if err := dec.readNCount(&br, uint16(maxTableSymbol[i])); err != nil { - return err - } - if br.overread() { - return io.ErrUnexpectedEOF - } - err = dec.transform(symbolTableX[i]) - if err != nil { - println("Transform table error:", err) - return err - } - if debugDecoder || debugEncoder { - println("Read table ok", "symbolLen:", dec.symbolLen) - } - // Set decoders as predefined so they aren't reused. - dec.preDefined = true - return nil - } - - if err := readDec(tableOffsets, d.ofDec.fse); err != nil { - return nil, err - } - if err := readDec(tableMatchLengths, d.mlDec.fse); err != nil { - return nil, err - } - if err := readDec(tableLiteralLengths, d.llDec.fse); err != nil { - return nil, err - } - if br.remain() < 12 { - return nil, io.ErrUnexpectedEOF - } - - d.offsets[0] = int(br.Uint32()) - br.advance(4) - d.offsets[1] = int(br.Uint32()) - br.advance(4) - d.offsets[2] = int(br.Uint32()) - br.advance(4) - if d.offsets[0] <= 0 || d.offsets[1] <= 0 || d.offsets[2] <= 0 { - return nil, errors.New("invalid offset in dictionary") - } - d.content = make([]byte, br.remain()) - copy(d.content, br.unread()) - if d.offsets[0] > len(d.content) || d.offsets[1] > len(d.content) || d.offsets[2] > len(d.content) { - return nil, fmt.Errorf("initial offset bigger than dictionary content size %d, offsets: %v", len(d.content), d.offsets) - } - - return &d, nil -} - -// InspectDictionary loads a zstd dictionary and provides functions to inspect the content. -func InspectDictionary(b []byte) (interface { - ID() uint32 - ContentSize() int - Content() []byte - Offsets() [3]int - LitEncoder() *huff0.Scratch -}, error) { - initPredefined() - d, err := loadDict(b) - return d, err -} - -type BuildDictOptions struct { - // Dictionary ID. - ID uint32 - - // Content to use to create dictionary tables. - Contents [][]byte - - // History to use for all blocks. - History []byte - - // Offsets to use. - Offsets [3]int - - // CompatV155 will make the dictionary compatible with Zstd v1.5.5 and earlier. - // See https://github.com/facebook/zstd/issues/3724 - CompatV155 bool - - // Use the specified encoder level. - // The dictionary will be built using the specified encoder level, - // which will reflect speed and make the dictionary tailored for that level. - // If not set SpeedBestCompression will be used. - Level EncoderLevel - - // DebugOut will write stats and other details here if set. - DebugOut io.Writer -} - -func BuildDict(o BuildDictOptions) ([]byte, error) { - initPredefined() - hist := o.History - contents := o.Contents - debug := o.DebugOut != nil - println := func(args ...interface{}) { - if o.DebugOut != nil { - fmt.Fprintln(o.DebugOut, args...) - } - } - printf := func(s string, args ...interface{}) { - if o.DebugOut != nil { - fmt.Fprintf(o.DebugOut, s, args...) - } - } - print := func(args ...interface{}) { - if o.DebugOut != nil { - fmt.Fprint(o.DebugOut, args...) - } - } - - if int64(len(hist)) > dictMaxLength { - return nil, fmt.Errorf("dictionary of size %d > %d", len(hist), int64(dictMaxLength)) - } - if len(hist) < 8 { - return nil, fmt.Errorf("dictionary of size %d < %d", len(hist), 8) - } - if len(contents) == 0 { - return nil, errors.New("no content provided") - } - d := dict{ - id: o.ID, - litEnc: nil, - llDec: sequenceDec{}, - ofDec: sequenceDec{}, - mlDec: sequenceDec{}, - offsets: o.Offsets, - content: hist, - } - block := blockEnc{lowMem: false} - block.init() - enc := encoder(&bestFastEncoder{fastBase: fastBase{maxMatchOff: int32(maxMatchLen), bufferReset: math.MaxInt32 - int32(maxMatchLen*2), lowMem: false}}) - if o.Level != 0 { - eOpts := encoderOptions{ - level: o.Level, - blockSize: maxMatchLen, - windowSize: maxMatchLen, - dict: &d, - lowMem: false, - } - enc = eOpts.encoder() - } else { - o.Level = SpeedBestCompression - } - var ( - remain [256]int - ll [256]int - ml [256]int - of [256]int - ) - addValues := func(dst *[256]int, src []byte) { - for _, v := range src { - dst[v]++ - } - } - addHist := func(dst *[256]int, src *[256]uint32) { - for i, v := range src { - dst[i] += int(v) - } - } - seqs := 0 - nUsed := 0 - litTotal := 0 - newOffsets := make(map[uint32]int, 1000) - for _, b := range contents { - block.reset(nil) - if len(b) < 8 { - continue - } - nUsed++ - enc.Reset(&d, true) - enc.Encode(&block, b) - addValues(&remain, block.literals) - litTotal += len(block.literals) - seqs += len(block.sequences) - block.genCodes() - addHist(&ll, block.coders.llEnc.Histogram()) - addHist(&ml, block.coders.mlEnc.Histogram()) - addHist(&of, block.coders.ofEnc.Histogram()) - for i, seq := range block.sequences { - if i > 3 { - break - } - offset := seq.offset - if offset == 0 { - continue - } - if offset > 3 { - newOffsets[offset-3]++ - } else { - newOffsets[uint32(o.Offsets[offset-1])]++ - } - } - } - // Find most used offsets. - var sortedOffsets []uint32 - for k := range newOffsets { - sortedOffsets = append(sortedOffsets, k) - } - sort.Slice(sortedOffsets, func(i, j int) bool { - a, b := sortedOffsets[i], sortedOffsets[j] - if a == b { - // Prefer the longer offset - return sortedOffsets[i] > sortedOffsets[j] - } - return newOffsets[sortedOffsets[i]] > newOffsets[sortedOffsets[j]] - }) - if len(sortedOffsets) > 3 { - if debug { - print("Offsets:") - for i, v := range sortedOffsets { - if i > 20 { - break - } - printf("[%d: %d],", v, newOffsets[v]) - } - println("") - } - - sortedOffsets = sortedOffsets[:3] - } - for i, v := range sortedOffsets { - o.Offsets[i] = int(v) - } - if debug { - println("New repeat offsets", o.Offsets) - } - - if nUsed == 0 || seqs == 0 { - return nil, fmt.Errorf("%d blocks, %d sequences found", nUsed, seqs) - } - if debug { - println("Sequences:", seqs, "Blocks:", nUsed, "Literals:", litTotal) - } - if seqs/nUsed < 512 { - // Use 512 as minimum. - nUsed = seqs / 512 - } - copyHist := func(dst *fseEncoder, src *[256]int) ([]byte, error) { - hist := dst.Histogram() - var maxSym uint8 - var maxCount int - var fakeLength int - for i, v := range src { - if v > 0 { - v = v / nUsed - if v == 0 { - v = 1 - } - } - if v > maxCount { - maxCount = v - } - if v != 0 { - maxSym = uint8(i) - } - fakeLength += v - hist[i] = uint32(v) - } - dst.HistogramFinished(maxSym, maxCount) - dst.reUsed = false - dst.useRLE = false - err := dst.normalizeCount(fakeLength) - if err != nil { - return nil, err - } - if debug { - println("RAW:", dst.count[:maxSym+1], "NORM:", dst.norm[:maxSym+1], "LEN:", fakeLength) - } - return dst.writeCount(nil) - } - if debug { - print("Literal lengths: ") - } - llTable, err := copyHist(block.coders.llEnc, &ll) - if err != nil { - return nil, err - } - if debug { - print("Match lengths: ") - } - mlTable, err := copyHist(block.coders.mlEnc, &ml) - if err != nil { - return nil, err - } - if debug { - print("Offsets: ") - } - ofTable, err := copyHist(block.coders.ofEnc, &of) - if err != nil { - return nil, err - } - - // Literal table - avgSize := litTotal - if avgSize > huff0.BlockSizeMax/2 { - avgSize = huff0.BlockSizeMax / 2 - } - huffBuff := make([]byte, 0, avgSize) - // Target size - div := litTotal / avgSize - if div < 1 { - div = 1 - } - if debug { - println("Huffman weights:") - } - for i, n := range remain[:] { - if n > 0 { - n = n / div - // Allow all entries to be represented. - if n == 0 { - n = 1 - } - huffBuff = append(huffBuff, bytes.Repeat([]byte{byte(i)}, n)...) - if debug { - printf("[%d: %d], ", i, n) - } - } - } - if o.CompatV155 && remain[255]/div == 0 { - huffBuff = append(huffBuff, 255) - } - scratch := &huff0.Scratch{TableLog: 11} - for tries := 0; tries < 255; tries++ { - scratch = &huff0.Scratch{TableLog: 11} - _, _, err = huff0.Compress1X(huffBuff, scratch) - if err == nil { - break - } - if debug { - printf("Try %d: Huffman error: %v\n", tries+1, err) - } - huffBuff = huffBuff[:0] - if tries == 250 { - if debug { - println("Huffman: Bailing out with predefined table") - } - - // Bail out.... Just generate something - huffBuff = append(huffBuff, bytes.Repeat([]byte{255}, 10000)...) - for i := 0; i < 128; i++ { - huffBuff = append(huffBuff, byte(i)) - } - continue - } - if errors.Is(err, huff0.ErrIncompressible) { - // Try truncating least common. - for i, n := range remain[:] { - if n > 0 { - n = n / (div * (i + 1)) - if n > 0 { - huffBuff = append(huffBuff, bytes.Repeat([]byte{byte(i)}, n)...) - } - } - } - if o.CompatV155 && len(huffBuff) > 0 && huffBuff[len(huffBuff)-1] != 255 { - huffBuff = append(huffBuff, 255) - } - if len(huffBuff) == 0 { - huffBuff = append(huffBuff, 0, 255) - } - } - if errors.Is(err, huff0.ErrUseRLE) { - for i, n := range remain[:] { - n = n / (div * (i + 1)) - // Allow all entries to be represented. - if n == 0 { - n = 1 - } - huffBuff = append(huffBuff, bytes.Repeat([]byte{byte(i)}, n)...) - } - } - } - - var out bytes.Buffer - out.Write([]byte(dictMagic)) - out.Write(binary.LittleEndian.AppendUint32(nil, o.ID)) - out.Write(scratch.OutTable) - if debug { - println("huff table:", len(scratch.OutTable), "bytes") - println("of table:", len(ofTable), "bytes") - println("ml table:", len(mlTable), "bytes") - println("ll table:", len(llTable), "bytes") - } - out.Write(ofTable) - out.Write(mlTable) - out.Write(llTable) - out.Write(binary.LittleEndian.AppendUint32(nil, uint32(o.Offsets[0]))) - out.Write(binary.LittleEndian.AppendUint32(nil, uint32(o.Offsets[1]))) - out.Write(binary.LittleEndian.AppendUint32(nil, uint32(o.Offsets[2]))) - out.Write(hist) - if debug { - _, err := loadDict(out.Bytes()) - if err != nil { - panic(err) - } - i, err := InspectDictionary(out.Bytes()) - if err != nil { - panic(err) - } - println("ID:", i.ID()) - println("Content size:", i.ContentSize()) - println("Encoder:", i.LitEncoder() != nil) - println("Offsets:", i.Offsets()) - var totalSize int - for _, b := range contents { - totalSize += len(b) - } - - encWith := func(opts ...EOption) int { - enc, err := NewWriter(nil, opts...) - if err != nil { - panic(err) - } - defer enc.Close() - var dst []byte - var totalSize int - for _, b := range contents { - dst = enc.EncodeAll(b, dst[:0]) - totalSize += len(dst) - } - return totalSize - } - plain := encWith(WithEncoderLevel(o.Level)) - withDict := encWith(WithEncoderLevel(o.Level), WithEncoderDict(out.Bytes())) - println("Input size:", totalSize) - println("Plain Compressed:", plain) - println("Dict Compressed:", withDict) - println("Saved:", plain-withDict, (plain-withDict)/len(contents), "bytes per input (rounded down)") - } - return out.Bytes(), nil -} diff --git a/vendor/github.com/klauspost/compress/zstd/enc_base.go b/vendor/github.com/klauspost/compress/zstd/enc_base.go deleted file mode 100644 index 5ca46038a..000000000 --- a/vendor/github.com/klauspost/compress/zstd/enc_base.go +++ /dev/null @@ -1,173 +0,0 @@ -package zstd - -import ( - "fmt" - "math/bits" - - "github.com/klauspost/compress/zstd/internal/xxhash" -) - -const ( - dictShardBits = 6 -) - -type fastBase struct { - // cur is the offset at the start of hist - cur int32 - // maximum offset. Should be at least 2x block size. - maxMatchOff int32 - bufferReset int32 - hist []byte - crc *xxhash.Digest - tmp [8]byte - blk *blockEnc - lastDictID uint32 - lowMem bool -} - -// CRC returns the underlying CRC writer. -func (e *fastBase) CRC() *xxhash.Digest { - return e.crc -} - -// AppendCRC will append the CRC to the destination slice and return it. -func (e *fastBase) AppendCRC(dst []byte) []byte { - crc := e.crc.Sum(e.tmp[:0]) - dst = append(dst, crc[7], crc[6], crc[5], crc[4]) - return dst -} - -// WindowSize returns the window size of the encoder, -// or a window size small enough to contain the input size, if > 0. -func (e *fastBase) WindowSize(size int64) int32 { - if size > 0 && size < int64(e.maxMatchOff) { - b := int32(1) << uint(bits.Len(uint(size))) - // Keep minimum window. - if b < 1024 { - b = 1024 - } - return b - } - return e.maxMatchOff -} - -// Block returns the current block. -func (e *fastBase) Block() *blockEnc { - return e.blk -} - -func (e *fastBase) addBlock(src []byte) int32 { - if debugAsserts && e.cur > e.bufferReset { - panic(fmt.Sprintf("ecur (%d) > buffer reset (%d)", e.cur, e.bufferReset)) - } - // check if we have space already - if len(e.hist)+len(src) > cap(e.hist) { - if cap(e.hist) == 0 { - e.ensureHist(len(src)) - } else { - if cap(e.hist) < int(e.maxMatchOff+maxCompressedBlockSize) { - panic(fmt.Errorf("unexpected buffer cap %d, want at least %d with window %d", cap(e.hist), e.maxMatchOff+maxCompressedBlockSize, e.maxMatchOff)) - } - // Move down - offset := int32(len(e.hist)) - e.maxMatchOff - copy(e.hist[0:e.maxMatchOff], e.hist[offset:]) - e.cur += offset - e.hist = e.hist[:e.maxMatchOff] - } - } - s := int32(len(e.hist)) - e.hist = append(e.hist, src...) - return s -} - -// ensureHist will ensure that history can keep at least this many bytes. -func (e *fastBase) ensureHist(n int) { - if cap(e.hist) >= n { - return - } - l := e.maxMatchOff - if (e.lowMem && e.maxMatchOff > maxCompressedBlockSize) || e.maxMatchOff <= maxCompressedBlockSize { - l += maxCompressedBlockSize - } else { - l += e.maxMatchOff - } - // Make it at least 1MB. - if l < 1<<20 && !e.lowMem { - l = 1 << 20 - } - // Make it at least the requested size. - if l < int32(n) { - l = int32(n) - } - e.hist = make([]byte, 0, l) -} - -// useBlock will replace the block with the provided one, -// but transfer recent offsets from the previous. -func (e *fastBase) UseBlock(enc *blockEnc) { - enc.reset(e.blk) - e.blk = enc -} - -func (e *fastBase) matchlen(s, t int32, src []byte) int32 { - if debugAsserts { - if s < 0 { - err := fmt.Sprintf("s (%d) < 0", s) - panic(err) - } - if t < 0 { - err := fmt.Sprintf("s (%d) < 0", s) - panic(err) - } - if s-t > e.maxMatchOff { - err := fmt.Sprintf("s (%d) - t (%d) > maxMatchOff (%d)", s, t, e.maxMatchOff) - panic(err) - } - if len(src)-int(s) > maxCompressedBlockSize { - panic(fmt.Sprintf("len(src)-s (%d) > maxCompressedBlockSize (%d)", len(src)-int(s), maxCompressedBlockSize)) - } - } - return int32(matchLen(src[s:], src[t:])) -} - -// Reset the encoding table. -func (e *fastBase) resetBase(d *dict, singleBlock bool) { - if e.blk == nil { - e.blk = &blockEnc{lowMem: e.lowMem} - e.blk.init() - } else { - e.blk.reset(nil) - } - e.blk.initNewEncode() - if e.crc == nil { - e.crc = xxhash.New() - } else { - e.crc.Reset() - } - e.blk.dictLitEnc = nil - if d != nil { - low := e.lowMem - if singleBlock { - e.lowMem = true - } - e.ensureHist(d.ContentSize() + maxCompressedBlockSize) - e.lowMem = low - } - - // We offset current position so everything will be out of reach. - // If above reset line, history will be purged. - if e.cur < e.bufferReset { - e.cur += e.maxMatchOff + int32(len(e.hist)) - } - e.hist = e.hist[:0] - if d != nil { - // Set offsets (currently not used) - for i, off := range d.offsets { - e.blk.recentOffsets[i] = uint32(off) - e.blk.prevRecentOffsets[i] = e.blk.recentOffsets[i] - } - // Transfer litenc. - e.blk.dictLitEnc = d.litEnc - e.hist = append(e.hist, d.content...) - } -} diff --git a/vendor/github.com/klauspost/compress/zstd/enc_best.go b/vendor/github.com/klauspost/compress/zstd/enc_best.go deleted file mode 100644 index 858f8f43a..000000000 --- a/vendor/github.com/klauspost/compress/zstd/enc_best.go +++ /dev/null @@ -1,531 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "bytes" - "fmt" - - "github.com/klauspost/compress" -) - -const ( - bestLongTableBits = 22 // Bits used in the long match table - bestLongTableSize = 1 << bestLongTableBits // Size of the table - bestLongLen = 8 // Bytes used for table hash - - // Note: Increasing the short table bits or making the hash shorter - // can actually lead to compression degradation since it will 'steal' more from the - // long match table and match offsets are quite big. - // This greatly depends on the type of input. - bestShortTableBits = 18 // Bits used in the short match table - bestShortTableSize = 1 << bestShortTableBits // Size of the table - bestShortLen = 4 // Bytes used for table hash - -) - -type match struct { - offset int32 - s int32 - length int32 - rep int32 - est int32 -} - -const highScore = maxMatchLen * 8 - -// estBits will estimate output bits from predefined tables. -func (m *match) estBits(bitsPerByte int32) { - mlc := mlCode(uint32(m.length - zstdMinMatch)) - var ofc uint8 - if m.rep < 0 { - ofc = ofCode(uint32(m.s-m.offset) + 3) - } else { - ofc = ofCode(uint32(m.rep)) - } - // Cost, excluding - ofTT, mlTT := fsePredefEnc[tableOffsets].ct.symbolTT[ofc], fsePredefEnc[tableMatchLengths].ct.symbolTT[mlc] - - // Add cost of match encoding... - m.est = int32(ofTT.outBits + mlTT.outBits) - m.est += int32(ofTT.deltaNbBits>>16 + mlTT.deltaNbBits>>16) - // Subtract savings compared to literal encoding... - m.est -= (m.length * bitsPerByte) >> 10 - if m.est > 0 { - // Unlikely gain.. - m.length = 0 - m.est = highScore - } -} - -// bestFastEncoder uses 2 tables, one for short matches (5 bytes) and one for long matches. -// The long match table contains the previous entry with the same hash, -// effectively making it a "chain" of length 2. -// When we find a long match we choose between the two values and select the longest. -// When we find a short match, after checking the long, we check if we can find a long at n+1 -// and that it is longer (lazy matching). -type bestFastEncoder struct { - fastBase - table [bestShortTableSize]prevEntry - longTable [bestLongTableSize]prevEntry - dictTable []prevEntry - dictLongTable []prevEntry -} - -// Encode improves compression... -func (e *bestFastEncoder) Encode(blk *blockEnc, src []byte) { - const ( - // Input margin is the number of bytes we read (8) - // and the maximum we will read ahead (2) - inputMargin = 8 + 4 - minNonLiteralBlockSize = 16 - ) - - // Protect against e.cur wraparound. - for e.cur >= e.bufferReset-int32(len(e.hist)) { - if len(e.hist) == 0 { - e.table = [bestShortTableSize]prevEntry{} - e.longTable = [bestLongTableSize]prevEntry{} - e.cur = e.maxMatchOff - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff - for i := range e.table[:] { - v := e.table[i].offset - v2 := e.table[i].prev - if v < minOff { - v = 0 - v2 = 0 - } else { - v = v - e.cur + e.maxMatchOff - if v2 < minOff { - v2 = 0 - } else { - v2 = v2 - e.cur + e.maxMatchOff - } - } - e.table[i] = prevEntry{ - offset: v, - prev: v2, - } - } - for i := range e.longTable[:] { - v := e.longTable[i].offset - v2 := e.longTable[i].prev - if v < minOff { - v = 0 - v2 = 0 - } else { - v = v - e.cur + e.maxMatchOff - if v2 < minOff { - v2 = 0 - } else { - v2 = v2 - e.cur + e.maxMatchOff - } - } - e.longTable[i] = prevEntry{ - offset: v, - prev: v2, - } - } - e.cur = e.maxMatchOff - break - } - - s := e.addBlock(src) - blk.size = len(src) - if len(src) < minNonLiteralBlockSize { - blk.extraLits = len(src) - blk.literals = blk.literals[:len(src)] - copy(blk.literals, src) - return - } - - // Use this to estimate literal cost. - // Scaled by 10 bits. - bitsPerByte := int32((compress.ShannonEntropyBits(src) * 1024) / len(src)) - // Huffman can never go < 1 bit/byte - if bitsPerByte < 1024 { - bitsPerByte = 1024 - } - - // Override src - src = e.hist - sLimit := int32(len(src)) - inputMargin - const kSearchStrength = 10 - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := s - - // Relative offsets - offset1 := int32(blk.recentOffsets[0]) - offset2 := int32(blk.recentOffsets[1]) - offset3 := int32(blk.recentOffsets[2]) - - addLiterals := func(s *seq, until int32) { - if until == nextEmit { - return - } - blk.literals = append(blk.literals, src[nextEmit:until]...) - s.litLen = uint32(until - nextEmit) - } - - if debugEncoder { - println("recent offsets:", blk.recentOffsets) - } - -encodeLoop: - for { - // We allow the encoder to optionally turn off repeat offsets across blocks - canRepeat := len(blk.sequences) > 2 - - if debugAsserts && canRepeat && offset1 == 0 { - panic("offset0 was 0") - } - - const goodEnough = 250 - - cv := load6432(src, s) - - nextHashL := hashLen(cv, bestLongTableBits, bestLongLen) - nextHashS := hashLen(cv, bestShortTableBits, bestShortLen) - candidateL := e.longTable[nextHashL] - candidateS := e.table[nextHashS] - - // Set m to a match at offset if it looks like that will improve compression. - improve := func(m *match, offset int32, s int32, first uint32, rep int32) { - delta := s - offset - if delta >= e.maxMatchOff || delta <= 0 || load3232(src, offset) != first { - return - } - if debugAsserts { - if offset >= s { - panic(fmt.Sprintf("offset: %d - s:%d - rep: %d - cur :%d - max: %d", offset, s, rep, e.cur, e.maxMatchOff)) - } - if !bytes.Equal(src[s:s+4], src[offset:offset+4]) { - panic(fmt.Sprintf("first match mismatch: %v != %v, first: %08x", src[s:s+4], src[offset:offset+4], first)) - } - } - // Try to quick reject if we already have a long match. - if m.length > 16 { - left := len(src) - int(m.s+m.length) - // If we are too close to the end, keep as is. - if left <= 0 { - return - } - checkLen := m.length - (s - m.s) - 8 - if left > 2 && checkLen > 4 { - // Check 4 bytes, 4 bytes from the end of the current match. - a := load3232(src, offset+checkLen) - b := load3232(src, s+checkLen) - if a != b { - return - } - } - } - l := 4 + e.matchlen(s+4, offset+4, src) - if rep < 0 { - // Extend candidate match backwards as far as possible. - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for offset > tMin && s > nextEmit && src[offset-1] == src[s-1] && l < maxMatchLength { - s-- - offset-- - l++ - } - } - - cand := match{offset: offset, s: s, length: l, rep: rep} - cand.estBits(bitsPerByte) - if m.est >= highScore || cand.est-m.est+(cand.s-m.s)*bitsPerByte>>10 < 0 { - *m = cand - } - } - - best := match{s: s, est: highScore} - improve(&best, candidateL.offset-e.cur, s, uint32(cv), -1) - improve(&best, candidateL.prev-e.cur, s, uint32(cv), -1) - improve(&best, candidateS.offset-e.cur, s, uint32(cv), -1) - improve(&best, candidateS.prev-e.cur, s, uint32(cv), -1) - - if canRepeat && best.length < goodEnough { - if s == nextEmit { - // Check repeats straight after a match. - improve(&best, s-offset2, s, uint32(cv), 1|4) - improve(&best, s-offset3, s, uint32(cv), 2|4) - if offset1 > 1 { - improve(&best, s-(offset1-1), s, uint32(cv), 3|4) - } - } - - // If either no match or a non-repeat match, check at + 1 - if best.rep <= 0 { - cv32 := uint32(cv >> 8) - spp := s + 1 - improve(&best, spp-offset1, spp, cv32, 1) - improve(&best, spp-offset2, spp, cv32, 2) - improve(&best, spp-offset3, spp, cv32, 3) - if best.rep < 0 { - cv32 = uint32(cv >> 24) - spp += 2 - improve(&best, spp-offset1, spp, cv32, 1) - improve(&best, spp-offset2, spp, cv32, 2) - improve(&best, spp-offset3, spp, cv32, 3) - } - } - } - // Load next and check... - e.longTable[nextHashL] = prevEntry{offset: s + e.cur, prev: candidateL.offset} - e.table[nextHashS] = prevEntry{offset: s + e.cur, prev: candidateS.offset} - - // Look far ahead, unless we have a really long match already... - if best.length < goodEnough { - // No match found, move forward on input, no need to check forward... - if best.length < 4 { - s += 1 + (s-nextEmit)>>(kSearchStrength-1) - if s >= sLimit { - break encodeLoop - } - continue - } - - candidateS = e.table[hashLen(cv>>8, bestShortTableBits, bestShortLen)] - cv = load6432(src, s+1) - cv2 := load6432(src, s+2) - candidateL = e.longTable[hashLen(cv, bestLongTableBits, bestLongLen)] - candidateL2 := e.longTable[hashLen(cv2, bestLongTableBits, bestLongLen)] - - // Short at s+1 - improve(&best, candidateS.offset-e.cur, s+1, uint32(cv), -1) - // Long at s+1, s+2 - improve(&best, candidateL.offset-e.cur, s+1, uint32(cv), -1) - improve(&best, candidateL.prev-e.cur, s+1, uint32(cv), -1) - improve(&best, candidateL2.offset-e.cur, s+2, uint32(cv2), -1) - improve(&best, candidateL2.prev-e.cur, s+2, uint32(cv2), -1) - if false { - // Short at s+3. - // Too often worse... - improve(&best, e.table[hashLen(cv2>>8, bestShortTableBits, bestShortLen)].offset-e.cur, s+3, uint32(cv2>>8), -1) - } - - // Start check at a fixed offset to allow for a few mismatches. - // For this compression level 2 yields the best results. - // We cannot do this if we have already indexed this position. - const skipBeginning = 2 - if best.s > s-skipBeginning { - // See if we can find a better match by checking where the current best ends. - // Use that offset to see if we can find a better full match. - if sAt := best.s + best.length; sAt < sLimit { - nextHashL := hashLen(load6432(src, sAt), bestLongTableBits, bestLongLen) - candidateEnd := e.longTable[nextHashL] - - if off := candidateEnd.offset - e.cur - best.length + skipBeginning; off >= 0 { - improve(&best, off, best.s+skipBeginning, load3232(src, best.s+skipBeginning), -1) - if off := candidateEnd.prev - e.cur - best.length + skipBeginning; off >= 0 { - improve(&best, off, best.s+skipBeginning, load3232(src, best.s+skipBeginning), -1) - } - } - } - } - } - - if debugAsserts { - if !bytes.Equal(src[best.s:best.s+best.length], src[best.offset:best.offset+best.length]) { - panic(fmt.Sprintf("match mismatch: %v != %v", src[best.s:best.s+best.length], src[best.offset:best.offset+best.length])) - } - } - - // We have a match, we can store the forward value - if best.rep > 0 { - var seq seq - seq.matchLen = uint32(best.length - zstdMinMatch) - if debugAsserts && s < nextEmit { - panic("s < nextEmit") - } - addLiterals(&seq, best.s) - - // Repeat. If bit 4 is set, this is a non-lit repeat. - seq.offset = uint32(best.rep & 3) - if debugSequences { - println("repeat sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Index old s + 1 -> s - 1 - index0 := s + 1 - s = best.s + best.length - - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, best.length) - } - break encodeLoop - } - // Index skipped... - off := index0 + e.cur - for index0 < s { - cv0 := load6432(src, index0) - h0 := hashLen(cv0, bestLongTableBits, bestLongLen) - h1 := hashLen(cv0, bestShortTableBits, bestShortLen) - e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.table[h1] = prevEntry{offset: off, prev: e.table[h1].offset} - off++ - index0++ - } - switch best.rep { - case 2, 4 | 1: - offset1, offset2 = offset2, offset1 - case 3, 4 | 2: - offset1, offset2, offset3 = offset3, offset1, offset2 - case 4 | 3: - offset1, offset2, offset3 = offset1-1, offset1, offset2 - } - continue - } - - // A 4-byte match has been found. Update recent offsets. - // We'll later see if more than 4 bytes. - index0 := s + 1 - s = best.s - t := best.offset - offset1, offset2, offset3 = s-t, offset1, offset2 - - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - - if debugAsserts && int(offset1) > len(src) { - panic("invalid offset") - } - - // Write our sequence - var seq seq - l := best.length - seq.litLen = uint32(s - nextEmit) - seq.matchLen = uint32(l - zstdMinMatch) - if seq.litLen > 0 { - blk.literals = append(blk.literals, src[nextEmit:s]...) - } - seq.offset = uint32(s-t) + 3 - s += l - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - nextEmit = s - if s >= sLimit { - break encodeLoop - } - - // Index old s + 1 -> s - 1 - for index0 < s { - cv0 := load6432(src, index0) - h0 := hashLen(cv0, bestLongTableBits, bestLongLen) - h1 := hashLen(cv0, bestShortTableBits, bestShortLen) - off := index0 + e.cur - e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.table[h1] = prevEntry{offset: off, prev: e.table[h1].offset} - index0++ - } - } - - if int(nextEmit) < len(src) { - blk.literals = append(blk.literals, src[nextEmit:]...) - blk.extraLits = len(src) - int(nextEmit) - } - blk.recentOffsets[0] = uint32(offset1) - blk.recentOffsets[1] = uint32(offset2) - blk.recentOffsets[2] = uint32(offset3) - if debugEncoder { - println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) - } -} - -// EncodeNoHist will encode a block with no history and no following blocks. -// Most notable difference is that src will not be copied for history and -// we do not need to check for max match length. -func (e *bestFastEncoder) EncodeNoHist(blk *blockEnc, src []byte) { - e.ensureHist(len(src)) - e.Encode(blk, src) -} - -// Reset will reset and set a dictionary if not nil -func (e *bestFastEncoder) Reset(d *dict, singleBlock bool) { - e.resetBase(d, singleBlock) - if d == nil { - return - } - // Init or copy dict table - if len(e.dictTable) != len(e.table) || d.id != e.lastDictID { - if len(e.dictTable) != len(e.table) { - e.dictTable = make([]prevEntry, len(e.table)) - } - end := int32(len(d.content)) - 8 + e.maxMatchOff - for i := e.maxMatchOff; i < end; i += 4 { - const hashLog = bestShortTableBits - - cv := load6432(d.content, i-e.maxMatchOff) - nextHash := hashLen(cv, hashLog, bestShortLen) // 0 -> 4 - nextHash1 := hashLen(cv>>8, hashLog, bestShortLen) // 1 -> 5 - nextHash2 := hashLen(cv>>16, hashLog, bestShortLen) // 2 -> 6 - nextHash3 := hashLen(cv>>24, hashLog, bestShortLen) // 3 -> 7 - e.dictTable[nextHash] = prevEntry{ - prev: e.dictTable[nextHash].offset, - offset: i, - } - e.dictTable[nextHash1] = prevEntry{ - prev: e.dictTable[nextHash1].offset, - offset: i + 1, - } - e.dictTable[nextHash2] = prevEntry{ - prev: e.dictTable[nextHash2].offset, - offset: i + 2, - } - e.dictTable[nextHash3] = prevEntry{ - prev: e.dictTable[nextHash3].offset, - offset: i + 3, - } - } - e.lastDictID = d.id - } - - // Init or copy dict table - if len(e.dictLongTable) != len(e.longTable) || d.id != e.lastDictID { - if len(e.dictLongTable) != len(e.longTable) { - e.dictLongTable = make([]prevEntry, len(e.longTable)) - } - if len(d.content) >= 8 { - cv := load6432(d.content, 0) - h := hashLen(cv, bestLongTableBits, bestLongLen) - e.dictLongTable[h] = prevEntry{ - offset: e.maxMatchOff, - prev: e.dictLongTable[h].offset, - } - - end := int32(len(d.content)) - 8 + e.maxMatchOff - off := 8 // First to read - for i := e.maxMatchOff + 1; i < end; i++ { - cv = cv>>8 | (uint64(d.content[off]) << 56) - h := hashLen(cv, bestLongTableBits, bestLongLen) - e.dictLongTable[h] = prevEntry{ - offset: i, - prev: e.dictLongTable[h].offset, - } - off++ - } - } - e.lastDictID = d.id - } - // Reset table to initial state - copy(e.longTable[:], e.dictLongTable) - - e.cur = e.maxMatchOff - // Reset table to initial state - copy(e.table[:], e.dictTable) -} diff --git a/vendor/github.com/klauspost/compress/zstd/enc_better.go b/vendor/github.com/klauspost/compress/zstd/enc_better.go deleted file mode 100644 index 8582f31a7..000000000 --- a/vendor/github.com/klauspost/compress/zstd/enc_better.go +++ /dev/null @@ -1,1242 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import "fmt" - -const ( - betterLongTableBits = 19 // Bits used in the long match table - betterLongTableSize = 1 << betterLongTableBits // Size of the table - betterLongLen = 8 // Bytes used for table hash - - // Note: Increasing the short table bits or making the hash shorter - // can actually lead to compression degradation since it will 'steal' more from the - // long match table and match offsets are quite big. - // This greatly depends on the type of input. - betterShortTableBits = 13 // Bits used in the short match table - betterShortTableSize = 1 << betterShortTableBits // Size of the table - betterShortLen = 5 // Bytes used for table hash - - betterLongTableShardCnt = 1 << (betterLongTableBits - dictShardBits) // Number of shards in the table - betterLongTableShardSize = betterLongTableSize / betterLongTableShardCnt // Size of an individual shard - - betterShortTableShardCnt = 1 << (betterShortTableBits - dictShardBits) // Number of shards in the table - betterShortTableShardSize = betterShortTableSize / betterShortTableShardCnt // Size of an individual shard -) - -type prevEntry struct { - offset int32 - prev int32 -} - -// betterFastEncoder uses 2 tables, one for short matches (5 bytes) and one for long matches. -// The long match table contains the previous entry with the same hash, -// effectively making it a "chain" of length 2. -// When we find a long match we choose between the two values and select the longest. -// When we find a short match, after checking the long, we check if we can find a long at n+1 -// and that it is longer (lazy matching). -type betterFastEncoder struct { - fastBase - table [betterShortTableSize]tableEntry - longTable [betterLongTableSize]prevEntry -} - -type betterFastEncoderDict struct { - betterFastEncoder - dictTable []tableEntry - dictLongTable []prevEntry - shortTableShardDirty [betterShortTableShardCnt]bool - longTableShardDirty [betterLongTableShardCnt]bool - allDirty bool -} - -// Encode improves compression... -func (e *betterFastEncoder) Encode(blk *blockEnc, src []byte) { - const ( - // Input margin is the number of bytes we read (8) - // and the maximum we will read ahead (2) - inputMargin = 8 + 2 - minNonLiteralBlockSize = 16 - ) - - // Protect against e.cur wraparound. - for e.cur >= e.bufferReset-int32(len(e.hist)) { - if len(e.hist) == 0 { - e.table = [betterShortTableSize]tableEntry{} - e.longTable = [betterLongTableSize]prevEntry{} - e.cur = e.maxMatchOff - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff - for i := range e.table[:] { - v := e.table[i].offset - if v < minOff { - v = 0 - } else { - v = v - e.cur + e.maxMatchOff - } - e.table[i].offset = v - } - for i := range e.longTable[:] { - v := e.longTable[i].offset - v2 := e.longTable[i].prev - if v < minOff { - v = 0 - v2 = 0 - } else { - v = v - e.cur + e.maxMatchOff - if v2 < minOff { - v2 = 0 - } else { - v2 = v2 - e.cur + e.maxMatchOff - } - } - e.longTable[i] = prevEntry{ - offset: v, - prev: v2, - } - } - e.cur = e.maxMatchOff - break - } - - s := e.addBlock(src) - blk.size = len(src) - if len(src) < minNonLiteralBlockSize { - blk.extraLits = len(src) - blk.literals = blk.literals[:len(src)] - copy(blk.literals, src) - return - } - - // Override src - src = e.hist - sLimit := int32(len(src)) - inputMargin - // stepSize is the number of bytes to skip on every main loop iteration. - // It should be >= 1. - const stepSize = 1 - - const kSearchStrength = 9 - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := s - cv := load6432(src, s) - - // Relative offsets - offset1 := int32(blk.recentOffsets[0]) - offset2 := int32(blk.recentOffsets[1]) - - addLiterals := func(s *seq, until int32) { - if until == nextEmit { - return - } - blk.literals = append(blk.literals, src[nextEmit:until]...) - s.litLen = uint32(until - nextEmit) - } - if debugEncoder { - println("recent offsets:", blk.recentOffsets) - } - -encodeLoop: - for { - var t int32 - // We allow the encoder to optionally turn off repeat offsets across blocks - canRepeat := len(blk.sequences) > 2 - var matched int32 - - for { - if debugAsserts && canRepeat && offset1 == 0 { - panic("offset0 was 0") - } - - nextHashL := hashLen(cv, betterLongTableBits, betterLongLen) - nextHashS := hashLen(cv, betterShortTableBits, betterShortLen) - candidateL := e.longTable[nextHashL] - candidateS := e.table[nextHashS] - - const repOff = 1 - repIndex := s - offset1 + repOff - off := s + e.cur - e.longTable[nextHashL] = prevEntry{offset: off, prev: candidateL.offset} - e.table[nextHashS] = tableEntry{offset: off, val: uint32(cv)} - - if canRepeat { - if repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>(repOff*8)) { - // Consider history as well. - var seq seq - lenght := 4 + e.matchlen(s+4+repOff, repIndex+4, src) - - seq.matchLen = uint32(lenght - zstdMinMatch) - - // We might be able to match backwards. - // Extend as long as we can. - start := s + repOff - // We end the search early, so we don't risk 0 literals - // and have to do special offset treatment. - startLimit := nextEmit + 1 - - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { - repIndex-- - start-- - seq.matchLen++ - } - addLiterals(&seq, start) - - // rep 0 - seq.offset = 1 - if debugSequences { - println("repeat sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Index match start+1 (long) -> s - 1 - index0 := s + repOff - s += lenght + repOff - - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, lenght) - - } - break encodeLoop - } - // Index skipped... - for index0 < s-1 { - cv0 := load6432(src, index0) - cv1 := cv0 >> 8 - h0 := hashLen(cv0, betterLongTableBits, betterLongLen) - off := index0 + e.cur - e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.table[hashLen(cv1, betterShortTableBits, betterShortLen)] = tableEntry{offset: off + 1, val: uint32(cv1)} - index0 += 2 - } - cv = load6432(src, s) - continue - } - const repOff2 = 1 - - // We deviate from the reference encoder and also check offset 2. - // Still slower and not much better, so disabled. - // repIndex = s - offset2 + repOff2 - if false && repIndex >= 0 && load6432(src, repIndex) == load6432(src, s+repOff) { - // Consider history as well. - var seq seq - lenght := 8 + e.matchlen(s+8+repOff2, repIndex+8, src) - - seq.matchLen = uint32(lenght - zstdMinMatch) - - // We might be able to match backwards. - // Extend as long as we can. - start := s + repOff2 - // We end the search early, so we don't risk 0 literals - // and have to do special offset treatment. - startLimit := nextEmit + 1 - - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { - repIndex-- - start-- - seq.matchLen++ - } - addLiterals(&seq, start) - - // rep 2 - seq.offset = 2 - if debugSequences { - println("repeat sequence 2", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - index0 := s + repOff2 - s += lenght + repOff2 - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, lenght) - - } - break encodeLoop - } - - // Index skipped... - for index0 < s-1 { - cv0 := load6432(src, index0) - cv1 := cv0 >> 8 - h0 := hashLen(cv0, betterLongTableBits, betterLongLen) - off := index0 + e.cur - e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.table[hashLen(cv1, betterShortTableBits, betterShortLen)] = tableEntry{offset: off + 1, val: uint32(cv1)} - index0 += 2 - } - cv = load6432(src, s) - // Swap offsets - offset1, offset2 = offset2, offset1 - continue - } - } - // Find the offsets of our two matches. - coffsetL := candidateL.offset - e.cur - coffsetLP := candidateL.prev - e.cur - - // Check if we have a long match. - if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) { - // Found a long match, at least 8 bytes. - matched = e.matchlen(s+8, coffsetL+8, src) + 8 - t = coffsetL - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugMatches { - println("long match") - } - - if s-coffsetLP < e.maxMatchOff && cv == load6432(src, coffsetLP) { - // Found a long match, at least 8 bytes. - prevMatch := e.matchlen(s+8, coffsetLP+8, src) + 8 - if prevMatch > matched { - matched = prevMatch - t = coffsetLP - } - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugMatches { - println("long match") - } - } - break - } - - // Check if we have a long match on prev. - if s-coffsetLP < e.maxMatchOff && cv == load6432(src, coffsetLP) { - // Found a long match, at least 8 bytes. - matched = e.matchlen(s+8, coffsetLP+8, src) + 8 - t = coffsetLP - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugMatches { - println("long match") - } - break - } - - coffsetS := candidateS.offset - e.cur - - // Check if we have a short match. - if s-coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val { - // found a regular match - matched = e.matchlen(s+4, coffsetS+4, src) + 4 - - // See if we can find a long match at s+1 - const checkAt = 1 - cv := load6432(src, s+checkAt) - nextHashL = hashLen(cv, betterLongTableBits, betterLongLen) - candidateL = e.longTable[nextHashL] - coffsetL = candidateL.offset - e.cur - - // We can store it, since we have at least a 4 byte match. - e.longTable[nextHashL] = prevEntry{offset: s + checkAt + e.cur, prev: candidateL.offset} - if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) { - // Found a long match, at least 8 bytes. - matchedNext := e.matchlen(s+8+checkAt, coffsetL+8, src) + 8 - if matchedNext > matched { - t = coffsetL - s += checkAt - matched = matchedNext - if debugMatches { - println("long match (after short)") - } - break - } - } - - // Check prev long... - coffsetL = candidateL.prev - e.cur - if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) { - // Found a long match, at least 8 bytes. - matchedNext := e.matchlen(s+8+checkAt, coffsetL+8, src) + 8 - if matchedNext > matched { - t = coffsetL - s += checkAt - matched = matchedNext - if debugMatches { - println("prev long match (after short)") - } - break - } - } - t = coffsetS - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugAsserts && t < 0 { - panic("t<0") - } - if debugMatches { - println("short match") - } - break - } - - // No match found, move forward in input. - s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - } - - // Try to find a better match by searching for a long match at the end of the current best match - if s+matched < sLimit { - // Allow some bytes at the beginning to mismatch. - // Sweet spot is around 3 bytes, but depends on input. - // The skipped bytes are tested in Extend backwards, - // and still picked up as part of the match if they do. - const skipBeginning = 3 - - nextHashL := hashLen(load6432(src, s+matched), betterLongTableBits, betterLongLen) - s2 := s + skipBeginning - cv := load3232(src, s2) - candidateL := e.longTable[nextHashL] - coffsetL := candidateL.offset - e.cur - matched + skipBeginning - if coffsetL >= 0 && coffsetL < s2 && s2-coffsetL < e.maxMatchOff && cv == load3232(src, coffsetL) { - // Found a long match, at least 4 bytes. - matchedNext := e.matchlen(s2+4, coffsetL+4, src) + 4 - if matchedNext > matched { - t = coffsetL - s = s2 - matched = matchedNext - if debugMatches { - println("long match at end-of-match") - } - } - } - - // Check prev long... - if true { - coffsetL = candidateL.prev - e.cur - matched + skipBeginning - if coffsetL >= 0 && coffsetL < s2 && s2-coffsetL < e.maxMatchOff && cv == load3232(src, coffsetL) { - // Found a long match, at least 4 bytes. - matchedNext := e.matchlen(s2+4, coffsetL+4, src) + 4 - if matchedNext > matched { - t = coffsetL - s = s2 - matched = matchedNext - if debugMatches { - println("prev long match at end-of-match") - } - } - } - } - } - // A match has been found. Update recent offsets. - offset2 = offset1 - offset1 = s - t - - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - - if debugAsserts && canRepeat && int(offset1) > len(src) { - panic("invalid offset") - } - - // Extend the n-byte match as long as possible. - l := matched - - // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { - s-- - t-- - l++ - } - - // Write our sequence - var seq seq - seq.litLen = uint32(s - nextEmit) - seq.matchLen = uint32(l - zstdMinMatch) - if seq.litLen > 0 { - blk.literals = append(blk.literals, src[nextEmit:s]...) - } - seq.offset = uint32(s-t) + 3 - s += l - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - nextEmit = s - if s >= sLimit { - break encodeLoop - } - - // Index match start+1 (long) -> s - 1 - index0 := s - l + 1 - for index0 < s-1 { - cv0 := load6432(src, index0) - cv1 := cv0 >> 8 - h0 := hashLen(cv0, betterLongTableBits, betterLongLen) - off := index0 + e.cur - e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.table[hashLen(cv1, betterShortTableBits, betterShortLen)] = tableEntry{offset: off + 1, val: uint32(cv1)} - index0 += 2 - } - - cv = load6432(src, s) - if !canRepeat { - continue - } - - // Check offset 2 - for { - o2 := s - offset2 - if load3232(src, o2) != uint32(cv) { - // Do regular search - break - } - - // Store this, since we have it. - nextHashL := hashLen(cv, betterLongTableBits, betterLongLen) - nextHashS := hashLen(cv, betterShortTableBits, betterShortLen) - - // We have at least 4 byte match. - // No need to check backwards. We come straight from a match - l := 4 + e.matchlen(s+4, o2+4, src) - - e.longTable[nextHashL] = prevEntry{offset: s + e.cur, prev: e.longTable[nextHashL].offset} - e.table[nextHashS] = tableEntry{offset: s + e.cur, val: uint32(cv)} - seq.matchLen = uint32(l) - zstdMinMatch - seq.litLen = 0 - - // Since litlen is always 0, this is offset 1. - seq.offset = 1 - s += l - nextEmit = s - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Swap offset 1 and 2. - offset1, offset2 = offset2, offset1 - if s >= sLimit { - // Finished - break encodeLoop - } - cv = load6432(src, s) - } - } - - if int(nextEmit) < len(src) { - blk.literals = append(blk.literals, src[nextEmit:]...) - blk.extraLits = len(src) - int(nextEmit) - } - blk.recentOffsets[0] = uint32(offset1) - blk.recentOffsets[1] = uint32(offset2) - if debugEncoder { - println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) - } -} - -// EncodeNoHist will encode a block with no history and no following blocks. -// Most notable difference is that src will not be copied for history and -// we do not need to check for max match length. -func (e *betterFastEncoder) EncodeNoHist(blk *blockEnc, src []byte) { - e.ensureHist(len(src)) - e.Encode(blk, src) -} - -// Encode improves compression... -func (e *betterFastEncoderDict) Encode(blk *blockEnc, src []byte) { - const ( - // Input margin is the number of bytes we read (8) - // and the maximum we will read ahead (2) - inputMargin = 8 + 2 - minNonLiteralBlockSize = 16 - ) - - // Protect against e.cur wraparound. - for e.cur >= e.bufferReset-int32(len(e.hist)) { - if len(e.hist) == 0 { - for i := range e.table[:] { - e.table[i] = tableEntry{} - } - for i := range e.longTable[:] { - e.longTable[i] = prevEntry{} - } - e.cur = e.maxMatchOff - e.allDirty = true - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff - for i := range e.table[:] { - v := e.table[i].offset - if v < minOff { - v = 0 - } else { - v = v - e.cur + e.maxMatchOff - } - e.table[i].offset = v - } - for i := range e.longTable[:] { - v := e.longTable[i].offset - v2 := e.longTable[i].prev - if v < minOff { - v = 0 - v2 = 0 - } else { - v = v - e.cur + e.maxMatchOff - if v2 < minOff { - v2 = 0 - } else { - v2 = v2 - e.cur + e.maxMatchOff - } - } - e.longTable[i] = prevEntry{ - offset: v, - prev: v2, - } - } - e.allDirty = true - e.cur = e.maxMatchOff - break - } - - s := e.addBlock(src) - blk.size = len(src) - if len(src) < minNonLiteralBlockSize { - blk.extraLits = len(src) - blk.literals = blk.literals[:len(src)] - copy(blk.literals, src) - return - } - - // Override src - src = e.hist - sLimit := int32(len(src)) - inputMargin - // stepSize is the number of bytes to skip on every main loop iteration. - // It should be >= 1. - const stepSize = 1 - - const kSearchStrength = 9 - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := s - cv := load6432(src, s) - - // Relative offsets - offset1 := int32(blk.recentOffsets[0]) - offset2 := int32(blk.recentOffsets[1]) - - addLiterals := func(s *seq, until int32) { - if until == nextEmit { - return - } - blk.literals = append(blk.literals, src[nextEmit:until]...) - s.litLen = uint32(until - nextEmit) - } - if debugEncoder { - println("recent offsets:", blk.recentOffsets) - } - -encodeLoop: - for { - var t int32 - // We allow the encoder to optionally turn off repeat offsets across blocks - canRepeat := len(blk.sequences) > 2 - var matched int32 - - for { - if debugAsserts && canRepeat && offset1 == 0 { - panic("offset0 was 0") - } - - nextHashL := hashLen(cv, betterLongTableBits, betterLongLen) - nextHashS := hashLen(cv, betterShortTableBits, betterShortLen) - candidateL := e.longTable[nextHashL] - candidateS := e.table[nextHashS] - - const repOff = 1 - repIndex := s - offset1 + repOff - off := s + e.cur - e.longTable[nextHashL] = prevEntry{offset: off, prev: candidateL.offset} - e.markLongShardDirty(nextHashL) - e.table[nextHashS] = tableEntry{offset: off, val: uint32(cv)} - e.markShortShardDirty(nextHashS) - - if canRepeat { - if repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>(repOff*8)) { - // Consider history as well. - var seq seq - lenght := 4 + e.matchlen(s+4+repOff, repIndex+4, src) - - seq.matchLen = uint32(lenght - zstdMinMatch) - - // We might be able to match backwards. - // Extend as long as we can. - start := s + repOff - // We end the search early, so we don't risk 0 literals - // and have to do special offset treatment. - startLimit := nextEmit + 1 - - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { - repIndex-- - start-- - seq.matchLen++ - } - addLiterals(&seq, start) - - // rep 0 - seq.offset = 1 - if debugSequences { - println("repeat sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Index match start+1 (long) -> s - 1 - index0 := s + repOff - s += lenght + repOff - - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, lenght) - - } - break encodeLoop - } - // Index skipped... - for index0 < s-1 { - cv0 := load6432(src, index0) - cv1 := cv0 >> 8 - h0 := hashLen(cv0, betterLongTableBits, betterLongLen) - off := index0 + e.cur - e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.markLongShardDirty(h0) - h1 := hashLen(cv1, betterShortTableBits, betterShortLen) - e.table[h1] = tableEntry{offset: off + 1, val: uint32(cv1)} - e.markShortShardDirty(h1) - index0 += 2 - } - cv = load6432(src, s) - continue - } - const repOff2 = 1 - - // We deviate from the reference encoder and also check offset 2. - // Still slower and not much better, so disabled. - // repIndex = s - offset2 + repOff2 - if false && repIndex >= 0 && load6432(src, repIndex) == load6432(src, s+repOff) { - // Consider history as well. - var seq seq - lenght := 8 + e.matchlen(s+8+repOff2, repIndex+8, src) - - seq.matchLen = uint32(lenght - zstdMinMatch) - - // We might be able to match backwards. - // Extend as long as we can. - start := s + repOff2 - // We end the search early, so we don't risk 0 literals - // and have to do special offset treatment. - startLimit := nextEmit + 1 - - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { - repIndex-- - start-- - seq.matchLen++ - } - addLiterals(&seq, start) - - // rep 2 - seq.offset = 2 - if debugSequences { - println("repeat sequence 2", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - index0 := s + repOff2 - s += lenght + repOff2 - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, lenght) - - } - break encodeLoop - } - - // Index skipped... - for index0 < s-1 { - cv0 := load6432(src, index0) - cv1 := cv0 >> 8 - h0 := hashLen(cv0, betterLongTableBits, betterLongLen) - off := index0 + e.cur - e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.markLongShardDirty(h0) - h1 := hashLen(cv1, betterShortTableBits, betterShortLen) - e.table[h1] = tableEntry{offset: off + 1, val: uint32(cv1)} - e.markShortShardDirty(h1) - index0 += 2 - } - cv = load6432(src, s) - // Swap offsets - offset1, offset2 = offset2, offset1 - continue - } - } - // Find the offsets of our two matches. - coffsetL := candidateL.offset - e.cur - coffsetLP := candidateL.prev - e.cur - - // Check if we have a long match. - if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) { - // Found a long match, at least 8 bytes. - matched = e.matchlen(s+8, coffsetL+8, src) + 8 - t = coffsetL - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugMatches { - println("long match") - } - - if s-coffsetLP < e.maxMatchOff && cv == load6432(src, coffsetLP) { - // Found a long match, at least 8 bytes. - prevMatch := e.matchlen(s+8, coffsetLP+8, src) + 8 - if prevMatch > matched { - matched = prevMatch - t = coffsetLP - } - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugMatches { - println("long match") - } - } - break - } - - // Check if we have a long match on prev. - if s-coffsetLP < e.maxMatchOff && cv == load6432(src, coffsetLP) { - // Found a long match, at least 8 bytes. - matched = e.matchlen(s+8, coffsetLP+8, src) + 8 - t = coffsetLP - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugMatches { - println("long match") - } - break - } - - coffsetS := candidateS.offset - e.cur - - // Check if we have a short match. - if s-coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val { - // found a regular match - matched = e.matchlen(s+4, coffsetS+4, src) + 4 - - // See if we can find a long match at s+1 - const checkAt = 1 - cv := load6432(src, s+checkAt) - nextHashL = hashLen(cv, betterLongTableBits, betterLongLen) - candidateL = e.longTable[nextHashL] - coffsetL = candidateL.offset - e.cur - - // We can store it, since we have at least a 4 byte match. - e.longTable[nextHashL] = prevEntry{offset: s + checkAt + e.cur, prev: candidateL.offset} - e.markLongShardDirty(nextHashL) - if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) { - // Found a long match, at least 8 bytes. - matchedNext := e.matchlen(s+8+checkAt, coffsetL+8, src) + 8 - if matchedNext > matched { - t = coffsetL - s += checkAt - matched = matchedNext - if debugMatches { - println("long match (after short)") - } - break - } - } - - // Check prev long... - coffsetL = candidateL.prev - e.cur - if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) { - // Found a long match, at least 8 bytes. - matchedNext := e.matchlen(s+8+checkAt, coffsetL+8, src) + 8 - if matchedNext > matched { - t = coffsetL - s += checkAt - matched = matchedNext - if debugMatches { - println("prev long match (after short)") - } - break - } - } - t = coffsetS - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugAsserts && t < 0 { - panic("t<0") - } - if debugMatches { - println("short match") - } - break - } - - // No match found, move forward in input. - s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - } - // Try to find a better match by searching for a long match at the end of the current best match - if s+matched < sLimit { - nextHashL := hashLen(load6432(src, s+matched), betterLongTableBits, betterLongLen) - cv := load3232(src, s) - candidateL := e.longTable[nextHashL] - coffsetL := candidateL.offset - e.cur - matched - if coffsetL >= 0 && coffsetL < s && s-coffsetL < e.maxMatchOff && cv == load3232(src, coffsetL) { - // Found a long match, at least 4 bytes. - matchedNext := e.matchlen(s+4, coffsetL+4, src) + 4 - if matchedNext > matched { - t = coffsetL - matched = matchedNext - if debugMatches { - println("long match at end-of-match") - } - } - } - - // Check prev long... - if true { - coffsetL = candidateL.prev - e.cur - matched - if coffsetL >= 0 && coffsetL < s && s-coffsetL < e.maxMatchOff && cv == load3232(src, coffsetL) { - // Found a long match, at least 4 bytes. - matchedNext := e.matchlen(s+4, coffsetL+4, src) + 4 - if matchedNext > matched { - t = coffsetL - matched = matchedNext - if debugMatches { - println("prev long match at end-of-match") - } - } - } - } - } - // A match has been found. Update recent offsets. - offset2 = offset1 - offset1 = s - t - - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - - if debugAsserts && canRepeat && int(offset1) > len(src) { - panic("invalid offset") - } - - // Extend the n-byte match as long as possible. - l := matched - - // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { - s-- - t-- - l++ - } - - // Write our sequence - var seq seq - seq.litLen = uint32(s - nextEmit) - seq.matchLen = uint32(l - zstdMinMatch) - if seq.litLen > 0 { - blk.literals = append(blk.literals, src[nextEmit:s]...) - } - seq.offset = uint32(s-t) + 3 - s += l - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - nextEmit = s - if s >= sLimit { - break encodeLoop - } - - // Index match start+1 (long) -> s - 1 - index0 := s - l + 1 - for index0 < s-1 { - cv0 := load6432(src, index0) - cv1 := cv0 >> 8 - h0 := hashLen(cv0, betterLongTableBits, betterLongLen) - off := index0 + e.cur - e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.markLongShardDirty(h0) - h1 := hashLen(cv1, betterShortTableBits, betterShortLen) - e.table[h1] = tableEntry{offset: off + 1, val: uint32(cv1)} - e.markShortShardDirty(h1) - index0 += 2 - } - - cv = load6432(src, s) - if !canRepeat { - continue - } - - // Check offset 2 - for { - o2 := s - offset2 - if load3232(src, o2) != uint32(cv) { - // Do regular search - break - } - - // Store this, since we have it. - nextHashL := hashLen(cv, betterLongTableBits, betterLongLen) - nextHashS := hashLen(cv, betterShortTableBits, betterShortLen) - - // We have at least 4 byte match. - // No need to check backwards. We come straight from a match - l := 4 + e.matchlen(s+4, o2+4, src) - - e.longTable[nextHashL] = prevEntry{offset: s + e.cur, prev: e.longTable[nextHashL].offset} - e.markLongShardDirty(nextHashL) - e.table[nextHashS] = tableEntry{offset: s + e.cur, val: uint32(cv)} - e.markShortShardDirty(nextHashS) - seq.matchLen = uint32(l) - zstdMinMatch - seq.litLen = 0 - - // Since litlen is always 0, this is offset 1. - seq.offset = 1 - s += l - nextEmit = s - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Swap offset 1 and 2. - offset1, offset2 = offset2, offset1 - if s >= sLimit { - // Finished - break encodeLoop - } - cv = load6432(src, s) - } - } - - if int(nextEmit) < len(src) { - blk.literals = append(blk.literals, src[nextEmit:]...) - blk.extraLits = len(src) - int(nextEmit) - } - blk.recentOffsets[0] = uint32(offset1) - blk.recentOffsets[1] = uint32(offset2) - if debugEncoder { - println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) - } -} - -// ResetDict will reset and set a dictionary if not nil -func (e *betterFastEncoder) Reset(d *dict, singleBlock bool) { - e.resetBase(d, singleBlock) - if d != nil { - panic("betterFastEncoder: Reset with dict") - } -} - -// ResetDict will reset and set a dictionary if not nil -func (e *betterFastEncoderDict) Reset(d *dict, singleBlock bool) { - e.resetBase(d, singleBlock) - if d == nil { - return - } - // Init or copy dict table - if len(e.dictTable) != len(e.table) || d.id != e.lastDictID { - if len(e.dictTable) != len(e.table) { - e.dictTable = make([]tableEntry, len(e.table)) - } - end := int32(len(d.content)) - 8 + e.maxMatchOff - for i := e.maxMatchOff; i < end; i += 4 { - const hashLog = betterShortTableBits - - cv := load6432(d.content, i-e.maxMatchOff) - nextHash := hashLen(cv, hashLog, betterShortLen) // 0 -> 4 - nextHash1 := hashLen(cv>>8, hashLog, betterShortLen) // 1 -> 5 - nextHash2 := hashLen(cv>>16, hashLog, betterShortLen) // 2 -> 6 - nextHash3 := hashLen(cv>>24, hashLog, betterShortLen) // 3 -> 7 - e.dictTable[nextHash] = tableEntry{ - val: uint32(cv), - offset: i, - } - e.dictTable[nextHash1] = tableEntry{ - val: uint32(cv >> 8), - offset: i + 1, - } - e.dictTable[nextHash2] = tableEntry{ - val: uint32(cv >> 16), - offset: i + 2, - } - e.dictTable[nextHash3] = tableEntry{ - val: uint32(cv >> 24), - offset: i + 3, - } - } - e.lastDictID = d.id - e.allDirty = true - } - - // Init or copy dict table - if len(e.dictLongTable) != len(e.longTable) || d.id != e.lastDictID { - if len(e.dictLongTable) != len(e.longTable) { - e.dictLongTable = make([]prevEntry, len(e.longTable)) - } - if len(d.content) >= 8 { - cv := load6432(d.content, 0) - h := hashLen(cv, betterLongTableBits, betterLongLen) - e.dictLongTable[h] = prevEntry{ - offset: e.maxMatchOff, - prev: e.dictLongTable[h].offset, - } - - end := int32(len(d.content)) - 8 + e.maxMatchOff - off := 8 // First to read - for i := e.maxMatchOff + 1; i < end; i++ { - cv = cv>>8 | (uint64(d.content[off]) << 56) - h := hashLen(cv, betterLongTableBits, betterLongLen) - e.dictLongTable[h] = prevEntry{ - offset: i, - prev: e.dictLongTable[h].offset, - } - off++ - } - } - e.lastDictID = d.id - e.allDirty = true - } - - // Reset table to initial state - { - dirtyShardCnt := 0 - if !e.allDirty { - for i := range e.shortTableShardDirty { - if e.shortTableShardDirty[i] { - dirtyShardCnt++ - } - } - } - const shardCnt = betterShortTableShardCnt - const shardSize = betterShortTableShardSize - if e.allDirty || dirtyShardCnt > shardCnt*4/6 { - copy(e.table[:], e.dictTable) - for i := range e.shortTableShardDirty { - e.shortTableShardDirty[i] = false - } - } else { - for i := range e.shortTableShardDirty { - if !e.shortTableShardDirty[i] { - continue - } - - copy(e.table[i*shardSize:(i+1)*shardSize], e.dictTable[i*shardSize:(i+1)*shardSize]) - e.shortTableShardDirty[i] = false - } - } - } - { - dirtyShardCnt := 0 - if !e.allDirty { - for i := range e.shortTableShardDirty { - if e.shortTableShardDirty[i] { - dirtyShardCnt++ - } - } - } - const shardCnt = betterLongTableShardCnt - const shardSize = betterLongTableShardSize - if e.allDirty || dirtyShardCnt > shardCnt*4/6 { - copy(e.longTable[:], e.dictLongTable) - for i := range e.longTableShardDirty { - e.longTableShardDirty[i] = false - } - } else { - for i := range e.longTableShardDirty { - if !e.longTableShardDirty[i] { - continue - } - - copy(e.longTable[i*shardSize:(i+1)*shardSize], e.dictLongTable[i*shardSize:(i+1)*shardSize]) - e.longTableShardDirty[i] = false - } - } - } - e.cur = e.maxMatchOff - e.allDirty = false -} - -func (e *betterFastEncoderDict) markLongShardDirty(entryNum uint32) { - e.longTableShardDirty[entryNum/betterLongTableShardSize] = true -} - -func (e *betterFastEncoderDict) markShortShardDirty(entryNum uint32) { - e.shortTableShardDirty[entryNum/betterShortTableShardSize] = true -} diff --git a/vendor/github.com/klauspost/compress/zstd/enc_dfast.go b/vendor/github.com/klauspost/compress/zstd/enc_dfast.go deleted file mode 100644 index a154c18f7..000000000 --- a/vendor/github.com/klauspost/compress/zstd/enc_dfast.go +++ /dev/null @@ -1,1123 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import "fmt" - -const ( - dFastLongTableBits = 17 // Bits used in the long match table - dFastLongTableSize = 1 << dFastLongTableBits // Size of the table - dFastLongTableMask = dFastLongTableSize - 1 // Mask for table indices. Redundant, but can eliminate bounds checks. - dFastLongLen = 8 // Bytes used for table hash - - dLongTableShardCnt = 1 << (dFastLongTableBits - dictShardBits) // Number of shards in the table - dLongTableShardSize = dFastLongTableSize / tableShardCnt // Size of an individual shard - - dFastShortTableBits = tableBits // Bits used in the short match table - dFastShortTableSize = 1 << dFastShortTableBits // Size of the table - dFastShortTableMask = dFastShortTableSize - 1 // Mask for table indices. Redundant, but can eliminate bounds checks. - dFastShortLen = 5 // Bytes used for table hash - -) - -type doubleFastEncoder struct { - fastEncoder - longTable [dFastLongTableSize]tableEntry -} - -type doubleFastEncoderDict struct { - fastEncoderDict - longTable [dFastLongTableSize]tableEntry - dictLongTable []tableEntry - longTableShardDirty [dLongTableShardCnt]bool -} - -// Encode mimmics functionality in zstd_dfast.c -func (e *doubleFastEncoder) Encode(blk *blockEnc, src []byte) { - const ( - // Input margin is the number of bytes we read (8) - // and the maximum we will read ahead (2) - inputMargin = 8 + 2 - minNonLiteralBlockSize = 16 - ) - - // Protect against e.cur wraparound. - for e.cur >= e.bufferReset-int32(len(e.hist)) { - if len(e.hist) == 0 { - e.table = [dFastShortTableSize]tableEntry{} - e.longTable = [dFastLongTableSize]tableEntry{} - e.cur = e.maxMatchOff - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff - for i := range e.table[:] { - v := e.table[i].offset - if v < minOff { - v = 0 - } else { - v = v - e.cur + e.maxMatchOff - } - e.table[i].offset = v - } - for i := range e.longTable[:] { - v := e.longTable[i].offset - if v < minOff { - v = 0 - } else { - v = v - e.cur + e.maxMatchOff - } - e.longTable[i].offset = v - } - e.cur = e.maxMatchOff - break - } - - s := e.addBlock(src) - blk.size = len(src) - if len(src) < minNonLiteralBlockSize { - blk.extraLits = len(src) - blk.literals = blk.literals[:len(src)] - copy(blk.literals, src) - return - } - - // Override src - src = e.hist - sLimit := int32(len(src)) - inputMargin - // stepSize is the number of bytes to skip on every main loop iteration. - // It should be >= 1. - const stepSize = 1 - - const kSearchStrength = 8 - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := s - cv := load6432(src, s) - - // Relative offsets - offset1 := int32(blk.recentOffsets[0]) - offset2 := int32(blk.recentOffsets[1]) - - addLiterals := func(s *seq, until int32) { - if until == nextEmit { - return - } - blk.literals = append(blk.literals, src[nextEmit:until]...) - s.litLen = uint32(until - nextEmit) - } - if debugEncoder { - println("recent offsets:", blk.recentOffsets) - } - -encodeLoop: - for { - var t int32 - // We allow the encoder to optionally turn off repeat offsets across blocks - canRepeat := len(blk.sequences) > 2 - - for { - if debugAsserts && canRepeat && offset1 == 0 { - panic("offset0 was 0") - } - - nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) - nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen) - candidateL := e.longTable[nextHashL] - candidateS := e.table[nextHashS] - - const repOff = 1 - repIndex := s - offset1 + repOff - entry := tableEntry{offset: s + e.cur, val: uint32(cv)} - e.longTable[nextHashL] = entry - e.table[nextHashS] = entry - - if canRepeat { - if repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>(repOff*8)) { - // Consider history as well. - var seq seq - lenght := 4 + e.matchlen(s+4+repOff, repIndex+4, src) - - seq.matchLen = uint32(lenght - zstdMinMatch) - - // We might be able to match backwards. - // Extend as long as we can. - start := s + repOff - // We end the search early, so we don't risk 0 literals - // and have to do special offset treatment. - startLimit := nextEmit + 1 - - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { - repIndex-- - start-- - seq.matchLen++ - } - addLiterals(&seq, start) - - // rep 0 - seq.offset = 1 - if debugSequences { - println("repeat sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - s += lenght + repOff - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, lenght) - - } - break encodeLoop - } - cv = load6432(src, s) - continue - } - } - // Find the offsets of our two matches. - coffsetL := s - (candidateL.offset - e.cur) - coffsetS := s - (candidateS.offset - e.cur) - - // Check if we have a long match. - if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { - // Found a long match, likely at least 8 bytes. - // Reference encoder checks all 8 bytes, we only check 4, - // but the likelihood of both the first 4 bytes and the hash matching should be enough. - t = candidateL.offset - e.cur - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugMatches { - println("long match") - } - break - } - - // Check if we have a short match. - if coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val { - // found a regular match - // See if we can find a long match at s+1 - const checkAt = 1 - cv := load6432(src, s+checkAt) - nextHashL = hashLen(cv, dFastLongTableBits, dFastLongLen) - candidateL = e.longTable[nextHashL] - coffsetL = s - (candidateL.offset - e.cur) + checkAt - - // We can store it, since we have at least a 4 byte match. - e.longTable[nextHashL] = tableEntry{offset: s + checkAt + e.cur, val: uint32(cv)} - if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { - // Found a long match, likely at least 8 bytes. - // Reference encoder checks all 8 bytes, we only check 4, - // but the likelihood of both the first 4 bytes and the hash matching should be enough. - t = candidateL.offset - e.cur - s += checkAt - if debugMatches { - println("long match (after short)") - } - break - } - - t = candidateS.offset - e.cur - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugAsserts && t < 0 { - panic("t<0") - } - if debugMatches { - println("short match") - } - break - } - - // No match found, move forward in input. - s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - } - - // A 4-byte match has been found. Update recent offsets. - // We'll later see if more than 4 bytes. - offset2 = offset1 - offset1 = s - t - - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - - if debugAsserts && canRepeat && int(offset1) > len(src) { - panic("invalid offset") - } - - // Extend the 4-byte match as long as possible. - l := e.matchlen(s+4, t+4, src) + 4 - - // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { - s-- - t-- - l++ - } - - // Write our sequence - var seq seq - seq.litLen = uint32(s - nextEmit) - seq.matchLen = uint32(l - zstdMinMatch) - if seq.litLen > 0 { - blk.literals = append(blk.literals, src[nextEmit:s]...) - } - seq.offset = uint32(s-t) + 3 - s += l - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - nextEmit = s - if s >= sLimit { - break encodeLoop - } - - // Index match start+1 (long) and start+2 (short) - index0 := s - l + 1 - // Index match end-2 (long) and end-1 (short) - index1 := s - 2 - - cv0 := load6432(src, index0) - cv1 := load6432(src, index1) - te0 := tableEntry{offset: index0 + e.cur, val: uint32(cv0)} - te1 := tableEntry{offset: index1 + e.cur, val: uint32(cv1)} - e.longTable[hashLen(cv0, dFastLongTableBits, dFastLongLen)] = te0 - e.longTable[hashLen(cv1, dFastLongTableBits, dFastLongLen)] = te1 - cv0 >>= 8 - cv1 >>= 8 - te0.offset++ - te1.offset++ - te0.val = uint32(cv0) - te1.val = uint32(cv1) - e.table[hashLen(cv0, dFastShortTableBits, dFastShortLen)] = te0 - e.table[hashLen(cv1, dFastShortTableBits, dFastShortLen)] = te1 - - cv = load6432(src, s) - - if !canRepeat { - continue - } - - // Check offset 2 - for { - o2 := s - offset2 - if load3232(src, o2) != uint32(cv) { - // Do regular search - break - } - - // Store this, since we have it. - nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen) - nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) - - // We have at least 4 byte match. - // No need to check backwards. We come straight from a match - l := 4 + e.matchlen(s+4, o2+4, src) - - entry := tableEntry{offset: s + e.cur, val: uint32(cv)} - e.longTable[nextHashL] = entry - e.table[nextHashS] = entry - seq.matchLen = uint32(l) - zstdMinMatch - seq.litLen = 0 - - // Since litlen is always 0, this is offset 1. - seq.offset = 1 - s += l - nextEmit = s - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Swap offset 1 and 2. - offset1, offset2 = offset2, offset1 - if s >= sLimit { - // Finished - break encodeLoop - } - cv = load6432(src, s) - } - } - - if int(nextEmit) < len(src) { - blk.literals = append(blk.literals, src[nextEmit:]...) - blk.extraLits = len(src) - int(nextEmit) - } - blk.recentOffsets[0] = uint32(offset1) - blk.recentOffsets[1] = uint32(offset2) - if debugEncoder { - println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) - } -} - -// EncodeNoHist will encode a block with no history and no following blocks. -// Most notable difference is that src will not be copied for history and -// we do not need to check for max match length. -func (e *doubleFastEncoder) EncodeNoHist(blk *blockEnc, src []byte) { - const ( - // Input margin is the number of bytes we read (8) - // and the maximum we will read ahead (2) - inputMargin = 8 + 2 - minNonLiteralBlockSize = 16 - ) - - // Protect against e.cur wraparound. - if e.cur >= e.bufferReset { - for i := range e.table[:] { - e.table[i] = tableEntry{} - } - for i := range e.longTable[:] { - e.longTable[i] = tableEntry{} - } - e.cur = e.maxMatchOff - } - - s := int32(0) - blk.size = len(src) - if len(src) < minNonLiteralBlockSize { - blk.extraLits = len(src) - blk.literals = blk.literals[:len(src)] - copy(blk.literals, src) - return - } - - // Override src - sLimit := int32(len(src)) - inputMargin - // stepSize is the number of bytes to skip on every main loop iteration. - // It should be >= 1. - const stepSize = 1 - - const kSearchStrength = 8 - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := s - cv := load6432(src, s) - - // Relative offsets - offset1 := int32(blk.recentOffsets[0]) - offset2 := int32(blk.recentOffsets[1]) - - addLiterals := func(s *seq, until int32) { - if until == nextEmit { - return - } - blk.literals = append(blk.literals, src[nextEmit:until]...) - s.litLen = uint32(until - nextEmit) - } - if debugEncoder { - println("recent offsets:", blk.recentOffsets) - } - -encodeLoop: - for { - var t int32 - for { - - nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) - nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen) - candidateL := e.longTable[nextHashL] - candidateS := e.table[nextHashS] - - const repOff = 1 - repIndex := s - offset1 + repOff - entry := tableEntry{offset: s + e.cur, val: uint32(cv)} - e.longTable[nextHashL] = entry - e.table[nextHashS] = entry - - if len(blk.sequences) > 2 { - if load3232(src, repIndex) == uint32(cv>>(repOff*8)) { - // Consider history as well. - var seq seq - //length := 4 + e.matchlen(s+4+repOff, repIndex+4, src) - length := 4 + int32(matchLen(src[s+4+repOff:], src[repIndex+4:])) - - seq.matchLen = uint32(length - zstdMinMatch) - - // We might be able to match backwards. - // Extend as long as we can. - start := s + repOff - // We end the search early, so we don't risk 0 literals - // and have to do special offset treatment. - startLimit := nextEmit + 1 - - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] { - repIndex-- - start-- - seq.matchLen++ - } - addLiterals(&seq, start) - - // rep 0 - seq.offset = 1 - if debugSequences { - println("repeat sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - s += length + repOff - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, length) - - } - break encodeLoop - } - cv = load6432(src, s) - continue - } - } - // Find the offsets of our two matches. - coffsetL := s - (candidateL.offset - e.cur) - coffsetS := s - (candidateS.offset - e.cur) - - // Check if we have a long match. - if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { - // Found a long match, likely at least 8 bytes. - // Reference encoder checks all 8 bytes, we only check 4, - // but the likelihood of both the first 4 bytes and the hash matching should be enough. - t = candidateL.offset - e.cur - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d). cur: %d", s, t, e.cur)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugMatches { - println("long match") - } - break - } - - // Check if we have a short match. - if coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val { - // found a regular match - // See if we can find a long match at s+1 - const checkAt = 1 - cv := load6432(src, s+checkAt) - nextHashL = hashLen(cv, dFastLongTableBits, dFastLongLen) - candidateL = e.longTable[nextHashL] - coffsetL = s - (candidateL.offset - e.cur) + checkAt - - // We can store it, since we have at least a 4 byte match. - e.longTable[nextHashL] = tableEntry{offset: s + checkAt + e.cur, val: uint32(cv)} - if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { - // Found a long match, likely at least 8 bytes. - // Reference encoder checks all 8 bytes, we only check 4, - // but the likelihood of both the first 4 bytes and the hash matching should be enough. - t = candidateL.offset - e.cur - s += checkAt - if debugMatches { - println("long match (after short)") - } - break - } - - t = candidateS.offset - e.cur - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugAsserts && t < 0 { - panic("t<0") - } - if debugMatches { - println("short match") - } - break - } - - // No match found, move forward in input. - s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - } - - // A 4-byte match has been found. Update recent offsets. - // We'll later see if more than 4 bytes. - offset2 = offset1 - offset1 = s - t - - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - - // Extend the 4-byte match as long as possible. - //l := e.matchlen(s+4, t+4, src) + 4 - l := int32(matchLen(src[s+4:], src[t+4:])) + 4 - - // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for t > tMin && s > nextEmit && src[t-1] == src[s-1] { - s-- - t-- - l++ - } - - // Write our sequence - var seq seq - seq.litLen = uint32(s - nextEmit) - seq.matchLen = uint32(l - zstdMinMatch) - if seq.litLen > 0 { - blk.literals = append(blk.literals, src[nextEmit:s]...) - } - seq.offset = uint32(s-t) + 3 - s += l - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - nextEmit = s - if s >= sLimit { - break encodeLoop - } - - // Index match start+1 (long) and start+2 (short) - index0 := s - l + 1 - // Index match end-2 (long) and end-1 (short) - index1 := s - 2 - - cv0 := load6432(src, index0) - cv1 := load6432(src, index1) - te0 := tableEntry{offset: index0 + e.cur, val: uint32(cv0)} - te1 := tableEntry{offset: index1 + e.cur, val: uint32(cv1)} - e.longTable[hashLen(cv0, dFastLongTableBits, dFastLongLen)] = te0 - e.longTable[hashLen(cv1, dFastLongTableBits, dFastLongLen)] = te1 - cv0 >>= 8 - cv1 >>= 8 - te0.offset++ - te1.offset++ - te0.val = uint32(cv0) - te1.val = uint32(cv1) - e.table[hashLen(cv0, dFastShortTableBits, dFastShortLen)] = te0 - e.table[hashLen(cv1, dFastShortTableBits, dFastShortLen)] = te1 - - cv = load6432(src, s) - - if len(blk.sequences) <= 2 { - continue - } - - // Check offset 2 - for { - o2 := s - offset2 - if load3232(src, o2) != uint32(cv) { - // Do regular search - break - } - - // Store this, since we have it. - nextHashS := hashLen(cv1>>8, dFastShortTableBits, dFastShortLen) - nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) - - // We have at least 4 byte match. - // No need to check backwards. We come straight from a match - //l := 4 + e.matchlen(s+4, o2+4, src) - l := 4 + int32(matchLen(src[s+4:], src[o2+4:])) - - entry := tableEntry{offset: s + e.cur, val: uint32(cv)} - e.longTable[nextHashL] = entry - e.table[nextHashS] = entry - seq.matchLen = uint32(l) - zstdMinMatch - seq.litLen = 0 - - // Since litlen is always 0, this is offset 1. - seq.offset = 1 - s += l - nextEmit = s - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Swap offset 1 and 2. - offset1, offset2 = offset2, offset1 - if s >= sLimit { - // Finished - break encodeLoop - } - cv = load6432(src, s) - } - } - - if int(nextEmit) < len(src) { - blk.literals = append(blk.literals, src[nextEmit:]...) - blk.extraLits = len(src) - int(nextEmit) - } - if debugEncoder { - println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) - } - - // We do not store history, so we must offset e.cur to avoid false matches for next user. - if e.cur < e.bufferReset { - e.cur += int32(len(src)) - } -} - -// Encode will encode the content, with a dictionary if initialized for it. -func (e *doubleFastEncoderDict) Encode(blk *blockEnc, src []byte) { - const ( - // Input margin is the number of bytes we read (8) - // and the maximum we will read ahead (2) - inputMargin = 8 + 2 - minNonLiteralBlockSize = 16 - ) - - // Protect against e.cur wraparound. - for e.cur >= e.bufferReset-int32(len(e.hist)) { - if len(e.hist) == 0 { - for i := range e.table[:] { - e.table[i] = tableEntry{} - } - for i := range e.longTable[:] { - e.longTable[i] = tableEntry{} - } - e.markAllShardsDirty() - e.cur = e.maxMatchOff - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff - for i := range e.table[:] { - v := e.table[i].offset - if v < minOff { - v = 0 - } else { - v = v - e.cur + e.maxMatchOff - } - e.table[i].offset = v - } - for i := range e.longTable[:] { - v := e.longTable[i].offset - if v < minOff { - v = 0 - } else { - v = v - e.cur + e.maxMatchOff - } - e.longTable[i].offset = v - } - e.markAllShardsDirty() - e.cur = e.maxMatchOff - break - } - - s := e.addBlock(src) - blk.size = len(src) - if len(src) < minNonLiteralBlockSize { - blk.extraLits = len(src) - blk.literals = blk.literals[:len(src)] - copy(blk.literals, src) - return - } - - // Override src - src = e.hist - sLimit := int32(len(src)) - inputMargin - // stepSize is the number of bytes to skip on every main loop iteration. - // It should be >= 1. - const stepSize = 1 - - const kSearchStrength = 8 - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := s - cv := load6432(src, s) - - // Relative offsets - offset1 := int32(blk.recentOffsets[0]) - offset2 := int32(blk.recentOffsets[1]) - - addLiterals := func(s *seq, until int32) { - if until == nextEmit { - return - } - blk.literals = append(blk.literals, src[nextEmit:until]...) - s.litLen = uint32(until - nextEmit) - } - if debugEncoder { - println("recent offsets:", blk.recentOffsets) - } - -encodeLoop: - for { - var t int32 - // We allow the encoder to optionally turn off repeat offsets across blocks - canRepeat := len(blk.sequences) > 2 - - for { - if debugAsserts && canRepeat && offset1 == 0 { - panic("offset0 was 0") - } - - nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) - nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen) - candidateL := e.longTable[nextHashL] - candidateS := e.table[nextHashS] - - const repOff = 1 - repIndex := s - offset1 + repOff - entry := tableEntry{offset: s + e.cur, val: uint32(cv)} - e.longTable[nextHashL] = entry - e.markLongShardDirty(nextHashL) - e.table[nextHashS] = entry - e.markShardDirty(nextHashS) - - if canRepeat { - if repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>(repOff*8)) { - // Consider history as well. - var seq seq - lenght := 4 + e.matchlen(s+4+repOff, repIndex+4, src) - - seq.matchLen = uint32(lenght - zstdMinMatch) - - // We might be able to match backwards. - // Extend as long as we can. - start := s + repOff - // We end the search early, so we don't risk 0 literals - // and have to do special offset treatment. - startLimit := nextEmit + 1 - - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { - repIndex-- - start-- - seq.matchLen++ - } - addLiterals(&seq, start) - - // rep 0 - seq.offset = 1 - if debugSequences { - println("repeat sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - s += lenght + repOff - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, lenght) - - } - break encodeLoop - } - cv = load6432(src, s) - continue - } - } - // Find the offsets of our two matches. - coffsetL := s - (candidateL.offset - e.cur) - coffsetS := s - (candidateS.offset - e.cur) - - // Check if we have a long match. - if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { - // Found a long match, likely at least 8 bytes. - // Reference encoder checks all 8 bytes, we only check 4, - // but the likelihood of both the first 4 bytes and the hash matching should be enough. - t = candidateL.offset - e.cur - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugMatches { - println("long match") - } - break - } - - // Check if we have a short match. - if coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val { - // found a regular match - // See if we can find a long match at s+1 - const checkAt = 1 - cv := load6432(src, s+checkAt) - nextHashL = hashLen(cv, dFastLongTableBits, dFastLongLen) - candidateL = e.longTable[nextHashL] - coffsetL = s - (candidateL.offset - e.cur) + checkAt - - // We can store it, since we have at least a 4 byte match. - e.longTable[nextHashL] = tableEntry{offset: s + checkAt + e.cur, val: uint32(cv)} - e.markLongShardDirty(nextHashL) - if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { - // Found a long match, likely at least 8 bytes. - // Reference encoder checks all 8 bytes, we only check 4, - // but the likelihood of both the first 4 bytes and the hash matching should be enough. - t = candidateL.offset - e.cur - s += checkAt - if debugMatches { - println("long match (after short)") - } - break - } - - t = candidateS.offset - e.cur - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugAsserts && t < 0 { - panic("t<0") - } - if debugMatches { - println("short match") - } - break - } - - // No match found, move forward in input. - s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - } - - // A 4-byte match has been found. Update recent offsets. - // We'll later see if more than 4 bytes. - offset2 = offset1 - offset1 = s - t - - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - - if debugAsserts && canRepeat && int(offset1) > len(src) { - panic("invalid offset") - } - - // Extend the 4-byte match as long as possible. - l := e.matchlen(s+4, t+4, src) + 4 - - // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { - s-- - t-- - l++ - } - - // Write our sequence - var seq seq - seq.litLen = uint32(s - nextEmit) - seq.matchLen = uint32(l - zstdMinMatch) - if seq.litLen > 0 { - blk.literals = append(blk.literals, src[nextEmit:s]...) - } - seq.offset = uint32(s-t) + 3 - s += l - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - nextEmit = s - if s >= sLimit { - break encodeLoop - } - - // Index match start+1 (long) and start+2 (short) - index0 := s - l + 1 - // Index match end-2 (long) and end-1 (short) - index1 := s - 2 - - cv0 := load6432(src, index0) - cv1 := load6432(src, index1) - te0 := tableEntry{offset: index0 + e.cur, val: uint32(cv0)} - te1 := tableEntry{offset: index1 + e.cur, val: uint32(cv1)} - longHash1 := hashLen(cv0, dFastLongTableBits, dFastLongLen) - longHash2 := hashLen(cv1, dFastLongTableBits, dFastLongLen) - e.longTable[longHash1] = te0 - e.longTable[longHash2] = te1 - e.markLongShardDirty(longHash1) - e.markLongShardDirty(longHash2) - cv0 >>= 8 - cv1 >>= 8 - te0.offset++ - te1.offset++ - te0.val = uint32(cv0) - te1.val = uint32(cv1) - hashVal1 := hashLen(cv0, dFastShortTableBits, dFastShortLen) - hashVal2 := hashLen(cv1, dFastShortTableBits, dFastShortLen) - e.table[hashVal1] = te0 - e.markShardDirty(hashVal1) - e.table[hashVal2] = te1 - e.markShardDirty(hashVal2) - - cv = load6432(src, s) - - if !canRepeat { - continue - } - - // Check offset 2 - for { - o2 := s - offset2 - if load3232(src, o2) != uint32(cv) { - // Do regular search - break - } - - // Store this, since we have it. - nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) - nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen) - - // We have at least 4 byte match. - // No need to check backwards. We come straight from a match - l := 4 + e.matchlen(s+4, o2+4, src) - - entry := tableEntry{offset: s + e.cur, val: uint32(cv)} - e.longTable[nextHashL] = entry - e.markLongShardDirty(nextHashL) - e.table[nextHashS] = entry - e.markShardDirty(nextHashS) - seq.matchLen = uint32(l) - zstdMinMatch - seq.litLen = 0 - - // Since litlen is always 0, this is offset 1. - seq.offset = 1 - s += l - nextEmit = s - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Swap offset 1 and 2. - offset1, offset2 = offset2, offset1 - if s >= sLimit { - // Finished - break encodeLoop - } - cv = load6432(src, s) - } - } - - if int(nextEmit) < len(src) { - blk.literals = append(blk.literals, src[nextEmit:]...) - blk.extraLits = len(src) - int(nextEmit) - } - blk.recentOffsets[0] = uint32(offset1) - blk.recentOffsets[1] = uint32(offset2) - if debugEncoder { - println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) - } - // If we encoded more than 64K mark all dirty. - if len(src) > 64<<10 { - e.markAllShardsDirty() - } -} - -// ResetDict will reset and set a dictionary if not nil -func (e *doubleFastEncoder) Reset(d *dict, singleBlock bool) { - e.fastEncoder.Reset(d, singleBlock) - if d != nil { - panic("doubleFastEncoder: Reset with dict not supported") - } -} - -// ResetDict will reset and set a dictionary if not nil -func (e *doubleFastEncoderDict) Reset(d *dict, singleBlock bool) { - allDirty := e.allDirty - e.fastEncoderDict.Reset(d, singleBlock) - if d == nil { - return - } - - // Init or copy dict table - if len(e.dictLongTable) != len(e.longTable) || d.id != e.lastDictID { - if len(e.dictLongTable) != len(e.longTable) { - e.dictLongTable = make([]tableEntry, len(e.longTable)) - } - if len(d.content) >= 8 { - cv := load6432(d.content, 0) - e.dictLongTable[hashLen(cv, dFastLongTableBits, dFastLongLen)] = tableEntry{ - val: uint32(cv), - offset: e.maxMatchOff, - } - end := int32(len(d.content)) - 8 + e.maxMatchOff - for i := e.maxMatchOff + 1; i < end; i++ { - cv = cv>>8 | (uint64(d.content[i-e.maxMatchOff+7]) << 56) - e.dictLongTable[hashLen(cv, dFastLongTableBits, dFastLongLen)] = tableEntry{ - val: uint32(cv), - offset: i, - } - } - } - e.lastDictID = d.id - allDirty = true - } - // Reset table to initial state - e.cur = e.maxMatchOff - - dirtyShardCnt := 0 - if !allDirty { - for i := range e.longTableShardDirty { - if e.longTableShardDirty[i] { - dirtyShardCnt++ - } - } - } - - if allDirty || dirtyShardCnt > dLongTableShardCnt/2 { - //copy(e.longTable[:], e.dictLongTable) - e.longTable = *(*[dFastLongTableSize]tableEntry)(e.dictLongTable) - for i := range e.longTableShardDirty { - e.longTableShardDirty[i] = false - } - return - } - for i := range e.longTableShardDirty { - if !e.longTableShardDirty[i] { - continue - } - - // copy(e.longTable[i*dLongTableShardSize:(i+1)*dLongTableShardSize], e.dictLongTable[i*dLongTableShardSize:(i+1)*dLongTableShardSize]) - *(*[dLongTableShardSize]tableEntry)(e.longTable[i*dLongTableShardSize:]) = *(*[dLongTableShardSize]tableEntry)(e.dictLongTable[i*dLongTableShardSize:]) - - e.longTableShardDirty[i] = false - } -} - -func (e *doubleFastEncoderDict) markLongShardDirty(entryNum uint32) { - e.longTableShardDirty[entryNum/dLongTableShardSize] = true -} diff --git a/vendor/github.com/klauspost/compress/zstd/enc_fast.go b/vendor/github.com/klauspost/compress/zstd/enc_fast.go deleted file mode 100644 index f45a3da7d..000000000 --- a/vendor/github.com/klauspost/compress/zstd/enc_fast.go +++ /dev/null @@ -1,891 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "fmt" -) - -const ( - tableBits = 15 // Bits used in the table - tableSize = 1 << tableBits // Size of the table - tableShardCnt = 1 << (tableBits - dictShardBits) // Number of shards in the table - tableShardSize = tableSize / tableShardCnt // Size of an individual shard - tableFastHashLen = 6 - tableMask = tableSize - 1 // Mask for table indices. Redundant, but can eliminate bounds checks. - maxMatchLength = 131074 -) - -type tableEntry struct { - val uint32 - offset int32 -} - -type fastEncoder struct { - fastBase - table [tableSize]tableEntry -} - -type fastEncoderDict struct { - fastEncoder - dictTable []tableEntry - tableShardDirty [tableShardCnt]bool - allDirty bool -} - -// Encode mimmics functionality in zstd_fast.c -func (e *fastEncoder) Encode(blk *blockEnc, src []byte) { - const ( - inputMargin = 8 - minNonLiteralBlockSize = 1 + 1 + inputMargin - ) - - // Protect against e.cur wraparound. - for e.cur >= e.bufferReset-int32(len(e.hist)) { - if len(e.hist) == 0 { - for i := range e.table[:] { - e.table[i] = tableEntry{} - } - e.cur = e.maxMatchOff - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff - for i := range e.table[:] { - v := e.table[i].offset - if v < minOff { - v = 0 - } else { - v = v - e.cur + e.maxMatchOff - } - e.table[i].offset = v - } - e.cur = e.maxMatchOff - break - } - - s := e.addBlock(src) - blk.size = len(src) - if len(src) < minNonLiteralBlockSize { - blk.extraLits = len(src) - blk.literals = blk.literals[:len(src)] - copy(blk.literals, src) - return - } - - // Override src - src = e.hist - sLimit := int32(len(src)) - inputMargin - // stepSize is the number of bytes to skip on every main loop iteration. - // It should be >= 2. - const stepSize = 2 - - // TEMPLATE - const hashLog = tableBits - // seems global, but would be nice to tweak. - const kSearchStrength = 6 - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := s - cv := load6432(src, s) - - // Relative offsets - offset1 := int32(blk.recentOffsets[0]) - offset2 := int32(blk.recentOffsets[1]) - - addLiterals := func(s *seq, until int32) { - if until == nextEmit { - return - } - blk.literals = append(blk.literals, src[nextEmit:until]...) - s.litLen = uint32(until - nextEmit) - } - if debugEncoder { - println("recent offsets:", blk.recentOffsets) - } - -encodeLoop: - for { - // t will contain the match offset when we find one. - // When existing the search loop, we have already checked 4 bytes. - var t int32 - - // We will not use repeat offsets across blocks. - // By not using them for the first 3 matches - canRepeat := len(blk.sequences) > 2 - - for { - if debugAsserts && canRepeat && offset1 == 0 { - panic("offset0 was 0") - } - - nextHash := hashLen(cv, hashLog, tableFastHashLen) - nextHash2 := hashLen(cv>>8, hashLog, tableFastHashLen) - candidate := e.table[nextHash] - candidate2 := e.table[nextHash2] - repIndex := s - offset1 + 2 - - e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} - e.table[nextHash2] = tableEntry{offset: s + e.cur + 1, val: uint32(cv >> 8)} - - if canRepeat && repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>16) { - // Consider history as well. - var seq seq - length := 4 + e.matchlen(s+6, repIndex+4, src) - seq.matchLen = uint32(length - zstdMinMatch) - - // We might be able to match backwards. - // Extend as long as we can. - start := s + 2 - // We end the search early, so we don't risk 0 literals - // and have to do special offset treatment. - startLimit := nextEmit + 1 - - sMin := s - e.maxMatchOff - if sMin < 0 { - sMin = 0 - } - for repIndex > sMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch { - repIndex-- - start-- - seq.matchLen++ - } - addLiterals(&seq, start) - - // rep 0 - seq.offset = 1 - if debugSequences { - println("repeat sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - s += length + 2 - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, length) - - } - break encodeLoop - } - cv = load6432(src, s) - continue - } - coffset0 := s - (candidate.offset - e.cur) - coffset1 := s - (candidate2.offset - e.cur) + 1 - if coffset0 < e.maxMatchOff && uint32(cv) == candidate.val { - // found a regular match - t = candidate.offset - e.cur - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - break - } - - if coffset1 < e.maxMatchOff && uint32(cv>>8) == candidate2.val { - // found a regular match - t = candidate2.offset - e.cur - s++ - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugAsserts && t < 0 { - panic("t<0") - } - break - } - s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - } - // A 4-byte match has been found. We'll later see if more than 4 bytes. - offset2 = offset1 - offset1 = s - t - - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - - if debugAsserts && canRepeat && int(offset1) > len(src) { - panic("invalid offset") - } - - // Extend the 4-byte match as long as possible. - l := e.matchlen(s+4, t+4, src) + 4 - - // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { - s-- - t-- - l++ - } - - // Write our sequence. - var seq seq - seq.litLen = uint32(s - nextEmit) - seq.matchLen = uint32(l - zstdMinMatch) - if seq.litLen > 0 { - blk.literals = append(blk.literals, src[nextEmit:s]...) - } - // Don't use repeat offsets - seq.offset = uint32(s-t) + 3 - s += l - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - nextEmit = s - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - - // Check offset 2 - if o2 := s - offset2; canRepeat && load3232(src, o2) == uint32(cv) { - // We have at least 4 byte match. - // No need to check backwards. We come straight from a match - l := 4 + e.matchlen(s+4, o2+4, src) - - // Store this, since we have it. - nextHash := hashLen(cv, hashLog, tableFastHashLen) - e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} - seq.matchLen = uint32(l) - zstdMinMatch - seq.litLen = 0 - // Since litlen is always 0, this is offset 1. - seq.offset = 1 - s += l - nextEmit = s - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Swap offset 1 and 2. - offset1, offset2 = offset2, offset1 - if s >= sLimit { - break encodeLoop - } - // Prepare next loop. - cv = load6432(src, s) - } - } - - if int(nextEmit) < len(src) { - blk.literals = append(blk.literals, src[nextEmit:]...) - blk.extraLits = len(src) - int(nextEmit) - } - blk.recentOffsets[0] = uint32(offset1) - blk.recentOffsets[1] = uint32(offset2) - if debugEncoder { - println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) - } -} - -// EncodeNoHist will encode a block with no history and no following blocks. -// Most notable difference is that src will not be copied for history and -// we do not need to check for max match length. -func (e *fastEncoder) EncodeNoHist(blk *blockEnc, src []byte) { - const ( - inputMargin = 8 - minNonLiteralBlockSize = 1 + 1 + inputMargin - ) - if debugEncoder { - if len(src) > maxCompressedBlockSize { - panic("src too big") - } - } - - // Protect against e.cur wraparound. - if e.cur >= e.bufferReset { - for i := range e.table[:] { - e.table[i] = tableEntry{} - } - e.cur = e.maxMatchOff - } - - s := int32(0) - blk.size = len(src) - if len(src) < minNonLiteralBlockSize { - blk.extraLits = len(src) - blk.literals = blk.literals[:len(src)] - copy(blk.literals, src) - return - } - - sLimit := int32(len(src)) - inputMargin - // stepSize is the number of bytes to skip on every main loop iteration. - // It should be >= 2. - const stepSize = 2 - - // TEMPLATE - const hashLog = tableBits - // seems global, but would be nice to tweak. - const kSearchStrength = 6 - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := s - cv := load6432(src, s) - - // Relative offsets - offset1 := int32(blk.recentOffsets[0]) - offset2 := int32(blk.recentOffsets[1]) - - addLiterals := func(s *seq, until int32) { - if until == nextEmit { - return - } - blk.literals = append(blk.literals, src[nextEmit:until]...) - s.litLen = uint32(until - nextEmit) - } - if debugEncoder { - println("recent offsets:", blk.recentOffsets) - } - -encodeLoop: - for { - // t will contain the match offset when we find one. - // When existing the search loop, we have already checked 4 bytes. - var t int32 - - // We will not use repeat offsets across blocks. - // By not using them for the first 3 matches - - for { - nextHash := hashLen(cv, hashLog, tableFastHashLen) - nextHash2 := hashLen(cv>>8, hashLog, tableFastHashLen) - candidate := e.table[nextHash] - candidate2 := e.table[nextHash2] - repIndex := s - offset1 + 2 - - e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} - e.table[nextHash2] = tableEntry{offset: s + e.cur + 1, val: uint32(cv >> 8)} - - if len(blk.sequences) > 2 && load3232(src, repIndex) == uint32(cv>>16) { - // Consider history as well. - var seq seq - length := 4 + e.matchlen(s+6, repIndex+4, src) - - seq.matchLen = uint32(length - zstdMinMatch) - - // We might be able to match backwards. - // Extend as long as we can. - start := s + 2 - // We end the search early, so we don't risk 0 literals - // and have to do special offset treatment. - startLimit := nextEmit + 1 - - sMin := s - e.maxMatchOff - if sMin < 0 { - sMin = 0 - } - for repIndex > sMin && start > startLimit && src[repIndex-1] == src[start-1] { - repIndex-- - start-- - seq.matchLen++ - } - addLiterals(&seq, start) - - // rep 0 - seq.offset = 1 - if debugSequences { - println("repeat sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - s += length + 2 - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, length) - - } - break encodeLoop - } - cv = load6432(src, s) - continue - } - coffset0 := s - (candidate.offset - e.cur) - coffset1 := s - (candidate2.offset - e.cur) + 1 - if coffset0 < e.maxMatchOff && uint32(cv) == candidate.val { - // found a regular match - t = candidate.offset - e.cur - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugAsserts && t < 0 { - panic(fmt.Sprintf("t (%d) < 0, candidate.offset: %d, e.cur: %d, coffset0: %d, e.maxMatchOff: %d", t, candidate.offset, e.cur, coffset0, e.maxMatchOff)) - } - break - } - - if coffset1 < e.maxMatchOff && uint32(cv>>8) == candidate2.val { - // found a regular match - t = candidate2.offset - e.cur - s++ - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugAsserts && t < 0 { - panic("t<0") - } - break - } - s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - } - // A 4-byte match has been found. We'll later see if more than 4 bytes. - offset2 = offset1 - offset1 = s - t - - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - - if debugAsserts && t < 0 { - panic(fmt.Sprintf("t (%d) < 0 ", t)) - } - // Extend the 4-byte match as long as possible. - l := e.matchlen(s+4, t+4, src) + 4 - - // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for t > tMin && s > nextEmit && src[t-1] == src[s-1] { - s-- - t-- - l++ - } - - // Write our sequence. - var seq seq - seq.litLen = uint32(s - nextEmit) - seq.matchLen = uint32(l - zstdMinMatch) - if seq.litLen > 0 { - blk.literals = append(blk.literals, src[nextEmit:s]...) - } - // Don't use repeat offsets - seq.offset = uint32(s-t) + 3 - s += l - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - nextEmit = s - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - - // Check offset 2 - if o2 := s - offset2; len(blk.sequences) > 2 && load3232(src, o2) == uint32(cv) { - // We have at least 4 byte match. - // No need to check backwards. We come straight from a match - l := 4 + e.matchlen(s+4, o2+4, src) - - // Store this, since we have it. - nextHash := hashLen(cv, hashLog, tableFastHashLen) - e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} - seq.matchLen = uint32(l) - zstdMinMatch - seq.litLen = 0 - // Since litlen is always 0, this is offset 1. - seq.offset = 1 - s += l - nextEmit = s - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Swap offset 1 and 2. - offset1, offset2 = offset2, offset1 - if s >= sLimit { - break encodeLoop - } - // Prepare next loop. - cv = load6432(src, s) - } - } - - if int(nextEmit) < len(src) { - blk.literals = append(blk.literals, src[nextEmit:]...) - blk.extraLits = len(src) - int(nextEmit) - } - if debugEncoder { - println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) - } - // We do not store history, so we must offset e.cur to avoid false matches for next user. - if e.cur < e.bufferReset { - e.cur += int32(len(src)) - } -} - -// Encode will encode the content, with a dictionary if initialized for it. -func (e *fastEncoderDict) Encode(blk *blockEnc, src []byte) { - const ( - inputMargin = 8 - minNonLiteralBlockSize = 1 + 1 + inputMargin - ) - if e.allDirty || len(src) > 32<<10 { - e.fastEncoder.Encode(blk, src) - e.allDirty = true - return - } - // Protect against e.cur wraparound. - for e.cur >= e.bufferReset-int32(len(e.hist)) { - if len(e.hist) == 0 { - e.table = [tableSize]tableEntry{} - e.cur = e.maxMatchOff - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff - for i := range e.table[:] { - v := e.table[i].offset - if v < minOff { - v = 0 - } else { - v = v - e.cur + e.maxMatchOff - } - e.table[i].offset = v - } - e.cur = e.maxMatchOff - break - } - - s := e.addBlock(src) - blk.size = len(src) - if len(src) < minNonLiteralBlockSize { - blk.extraLits = len(src) - blk.literals = blk.literals[:len(src)] - copy(blk.literals, src) - return - } - - // Override src - src = e.hist - sLimit := int32(len(src)) - inputMargin - // stepSize is the number of bytes to skip on every main loop iteration. - // It should be >= 2. - const stepSize = 2 - - // TEMPLATE - const hashLog = tableBits - // seems global, but would be nice to tweak. - const kSearchStrength = 7 - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := s - cv := load6432(src, s) - - // Relative offsets - offset1 := int32(blk.recentOffsets[0]) - offset2 := int32(blk.recentOffsets[1]) - - addLiterals := func(s *seq, until int32) { - if until == nextEmit { - return - } - blk.literals = append(blk.literals, src[nextEmit:until]...) - s.litLen = uint32(until - nextEmit) - } - if debugEncoder { - println("recent offsets:", blk.recentOffsets) - } - -encodeLoop: - for { - // t will contain the match offset when we find one. - // When existing the search loop, we have already checked 4 bytes. - var t int32 - - // We will not use repeat offsets across blocks. - // By not using them for the first 3 matches - canRepeat := len(blk.sequences) > 2 - - for { - if debugAsserts && canRepeat && offset1 == 0 { - panic("offset0 was 0") - } - - nextHash := hashLen(cv, hashLog, tableFastHashLen) - nextHash2 := hashLen(cv>>8, hashLog, tableFastHashLen) - candidate := e.table[nextHash] - candidate2 := e.table[nextHash2] - repIndex := s - offset1 + 2 - - e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} - e.markShardDirty(nextHash) - e.table[nextHash2] = tableEntry{offset: s + e.cur + 1, val: uint32(cv >> 8)} - e.markShardDirty(nextHash2) - - if canRepeat && repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>16) { - // Consider history as well. - var seq seq - length := 4 + e.matchlen(s+6, repIndex+4, src) - - seq.matchLen = uint32(length - zstdMinMatch) - - // We might be able to match backwards. - // Extend as long as we can. - start := s + 2 - // We end the search early, so we don't risk 0 literals - // and have to do special offset treatment. - startLimit := nextEmit + 1 - - sMin := s - e.maxMatchOff - if sMin < 0 { - sMin = 0 - } - for repIndex > sMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch { - repIndex-- - start-- - seq.matchLen++ - } - addLiterals(&seq, start) - - // rep 0 - seq.offset = 1 - if debugSequences { - println("repeat sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - s += length + 2 - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, length) - - } - break encodeLoop - } - cv = load6432(src, s) - continue - } - coffset0 := s - (candidate.offset - e.cur) - coffset1 := s - (candidate2.offset - e.cur) + 1 - if coffset0 < e.maxMatchOff && uint32(cv) == candidate.val { - // found a regular match - t = candidate.offset - e.cur - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - break - } - - if coffset1 < e.maxMatchOff && uint32(cv>>8) == candidate2.val { - // found a regular match - t = candidate2.offset - e.cur - s++ - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugAsserts && t < 0 { - panic("t<0") - } - break - } - s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - } - // A 4-byte match has been found. We'll later see if more than 4 bytes. - offset2 = offset1 - offset1 = s - t - - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - - if debugAsserts && canRepeat && int(offset1) > len(src) { - panic("invalid offset") - } - - // Extend the 4-byte match as long as possible. - l := e.matchlen(s+4, t+4, src) + 4 - - // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { - s-- - t-- - l++ - } - - // Write our sequence. - var seq seq - seq.litLen = uint32(s - nextEmit) - seq.matchLen = uint32(l - zstdMinMatch) - if seq.litLen > 0 { - blk.literals = append(blk.literals, src[nextEmit:s]...) - } - // Don't use repeat offsets - seq.offset = uint32(s-t) + 3 - s += l - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - nextEmit = s - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - - // Check offset 2 - if o2 := s - offset2; canRepeat && load3232(src, o2) == uint32(cv) { - // We have at least 4 byte match. - // No need to check backwards. We come straight from a match - l := 4 + e.matchlen(s+4, o2+4, src) - - // Store this, since we have it. - nextHash := hashLen(cv, hashLog, tableFastHashLen) - e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} - e.markShardDirty(nextHash) - seq.matchLen = uint32(l) - zstdMinMatch - seq.litLen = 0 - // Since litlen is always 0, this is offset 1. - seq.offset = 1 - s += l - nextEmit = s - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Swap offset 1 and 2. - offset1, offset2 = offset2, offset1 - if s >= sLimit { - break encodeLoop - } - // Prepare next loop. - cv = load6432(src, s) - } - } - - if int(nextEmit) < len(src) { - blk.literals = append(blk.literals, src[nextEmit:]...) - blk.extraLits = len(src) - int(nextEmit) - } - blk.recentOffsets[0] = uint32(offset1) - blk.recentOffsets[1] = uint32(offset2) - if debugEncoder { - println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) - } -} - -// ResetDict will reset and set a dictionary if not nil -func (e *fastEncoder) Reset(d *dict, singleBlock bool) { - e.resetBase(d, singleBlock) - if d != nil { - panic("fastEncoder: Reset with dict") - } -} - -// ResetDict will reset and set a dictionary if not nil -func (e *fastEncoderDict) Reset(d *dict, singleBlock bool) { - e.resetBase(d, singleBlock) - if d == nil { - return - } - - // Init or copy dict table - if len(e.dictTable) != len(e.table) || d.id != e.lastDictID { - if len(e.dictTable) != len(e.table) { - e.dictTable = make([]tableEntry, len(e.table)) - } - if true { - end := e.maxMatchOff + int32(len(d.content)) - 8 - for i := e.maxMatchOff; i < end; i += 2 { - const hashLog = tableBits - - cv := load6432(d.content, i-e.maxMatchOff) - nextHash := hashLen(cv, hashLog, tableFastHashLen) // 0 -> 6 - nextHash1 := hashLen(cv>>8, hashLog, tableFastHashLen) // 1 -> 7 - e.dictTable[nextHash] = tableEntry{ - val: uint32(cv), - offset: i, - } - e.dictTable[nextHash1] = tableEntry{ - val: uint32(cv >> 8), - offset: i + 1, - } - } - } - e.lastDictID = d.id - e.allDirty = true - } - - e.cur = e.maxMatchOff - dirtyShardCnt := 0 - if !e.allDirty { - for i := range e.tableShardDirty { - if e.tableShardDirty[i] { - dirtyShardCnt++ - } - } - } - - const shardCnt = tableShardCnt - const shardSize = tableShardSize - if e.allDirty || dirtyShardCnt > shardCnt*4/6 { - //copy(e.table[:], e.dictTable) - e.table = *(*[tableSize]tableEntry)(e.dictTable) - for i := range e.tableShardDirty { - e.tableShardDirty[i] = false - } - e.allDirty = false - return - } - for i := range e.tableShardDirty { - if !e.tableShardDirty[i] { - continue - } - - //copy(e.table[i*shardSize:(i+1)*shardSize], e.dictTable[i*shardSize:(i+1)*shardSize]) - *(*[shardSize]tableEntry)(e.table[i*shardSize:]) = *(*[shardSize]tableEntry)(e.dictTable[i*shardSize:]) - e.tableShardDirty[i] = false - } - e.allDirty = false -} - -func (e *fastEncoderDict) markAllShardsDirty() { - e.allDirty = true -} - -func (e *fastEncoderDict) markShardDirty(entryNum uint32) { - e.tableShardDirty[entryNum/tableShardSize] = true -} diff --git a/vendor/github.com/klauspost/compress/zstd/encoder.go b/vendor/github.com/klauspost/compress/zstd/encoder.go deleted file mode 100644 index 72af7ef0f..000000000 --- a/vendor/github.com/klauspost/compress/zstd/encoder.go +++ /dev/null @@ -1,619 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "crypto/rand" - "fmt" - "io" - "math" - rdebug "runtime/debug" - "sync" - - "github.com/klauspost/compress/zstd/internal/xxhash" -) - -// Encoder provides encoding to Zstandard. -// An Encoder can be used for either compressing a stream via the -// io.WriteCloser interface supported by the Encoder or as multiple independent -// tasks via the EncodeAll function. -// Smaller encodes are encouraged to use the EncodeAll function. -// Use NewWriter to create a new instance. -type Encoder struct { - o encoderOptions - encoders chan encoder - state encoderState - init sync.Once -} - -type encoder interface { - Encode(blk *blockEnc, src []byte) - EncodeNoHist(blk *blockEnc, src []byte) - Block() *blockEnc - CRC() *xxhash.Digest - AppendCRC([]byte) []byte - WindowSize(size int64) int32 - UseBlock(*blockEnc) - Reset(d *dict, singleBlock bool) -} - -type encoderState struct { - w io.Writer - filling []byte - current []byte - previous []byte - encoder encoder - writing *blockEnc - err error - writeErr error - nWritten int64 - nInput int64 - frameContentSize int64 - headerWritten bool - eofWritten bool - fullFrameWritten bool - - // This waitgroup indicates an encode is running. - wg sync.WaitGroup - // This waitgroup indicates we have a block encoding/writing. - wWg sync.WaitGroup -} - -// NewWriter will create a new Zstandard encoder. -// If the encoder will be used for encoding blocks a nil writer can be used. -func NewWriter(w io.Writer, opts ...EOption) (*Encoder, error) { - initPredefined() - var e Encoder - e.o.setDefault() - for _, o := range opts { - err := o(&e.o) - if err != nil { - return nil, err - } - } - if w != nil { - e.Reset(w) - } - return &e, nil -} - -func (e *Encoder) initialize() { - if e.o.concurrent == 0 { - e.o.setDefault() - } - e.encoders = make(chan encoder, e.o.concurrent) - for i := 0; i < e.o.concurrent; i++ { - enc := e.o.encoder() - e.encoders <- enc - } -} - -// Reset will re-initialize the writer and new writes will encode to the supplied writer -// as a new, independent stream. -func (e *Encoder) Reset(w io.Writer) { - s := &e.state - s.wg.Wait() - s.wWg.Wait() - if cap(s.filling) == 0 { - s.filling = make([]byte, 0, e.o.blockSize) - } - if e.o.concurrent > 1 { - if cap(s.current) == 0 { - s.current = make([]byte, 0, e.o.blockSize) - } - if cap(s.previous) == 0 { - s.previous = make([]byte, 0, e.o.blockSize) - } - s.current = s.current[:0] - s.previous = s.previous[:0] - if s.writing == nil { - s.writing = &blockEnc{lowMem: e.o.lowMem} - s.writing.init() - } - s.writing.initNewEncode() - } - if s.encoder == nil { - s.encoder = e.o.encoder() - } - s.filling = s.filling[:0] - s.encoder.Reset(e.o.dict, false) - s.headerWritten = false - s.eofWritten = false - s.fullFrameWritten = false - s.w = w - s.err = nil - s.nWritten = 0 - s.nInput = 0 - s.writeErr = nil - s.frameContentSize = 0 -} - -// ResetContentSize will reset and set a content size for the next stream. -// If the bytes written does not match the size given an error will be returned -// when calling Close(). -// This is removed when Reset is called. -// Sizes <= 0 results in no content size set. -func (e *Encoder) ResetContentSize(w io.Writer, size int64) { - e.Reset(w) - if size >= 0 { - e.state.frameContentSize = size - } -} - -// Write data to the encoder. -// Input data will be buffered and as the buffer fills up -// content will be compressed and written to the output. -// When done writing, use Close to flush the remaining output -// and write CRC if requested. -func (e *Encoder) Write(p []byte) (n int, err error) { - s := &e.state - for len(p) > 0 { - if len(p)+len(s.filling) < e.o.blockSize { - if e.o.crc { - _, _ = s.encoder.CRC().Write(p) - } - s.filling = append(s.filling, p...) - return n + len(p), nil - } - add := p - if len(p)+len(s.filling) > e.o.blockSize { - add = add[:e.o.blockSize-len(s.filling)] - } - if e.o.crc { - _, _ = s.encoder.CRC().Write(add) - } - s.filling = append(s.filling, add...) - p = p[len(add):] - n += len(add) - if len(s.filling) < e.o.blockSize { - return n, nil - } - err := e.nextBlock(false) - if err != nil { - return n, err - } - if debugAsserts && len(s.filling) > 0 { - panic(len(s.filling)) - } - } - return n, nil -} - -// nextBlock will synchronize and start compressing input in e.state.filling. -// If an error has occurred during encoding it will be returned. -func (e *Encoder) nextBlock(final bool) error { - s := &e.state - // Wait for current block. - s.wg.Wait() - if s.err != nil { - return s.err - } - if len(s.filling) > e.o.blockSize { - return fmt.Errorf("block > maxStoreBlockSize") - } - if !s.headerWritten { - // If we have a single block encode, do a sync compression. - if final && len(s.filling) == 0 && !e.o.fullZero { - s.headerWritten = true - s.fullFrameWritten = true - s.eofWritten = true - return nil - } - if final && len(s.filling) > 0 { - s.current = e.EncodeAll(s.filling, s.current[:0]) - var n2 int - n2, s.err = s.w.Write(s.current) - if s.err != nil { - return s.err - } - s.nWritten += int64(n2) - s.nInput += int64(len(s.filling)) - s.current = s.current[:0] - s.filling = s.filling[:0] - s.headerWritten = true - s.fullFrameWritten = true - s.eofWritten = true - return nil - } - - var tmp [maxHeaderSize]byte - fh := frameHeader{ - ContentSize: uint64(s.frameContentSize), - WindowSize: uint32(s.encoder.WindowSize(s.frameContentSize)), - SingleSegment: false, - Checksum: e.o.crc, - DictID: e.o.dict.ID(), - } - - dst := fh.appendTo(tmp[:0]) - s.headerWritten = true - s.wWg.Wait() - var n2 int - n2, s.err = s.w.Write(dst) - if s.err != nil { - return s.err - } - s.nWritten += int64(n2) - } - if s.eofWritten { - // Ensure we only write it once. - final = false - } - - if len(s.filling) == 0 { - // Final block, but no data. - if final { - enc := s.encoder - blk := enc.Block() - blk.reset(nil) - blk.last = true - blk.encodeRaw(nil) - s.wWg.Wait() - _, s.err = s.w.Write(blk.output) - s.nWritten += int64(len(blk.output)) - s.eofWritten = true - } - return s.err - } - - // SYNC: - if e.o.concurrent == 1 { - src := s.filling - s.nInput += int64(len(s.filling)) - if debugEncoder { - println("Adding sync block,", len(src), "bytes, final:", final) - } - enc := s.encoder - blk := enc.Block() - blk.reset(nil) - enc.Encode(blk, src) - blk.last = final - if final { - s.eofWritten = true - } - - s.err = blk.encode(src, e.o.noEntropy, !e.o.allLitEntropy) - if s.err != nil { - return s.err - } - _, s.err = s.w.Write(blk.output) - s.nWritten += int64(len(blk.output)) - s.filling = s.filling[:0] - return s.err - } - - // Move blocks forward. - s.filling, s.current, s.previous = s.previous[:0], s.filling, s.current - s.nInput += int64(len(s.current)) - s.wg.Add(1) - go func(src []byte) { - if debugEncoder { - println("Adding block,", len(src), "bytes, final:", final) - } - defer func() { - if r := recover(); r != nil { - s.err = fmt.Errorf("panic while encoding: %v", r) - rdebug.PrintStack() - } - s.wg.Done() - }() - enc := s.encoder - blk := enc.Block() - enc.Encode(blk, src) - blk.last = final - if final { - s.eofWritten = true - } - // Wait for pending writes. - s.wWg.Wait() - if s.writeErr != nil { - s.err = s.writeErr - return - } - // Transfer encoders from previous write block. - blk.swapEncoders(s.writing) - // Transfer recent offsets to next. - enc.UseBlock(s.writing) - s.writing = blk - s.wWg.Add(1) - go func() { - defer func() { - if r := recover(); r != nil { - s.writeErr = fmt.Errorf("panic while encoding/writing: %v", r) - rdebug.PrintStack() - } - s.wWg.Done() - }() - s.writeErr = blk.encode(src, e.o.noEntropy, !e.o.allLitEntropy) - if s.writeErr != nil { - return - } - _, s.writeErr = s.w.Write(blk.output) - s.nWritten += int64(len(blk.output)) - }() - }(s.current) - return nil -} - -// ReadFrom reads data from r until EOF or error. -// The return value n is the number of bytes read. -// Any error except io.EOF encountered during the read is also returned. -// -// The Copy function uses ReaderFrom if available. -func (e *Encoder) ReadFrom(r io.Reader) (n int64, err error) { - if debugEncoder { - println("Using ReadFrom") - } - - // Flush any current writes. - if len(e.state.filling) > 0 { - if err := e.nextBlock(false); err != nil { - return 0, err - } - } - e.state.filling = e.state.filling[:e.o.blockSize] - src := e.state.filling - for { - n2, err := r.Read(src) - if e.o.crc { - _, _ = e.state.encoder.CRC().Write(src[:n2]) - } - // src is now the unfilled part... - src = src[n2:] - n += int64(n2) - switch err { - case io.EOF: - e.state.filling = e.state.filling[:len(e.state.filling)-len(src)] - if debugEncoder { - println("ReadFrom: got EOF final block:", len(e.state.filling)) - } - return n, nil - case nil: - default: - if debugEncoder { - println("ReadFrom: got error:", err) - } - e.state.err = err - return n, err - } - if len(src) > 0 { - if debugEncoder { - println("ReadFrom: got space left in source:", len(src)) - } - continue - } - err = e.nextBlock(false) - if err != nil { - return n, err - } - e.state.filling = e.state.filling[:e.o.blockSize] - src = e.state.filling - } -} - -// Flush will send the currently written data to output -// and block until everything has been written. -// This should only be used on rare occasions where pushing the currently queued data is critical. -func (e *Encoder) Flush() error { - s := &e.state - if len(s.filling) > 0 { - err := e.nextBlock(false) - if err != nil { - return err - } - } - s.wg.Wait() - s.wWg.Wait() - if s.err != nil { - return s.err - } - return s.writeErr -} - -// Close will flush the final output and close the stream. -// The function will block until everything has been written. -// The Encoder can still be re-used after calling this. -func (e *Encoder) Close() error { - s := &e.state - if s.encoder == nil { - return nil - } - err := e.nextBlock(true) - if err != nil { - return err - } - if s.frameContentSize > 0 { - if s.nInput != s.frameContentSize { - return fmt.Errorf("frame content size %d given, but %d bytes was written", s.frameContentSize, s.nInput) - } - } - if e.state.fullFrameWritten { - return s.err - } - s.wg.Wait() - s.wWg.Wait() - - if s.err != nil { - return s.err - } - if s.writeErr != nil { - return s.writeErr - } - - // Write CRC - if e.o.crc && s.err == nil { - // heap alloc. - var tmp [4]byte - _, s.err = s.w.Write(s.encoder.AppendCRC(tmp[:0])) - s.nWritten += 4 - } - - // Add padding with content from crypto/rand.Reader - if s.err == nil && e.o.pad > 0 { - add := calcSkippableFrame(s.nWritten, int64(e.o.pad)) - frame, err := skippableFrame(s.filling[:0], add, rand.Reader) - if err != nil { - return err - } - _, s.err = s.w.Write(frame) - } - return s.err -} - -// EncodeAll will encode all input in src and append it to dst. -// This function can be called concurrently, but each call will only run on a single goroutine. -// If empty input is given, nothing is returned, unless WithZeroFrames is specified. -// Encoded blocks can be concatenated and the result will be the combined input stream. -// Data compressed with EncodeAll can be decoded with the Decoder, -// using either a stream or DecodeAll. -func (e *Encoder) EncodeAll(src, dst []byte) []byte { - if len(src) == 0 { - if e.o.fullZero { - // Add frame header. - fh := frameHeader{ - ContentSize: 0, - WindowSize: MinWindowSize, - SingleSegment: true, - // Adding a checksum would be a waste of space. - Checksum: false, - DictID: 0, - } - dst = fh.appendTo(dst) - - // Write raw block as last one only. - var blk blockHeader - blk.setSize(0) - blk.setType(blockTypeRaw) - blk.setLast(true) - dst = blk.appendTo(dst) - } - return dst - } - e.init.Do(e.initialize) - enc := <-e.encoders - defer func() { - // Release encoder reference to last block. - // If a non-single block is needed the encoder will reset again. - e.encoders <- enc - }() - // Use single segments when above minimum window and below window size. - single := len(src) <= e.o.windowSize && len(src) > MinWindowSize - if e.o.single != nil { - single = *e.o.single - } - fh := frameHeader{ - ContentSize: uint64(len(src)), - WindowSize: uint32(enc.WindowSize(int64(len(src)))), - SingleSegment: single, - Checksum: e.o.crc, - DictID: e.o.dict.ID(), - } - - // If less than 1MB, allocate a buffer up front. - if len(dst) == 0 && cap(dst) == 0 && len(src) < 1<<20 && !e.o.lowMem { - dst = make([]byte, 0, len(src)) - } - dst = fh.appendTo(dst) - - // If we can do everything in one block, prefer that. - if len(src) <= e.o.blockSize { - enc.Reset(e.o.dict, true) - // Slightly faster with no history and everything in one block. - if e.o.crc { - _, _ = enc.CRC().Write(src) - } - blk := enc.Block() - blk.last = true - if e.o.dict == nil { - enc.EncodeNoHist(blk, src) - } else { - enc.Encode(blk, src) - } - - // If we got the exact same number of literals as input, - // assume the literals cannot be compressed. - oldout := blk.output - // Output directly to dst - blk.output = dst - - err := blk.encode(src, e.o.noEntropy, !e.o.allLitEntropy) - if err != nil { - panic(err) - } - dst = blk.output - blk.output = oldout - } else { - enc.Reset(e.o.dict, false) - blk := enc.Block() - for len(src) > 0 { - todo := src - if len(todo) > e.o.blockSize { - todo = todo[:e.o.blockSize] - } - src = src[len(todo):] - if e.o.crc { - _, _ = enc.CRC().Write(todo) - } - blk.pushOffsets() - enc.Encode(blk, todo) - if len(src) == 0 { - blk.last = true - } - err := blk.encode(todo, e.o.noEntropy, !e.o.allLitEntropy) - if err != nil { - panic(err) - } - dst = append(dst, blk.output...) - blk.reset(nil) - } - } - if e.o.crc { - dst = enc.AppendCRC(dst) - } - // Add padding with content from crypto/rand.Reader - if e.o.pad > 0 { - add := calcSkippableFrame(int64(len(dst)), int64(e.o.pad)) - var err error - dst, err = skippableFrame(dst, add, rand.Reader) - if err != nil { - panic(err) - } - } - return dst -} - -// MaxEncodedSize returns the expected maximum -// size of an encoded block or stream. -func (e *Encoder) MaxEncodedSize(size int) int { - frameHeader := 4 + 2 // magic + frame header & window descriptor - if e.o.dict != nil { - frameHeader += 4 - } - // Frame content size: - if size < 256 { - frameHeader++ - } else if size < 65536+256 { - frameHeader += 2 - } else if size < math.MaxInt32 { - frameHeader += 4 - } else { - frameHeader += 8 - } - // Final crc - if e.o.crc { - frameHeader += 4 - } - - // Max overhead is 3 bytes/block. - // There cannot be 0 blocks. - blocks := (size + e.o.blockSize) / e.o.blockSize - - // Combine, add padding. - maxSz := frameHeader + 3*blocks + size - if e.o.pad > 1 { - maxSz += calcSkippableFrame(int64(maxSz), int64(e.o.pad)) - } - return maxSz -} diff --git a/vendor/github.com/klauspost/compress/zstd/encoder_options.go b/vendor/github.com/klauspost/compress/zstd/encoder_options.go deleted file mode 100644 index faaf81921..000000000 --- a/vendor/github.com/klauspost/compress/zstd/encoder_options.go +++ /dev/null @@ -1,339 +0,0 @@ -package zstd - -import ( - "errors" - "fmt" - "math" - "math/bits" - "runtime" - "strings" -) - -// EOption is an option for creating a encoder. -type EOption func(*encoderOptions) error - -// options retains accumulated state of multiple options. -type encoderOptions struct { - concurrent int - level EncoderLevel - single *bool - pad int - blockSize int - windowSize int - crc bool - fullZero bool - noEntropy bool - allLitEntropy bool - customWindow bool - customALEntropy bool - customBlockSize bool - lowMem bool - dict *dict -} - -func (o *encoderOptions) setDefault() { - *o = encoderOptions{ - concurrent: runtime.GOMAXPROCS(0), - crc: true, - single: nil, - blockSize: maxCompressedBlockSize, - windowSize: 8 << 20, - level: SpeedDefault, - allLitEntropy: false, - lowMem: false, - } -} - -// encoder returns an encoder with the selected options. -func (o encoderOptions) encoder() encoder { - switch o.level { - case SpeedFastest: - if o.dict != nil { - return &fastEncoderDict{fastEncoder: fastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}}} - } - return &fastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}} - - case SpeedDefault: - if o.dict != nil { - return &doubleFastEncoderDict{fastEncoderDict: fastEncoderDict{fastEncoder: fastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}}}} - } - return &doubleFastEncoder{fastEncoder: fastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}}} - case SpeedBetterCompression: - if o.dict != nil { - return &betterFastEncoderDict{betterFastEncoder: betterFastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}}} - } - return &betterFastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}} - case SpeedBestCompression: - return &bestFastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}} - } - panic("unknown compression level") -} - -// WithEncoderCRC will add CRC value to output. -// Output will be 4 bytes larger. -func WithEncoderCRC(b bool) EOption { - return func(o *encoderOptions) error { o.crc = b; return nil } -} - -// WithEncoderConcurrency will set the concurrency, -// meaning the maximum number of encoders to run concurrently. -// The value supplied must be at least 1. -// For streams, setting a value of 1 will disable async compression. -// By default this will be set to GOMAXPROCS. -func WithEncoderConcurrency(n int) EOption { - return func(o *encoderOptions) error { - if n <= 0 { - return fmt.Errorf("concurrency must be at least 1") - } - o.concurrent = n - return nil - } -} - -// WithWindowSize will set the maximum allowed back-reference distance. -// The value must be a power of two between MinWindowSize and MaxWindowSize. -// A larger value will enable better compression but allocate more memory and, -// for above-default values, take considerably longer. -// The default value is determined by the compression level. -func WithWindowSize(n int) EOption { - return func(o *encoderOptions) error { - switch { - case n < MinWindowSize: - return fmt.Errorf("window size must be at least %d", MinWindowSize) - case n > MaxWindowSize: - return fmt.Errorf("window size must be at most %d", MaxWindowSize) - case (n & (n - 1)) != 0: - return errors.New("window size must be a power of 2") - } - - o.windowSize = n - o.customWindow = true - if o.blockSize > o.windowSize { - o.blockSize = o.windowSize - o.customBlockSize = true - } - return nil - } -} - -// WithEncoderPadding will add padding to all output so the size will be a multiple of n. -// This can be used to obfuscate the exact output size or make blocks of a certain size. -// The contents will be a skippable frame, so it will be invisible by the decoder. -// n must be > 0 and <= 1GB, 1<<30 bytes. -// The padded area will be filled with data from crypto/rand.Reader. -// If `EncodeAll` is used with data already in the destination, the total size will be multiple of this. -func WithEncoderPadding(n int) EOption { - return func(o *encoderOptions) error { - if n <= 0 { - return fmt.Errorf("padding must be at least 1") - } - // No need to waste our time. - if n == 1 { - n = 0 - } - if n > 1<<30 { - return fmt.Errorf("padding must less than 1GB (1<<30 bytes) ") - } - o.pad = n - return nil - } -} - -// EncoderLevel predefines encoder compression levels. -// Only use the constants made available, since the actual mapping -// of these values are very likely to change and your compression could change -// unpredictably when upgrading the library. -type EncoderLevel int - -const ( - speedNotSet EncoderLevel = iota - - // SpeedFastest will choose the fastest reasonable compression. - // This is roughly equivalent to the fastest Zstandard mode. - SpeedFastest - - // SpeedDefault is the default "pretty fast" compression option. - // This is roughly equivalent to the default Zstandard mode (level 3). - SpeedDefault - - // SpeedBetterCompression will yield better compression than the default. - // Currently it is about zstd level 7-8 with ~ 2x-3x the default CPU usage. - // By using this, notice that CPU usage may go up in the future. - SpeedBetterCompression - - // SpeedBestCompression will choose the best available compression option. - // This will offer the best compression no matter the CPU cost. - SpeedBestCompression - - // speedLast should be kept as the last actual compression option. - // The is not for external usage, but is used to keep track of the valid options. - speedLast -) - -// EncoderLevelFromString will convert a string representation of an encoding level back -// to a compression level. The compare is not case sensitive. -// If the string wasn't recognized, (false, SpeedDefault) will be returned. -func EncoderLevelFromString(s string) (bool, EncoderLevel) { - for l := speedNotSet + 1; l < speedLast; l++ { - if strings.EqualFold(s, l.String()) { - return true, l - } - } - return false, SpeedDefault -} - -// EncoderLevelFromZstd will return an encoder level that closest matches the compression -// ratio of a specific zstd compression level. -// Many input values will provide the same compression level. -func EncoderLevelFromZstd(level int) EncoderLevel { - switch { - case level < 3: - return SpeedFastest - case level >= 3 && level < 6: - return SpeedDefault - case level >= 6 && level < 10: - return SpeedBetterCompression - default: - return SpeedBestCompression - } -} - -// String provides a string representation of the compression level. -func (e EncoderLevel) String() string { - switch e { - case SpeedFastest: - return "fastest" - case SpeedDefault: - return "default" - case SpeedBetterCompression: - return "better" - case SpeedBestCompression: - return "best" - default: - return "invalid" - } -} - -// WithEncoderLevel specifies a predefined compression level. -func WithEncoderLevel(l EncoderLevel) EOption { - return func(o *encoderOptions) error { - switch { - case l <= speedNotSet || l >= speedLast: - return fmt.Errorf("unknown encoder level") - } - o.level = l - if !o.customWindow { - switch o.level { - case SpeedFastest: - o.windowSize = 4 << 20 - if !o.customBlockSize { - o.blockSize = 1 << 16 - } - case SpeedDefault: - o.windowSize = 8 << 20 - case SpeedBetterCompression: - o.windowSize = 16 << 20 - case SpeedBestCompression: - o.windowSize = 32 << 20 - } - } - if !o.customALEntropy { - o.allLitEntropy = l > SpeedDefault - } - - return nil - } -} - -// WithZeroFrames will encode 0 length input as full frames. -// This can be needed for compatibility with zstandard usage, -// but is not needed for this package. -func WithZeroFrames(b bool) EOption { - return func(o *encoderOptions) error { - o.fullZero = b - return nil - } -} - -// WithAllLitEntropyCompression will apply entropy compression if no matches are found. -// Disabling this will skip incompressible data faster, but in cases with no matches but -// skewed character distribution compression is lost. -// Default value depends on the compression level selected. -func WithAllLitEntropyCompression(b bool) EOption { - return func(o *encoderOptions) error { - o.customALEntropy = true - o.allLitEntropy = b - return nil - } -} - -// WithNoEntropyCompression will always skip entropy compression of literals. -// This can be useful if content has matches, but unlikely to benefit from entropy -// compression. Usually the slight speed improvement is not worth enabling this. -func WithNoEntropyCompression(b bool) EOption { - return func(o *encoderOptions) error { - o.noEntropy = b - return nil - } -} - -// WithSingleSegment will set the "single segment" flag when EncodeAll is used. -// If this flag is set, data must be regenerated within a single continuous memory segment. -// In this case, Window_Descriptor byte is skipped, but Frame_Content_Size is necessarily present. -// As a consequence, the decoder must allocate a memory segment of size equal or larger than size of your content. -// In order to preserve the decoder from unreasonable memory requirements, -// a decoder is allowed to reject a compressed frame which requests a memory size beyond decoder's authorized range. -// For broader compatibility, decoders are recommended to support memory sizes of at least 8 MB. -// This is only a recommendation, each decoder is free to support higher or lower limits, depending on local limitations. -// If this is not specified, block encodes will automatically choose this based on the input size and the window size. -// This setting has no effect on streamed encodes. -func WithSingleSegment(b bool) EOption { - return func(o *encoderOptions) error { - o.single = &b - return nil - } -} - -// WithLowerEncoderMem will trade in some memory cases trade less memory usage for -// slower encoding speed. -// This will not change the window size which is the primary function for reducing -// memory usage. See WithWindowSize. -func WithLowerEncoderMem(b bool) EOption { - return func(o *encoderOptions) error { - o.lowMem = b - return nil - } -} - -// WithEncoderDict allows to register a dictionary that will be used for the encode. -// -// The slice dict must be in the [dictionary format] produced by -// "zstd --train" from the Zstandard reference implementation. -// -// The encoder *may* choose to use no dictionary instead for certain payloads. -// -// [dictionary format]: https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#dictionary-format -func WithEncoderDict(dict []byte) EOption { - return func(o *encoderOptions) error { - d, err := loadDict(dict) - if err != nil { - return err - } - o.dict = d - return nil - } -} - -// WithEncoderDictRaw registers a dictionary that may be used by the encoder. -// -// The slice content may contain arbitrary data. It will be used as an initial -// history. -func WithEncoderDictRaw(id uint32, content []byte) EOption { - return func(o *encoderOptions) error { - if bits.UintSize > 32 && uint(len(content)) > dictMaxLength { - return fmt.Errorf("dictionary of size %d > 2GiB too large", len(content)) - } - o.dict = &dict{id: id, content: content, offsets: [3]int{1, 4, 8}} - return nil - } -} diff --git a/vendor/github.com/klauspost/compress/zstd/framedec.go b/vendor/github.com/klauspost/compress/zstd/framedec.go deleted file mode 100644 index 53e160f7e..000000000 --- a/vendor/github.com/klauspost/compress/zstd/framedec.go +++ /dev/null @@ -1,413 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "encoding/binary" - "encoding/hex" - "errors" - "io" - - "github.com/klauspost/compress/zstd/internal/xxhash" -) - -type frameDec struct { - o decoderOptions - crc *xxhash.Digest - - WindowSize uint64 - - // Frame history passed between blocks - history history - - rawInput byteBuffer - - // Byte buffer that can be reused for small input blocks. - bBuf byteBuf - - FrameContentSize uint64 - - DictionaryID uint32 - HasCheckSum bool - SingleSegment bool -} - -const ( - // MinWindowSize is the minimum Window Size, which is 1 KB. - MinWindowSize = 1 << 10 - - // MaxWindowSize is the maximum encoder window size - // and the default decoder maximum window size. - MaxWindowSize = 1 << 29 -) - -const ( - frameMagic = "\x28\xb5\x2f\xfd" - skippableFrameMagic = "\x2a\x4d\x18" -) - -func newFrameDec(o decoderOptions) *frameDec { - if o.maxWindowSize > o.maxDecodedSize { - o.maxWindowSize = o.maxDecodedSize - } - d := frameDec{ - o: o, - } - return &d -} - -// reset will read the frame header and prepare for block decoding. -// If nothing can be read from the input, io.EOF will be returned. -// Any other error indicated that the stream contained data, but -// there was a problem. -func (d *frameDec) reset(br byteBuffer) error { - d.HasCheckSum = false - d.WindowSize = 0 - var signature [4]byte - for { - var err error - // Check if we can read more... - b, err := br.readSmall(1) - switch err { - case io.EOF, io.ErrUnexpectedEOF: - return io.EOF - case nil: - signature[0] = b[0] - default: - return err - } - // Read the rest, don't allow io.ErrUnexpectedEOF - b, err = br.readSmall(3) - switch err { - case io.EOF: - return io.EOF - case nil: - copy(signature[1:], b) - default: - return err - } - - if string(signature[1:4]) != skippableFrameMagic || signature[0]&0xf0 != 0x50 { - if debugDecoder { - println("Not skippable", hex.EncodeToString(signature[:]), hex.EncodeToString([]byte(skippableFrameMagic))) - } - // Break if not skippable frame. - break - } - // Read size to skip - b, err = br.readSmall(4) - if err != nil { - if debugDecoder { - println("Reading Frame Size", err) - } - return err - } - n := uint32(b[0]) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24) - println("Skipping frame with", n, "bytes.") - err = br.skipN(int64(n)) - if err != nil { - if debugDecoder { - println("Reading discarded frame", err) - } - return err - } - } - if string(signature[:]) != frameMagic { - if debugDecoder { - println("Got magic numbers: ", signature, "want:", []byte(frameMagic)) - } - return ErrMagicMismatch - } - - // Read Frame_Header_Descriptor - fhd, err := br.readByte() - if err != nil { - if debugDecoder { - println("Reading Frame_Header_Descriptor", err) - } - return err - } - d.SingleSegment = fhd&(1<<5) != 0 - - if fhd&(1<<3) != 0 { - return errors.New("reserved bit set on frame header") - } - - // Read Window_Descriptor - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#window_descriptor - d.WindowSize = 0 - if !d.SingleSegment { - wd, err := br.readByte() - if err != nil { - if debugDecoder { - println("Reading Window_Descriptor", err) - } - return err - } - printf("raw: %x, mantissa: %d, exponent: %d\n", wd, wd&7, wd>>3) - windowLog := 10 + (wd >> 3) - windowBase := uint64(1) << windowLog - windowAdd := (windowBase / 8) * uint64(wd&0x7) - d.WindowSize = windowBase + windowAdd - } - - // Read Dictionary_ID - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#dictionary_id - d.DictionaryID = 0 - if size := fhd & 3; size != 0 { - if size == 3 { - size = 4 - } - - b, err := br.readSmall(int(size)) - if err != nil { - println("Reading Dictionary_ID", err) - return err - } - var id uint32 - switch len(b) { - case 1: - id = uint32(b[0]) - case 2: - id = uint32(b[0]) | (uint32(b[1]) << 8) - case 4: - id = uint32(b[0]) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24) - } - if debugDecoder { - println("Dict size", size, "ID:", id) - } - d.DictionaryID = id - } - - // Read Frame_Content_Size - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#frame_content_size - var fcsSize int - v := fhd >> 6 - switch v { - case 0: - if d.SingleSegment { - fcsSize = 1 - } - default: - fcsSize = 1 << v - } - d.FrameContentSize = fcsUnknown - if fcsSize > 0 { - b, err := br.readSmall(fcsSize) - if err != nil { - println("Reading Frame content", err) - return err - } - switch len(b) { - case 1: - d.FrameContentSize = uint64(b[0]) - case 2: - // When FCS_Field_Size is 2, the offset of 256 is added. - d.FrameContentSize = uint64(b[0]) | (uint64(b[1]) << 8) + 256 - case 4: - d.FrameContentSize = uint64(b[0]) | (uint64(b[1]) << 8) | (uint64(b[2]) << 16) | (uint64(b[3]) << 24) - case 8: - d1 := uint32(b[0]) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24) - d2 := uint32(b[4]) | (uint32(b[5]) << 8) | (uint32(b[6]) << 16) | (uint32(b[7]) << 24) - d.FrameContentSize = uint64(d1) | (uint64(d2) << 32) - } - if debugDecoder { - println("Read FCS:", d.FrameContentSize) - } - } - - // Move this to shared. - d.HasCheckSum = fhd&(1<<2) != 0 - if d.HasCheckSum { - if d.crc == nil { - d.crc = xxhash.New() - } - d.crc.Reset() - } - - if d.WindowSize > d.o.maxWindowSize { - if debugDecoder { - printf("window size %d > max %d\n", d.WindowSize, d.o.maxWindowSize) - } - return ErrWindowSizeExceeded - } - - if d.WindowSize == 0 && d.SingleSegment { - // We may not need window in this case. - d.WindowSize = d.FrameContentSize - if d.WindowSize < MinWindowSize { - d.WindowSize = MinWindowSize - } - if d.WindowSize > d.o.maxDecodedSize { - if debugDecoder { - printf("window size %d > max %d\n", d.WindowSize, d.o.maxWindowSize) - } - return ErrDecoderSizeExceeded - } - } - - // The minimum Window_Size is 1 KB. - if d.WindowSize < MinWindowSize { - if debugDecoder { - println("got window size: ", d.WindowSize) - } - return ErrWindowSizeTooSmall - } - d.history.windowSize = int(d.WindowSize) - if !d.o.lowMem || d.history.windowSize < maxBlockSize { - // Alloc 2x window size if not low-mem, or window size below 2MB. - d.history.allocFrameBuffer = d.history.windowSize * 2 - } else { - if d.o.lowMem { - // Alloc with 1MB extra. - d.history.allocFrameBuffer = d.history.windowSize + maxBlockSize/2 - } else { - // Alloc with 2MB extra. - d.history.allocFrameBuffer = d.history.windowSize + maxBlockSize - } - } - - if debugDecoder { - println("Frame: Dict:", d.DictionaryID, "FrameContentSize:", d.FrameContentSize, "singleseg:", d.SingleSegment, "window:", d.WindowSize, "crc:", d.HasCheckSum) - } - - // history contains input - maybe we do something - d.rawInput = br - return nil -} - -// next will start decoding the next block from stream. -func (d *frameDec) next(block *blockDec) error { - if debugDecoder { - println("decoding new block") - } - err := block.reset(d.rawInput, d.WindowSize) - if err != nil { - println("block error:", err) - // Signal the frame decoder we have a problem. - block.sendErr(err) - return err - } - return nil -} - -// checkCRC will check the checksum, assuming the frame has one. -// Will return ErrCRCMismatch if crc check failed, otherwise nil. -func (d *frameDec) checkCRC() error { - // We can overwrite upper tmp now - buf, err := d.rawInput.readSmall(4) - if err != nil { - println("CRC missing?", err) - return err - } - - want := binary.LittleEndian.Uint32(buf[:4]) - got := uint32(d.crc.Sum64()) - - if got != want { - if debugDecoder { - printf("CRC check failed: got %08x, want %08x\n", got, want) - } - return ErrCRCMismatch - } - if debugDecoder { - printf("CRC ok %08x\n", got) - } - return nil -} - -// consumeCRC skips over the checksum, assuming the frame has one. -func (d *frameDec) consumeCRC() error { - _, err := d.rawInput.readSmall(4) - if err != nil { - println("CRC missing?", err) - } - return err -} - -// runDecoder will run the decoder for the remainder of the frame. -func (d *frameDec) runDecoder(dst []byte, dec *blockDec) ([]byte, error) { - saved := d.history.b - - // We use the history for output to avoid copying it. - d.history.b = dst - d.history.ignoreBuffer = len(dst) - // Store input length, so we only check new data. - crcStart := len(dst) - d.history.decoders.maxSyncLen = 0 - if d.o.limitToCap { - d.history.decoders.maxSyncLen = uint64(cap(dst) - len(dst)) - } - if d.FrameContentSize != fcsUnknown { - if !d.o.limitToCap || d.FrameContentSize+uint64(len(dst)) < d.history.decoders.maxSyncLen { - d.history.decoders.maxSyncLen = d.FrameContentSize + uint64(len(dst)) - } - if d.history.decoders.maxSyncLen > d.o.maxDecodedSize { - if debugDecoder { - println("maxSyncLen:", d.history.decoders.maxSyncLen, "> maxDecodedSize:", d.o.maxDecodedSize) - } - return dst, ErrDecoderSizeExceeded - } - if debugDecoder { - println("maxSyncLen:", d.history.decoders.maxSyncLen) - } - if !d.o.limitToCap && uint64(cap(dst)) < d.history.decoders.maxSyncLen { - // Alloc for output - dst2 := make([]byte, len(dst), d.history.decoders.maxSyncLen+compressedBlockOverAlloc) - copy(dst2, dst) - dst = dst2 - } - } - var err error - for { - err = dec.reset(d.rawInput, d.WindowSize) - if err != nil { - break - } - if debugDecoder { - println("next block:", dec) - } - err = dec.decodeBuf(&d.history) - if err != nil { - break - } - if uint64(len(d.history.b)-crcStart) > d.o.maxDecodedSize { - println("runDecoder: maxDecodedSize exceeded", uint64(len(d.history.b)-crcStart), ">", d.o.maxDecodedSize) - err = ErrDecoderSizeExceeded - break - } - if d.o.limitToCap && len(d.history.b) > cap(dst) { - println("runDecoder: cap exceeded", uint64(len(d.history.b)), ">", cap(dst)) - err = ErrDecoderSizeExceeded - break - } - if uint64(len(d.history.b)-crcStart) > d.FrameContentSize { - println("runDecoder: FrameContentSize exceeded", uint64(len(d.history.b)-crcStart), ">", d.FrameContentSize) - err = ErrFrameSizeExceeded - break - } - if dec.Last { - break - } - if debugDecoder { - println("runDecoder: FrameContentSize", uint64(len(d.history.b)-crcStart), "<=", d.FrameContentSize) - } - } - dst = d.history.b - if err == nil { - if d.FrameContentSize != fcsUnknown && uint64(len(d.history.b)-crcStart) != d.FrameContentSize { - err = ErrFrameSizeMismatch - } else if d.HasCheckSum { - if d.o.ignoreChecksum { - err = d.consumeCRC() - } else { - d.crc.Write(dst[crcStart:]) - err = d.checkCRC() - } - } - } - d.history.b = saved - return dst, err -} diff --git a/vendor/github.com/klauspost/compress/zstd/frameenc.go b/vendor/github.com/klauspost/compress/zstd/frameenc.go deleted file mode 100644 index 2f5d5ed45..000000000 --- a/vendor/github.com/klauspost/compress/zstd/frameenc.go +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "encoding/binary" - "fmt" - "io" - "math" - "math/bits" -) - -type frameHeader struct { - ContentSize uint64 - WindowSize uint32 - SingleSegment bool - Checksum bool - DictID uint32 -} - -const maxHeaderSize = 14 - -func (f frameHeader) appendTo(dst []byte) []byte { - dst = append(dst, frameMagic...) - var fhd uint8 - if f.Checksum { - fhd |= 1 << 2 - } - if f.SingleSegment { - fhd |= 1 << 5 - } - - var dictIDContent []byte - if f.DictID > 0 { - var tmp [4]byte - if f.DictID < 256 { - fhd |= 1 - tmp[0] = uint8(f.DictID) - dictIDContent = tmp[:1] - } else if f.DictID < 1<<16 { - fhd |= 2 - binary.LittleEndian.PutUint16(tmp[:2], uint16(f.DictID)) - dictIDContent = tmp[:2] - } else { - fhd |= 3 - binary.LittleEndian.PutUint32(tmp[:4], f.DictID) - dictIDContent = tmp[:4] - } - } - var fcs uint8 - if f.ContentSize >= 256 { - fcs++ - } - if f.ContentSize >= 65536+256 { - fcs++ - } - if f.ContentSize >= 0xffffffff { - fcs++ - } - - fhd |= fcs << 6 - - dst = append(dst, fhd) - if !f.SingleSegment { - const winLogMin = 10 - windowLog := (bits.Len32(f.WindowSize-1) - winLogMin) << 3 - dst = append(dst, uint8(windowLog)) - } - if f.DictID > 0 { - dst = append(dst, dictIDContent...) - } - switch fcs { - case 0: - if f.SingleSegment { - dst = append(dst, uint8(f.ContentSize)) - } - // Unless SingleSegment is set, framessizes < 256 are nto stored. - case 1: - f.ContentSize -= 256 - dst = append(dst, uint8(f.ContentSize), uint8(f.ContentSize>>8)) - case 2: - dst = append(dst, uint8(f.ContentSize), uint8(f.ContentSize>>8), uint8(f.ContentSize>>16), uint8(f.ContentSize>>24)) - case 3: - dst = append(dst, uint8(f.ContentSize), uint8(f.ContentSize>>8), uint8(f.ContentSize>>16), uint8(f.ContentSize>>24), - uint8(f.ContentSize>>32), uint8(f.ContentSize>>40), uint8(f.ContentSize>>48), uint8(f.ContentSize>>56)) - default: - panic("invalid fcs") - } - return dst -} - -const skippableFrameHeader = 4 + 4 - -// calcSkippableFrame will return a total size to be added for written -// to be divisible by multiple. -// The value will always be > skippableFrameHeader. -// The function will panic if written < 0 or wantMultiple <= 0. -func calcSkippableFrame(written, wantMultiple int64) int { - if wantMultiple <= 0 { - panic("wantMultiple <= 0") - } - if written < 0 { - panic("written < 0") - } - leftOver := written % wantMultiple - if leftOver == 0 { - return 0 - } - toAdd := wantMultiple - leftOver - for toAdd < skippableFrameHeader { - toAdd += wantMultiple - } - return int(toAdd) -} - -// skippableFrame will add a skippable frame with a total size of bytes. -// total should be >= skippableFrameHeader and < math.MaxUint32. -func skippableFrame(dst []byte, total int, r io.Reader) ([]byte, error) { - if total == 0 { - return dst, nil - } - if total < skippableFrameHeader { - return dst, fmt.Errorf("requested skippable frame (%d) < 8", total) - } - if int64(total) > math.MaxUint32 { - return dst, fmt.Errorf("requested skippable frame (%d) > max uint32", total) - } - dst = append(dst, 0x50, 0x2a, 0x4d, 0x18) - f := uint32(total - skippableFrameHeader) - dst = append(dst, uint8(f), uint8(f>>8), uint8(f>>16), uint8(f>>24)) - start := len(dst) - dst = append(dst, make([]byte, f)...) - _, err := io.ReadFull(r, dst[start:]) - return dst, err -} diff --git a/vendor/github.com/klauspost/compress/zstd/fse_decoder.go b/vendor/github.com/klauspost/compress/zstd/fse_decoder.go deleted file mode 100644 index 2f8860a72..000000000 --- a/vendor/github.com/klauspost/compress/zstd/fse_decoder.go +++ /dev/null @@ -1,307 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "encoding/binary" - "errors" - "fmt" - "io" -) - -const ( - tablelogAbsoluteMax = 9 -) - -const ( - /*!MEMORY_USAGE : - * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) - * Increasing memory usage improves compression ratio - * Reduced memory usage can improve speed, due to cache effect - * Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */ - maxMemoryUsage = tablelogAbsoluteMax + 2 - - maxTableLog = maxMemoryUsage - 2 - maxTablesize = 1 << maxTableLog - maxTableMask = (1 << maxTableLog) - 1 - minTablelog = 5 - maxSymbolValue = 255 -) - -// fseDecoder provides temporary storage for compression and decompression. -type fseDecoder struct { - dt [maxTablesize]decSymbol // Decompression table. - symbolLen uint16 // Length of active part of the symbol table. - actualTableLog uint8 // Selected tablelog. - maxBits uint8 // Maximum number of additional bits - - // used for table creation to avoid allocations. - stateTable [256]uint16 - norm [maxSymbolValue + 1]int16 - preDefined bool -} - -// tableStep returns the next table index. -func tableStep(tableSize uint32) uint32 { - return (tableSize >> 1) + (tableSize >> 3) + 3 -} - -// readNCount will read the symbol distribution so decoding tables can be constructed. -func (s *fseDecoder) readNCount(b *byteReader, maxSymbol uint16) error { - var ( - charnum uint16 - previous0 bool - ) - if b.remain() < 4 { - return errors.New("input too small") - } - bitStream := b.Uint32NC() - nbBits := uint((bitStream & 0xF) + minTablelog) // extract tableLog - if nbBits > tablelogAbsoluteMax { - println("Invalid tablelog:", nbBits) - return errors.New("tableLog too large") - } - bitStream >>= 4 - bitCount := uint(4) - - s.actualTableLog = uint8(nbBits) - remaining := int32((1 << nbBits) + 1) - threshold := int32(1 << nbBits) - gotTotal := int32(0) - nbBits++ - - for remaining > 1 && charnum <= maxSymbol { - if previous0 { - //println("prev0") - n0 := charnum - for (bitStream & 0xFFFF) == 0xFFFF { - //println("24 x 0") - n0 += 24 - if r := b.remain(); r > 5 { - b.advance(2) - // The check above should make sure we can read 32 bits - bitStream = b.Uint32NC() >> bitCount - } else { - // end of bit stream - bitStream >>= 16 - bitCount += 16 - } - } - //printf("bitstream: %d, 0b%b", bitStream&3, bitStream) - for (bitStream & 3) == 3 { - n0 += 3 - bitStream >>= 2 - bitCount += 2 - } - n0 += uint16(bitStream & 3) - bitCount += 2 - - if n0 > maxSymbolValue { - return errors.New("maxSymbolValue too small") - } - //println("inserting ", n0-charnum, "zeroes from idx", charnum, "ending before", n0) - for charnum < n0 { - s.norm[uint8(charnum)] = 0 - charnum++ - } - - if r := b.remain(); r >= 7 || r-int(bitCount>>3) >= 4 { - b.advance(bitCount >> 3) - bitCount &= 7 - // The check above should make sure we can read 32 bits - bitStream = b.Uint32NC() >> bitCount - } else { - bitStream >>= 2 - } - } - - max := (2*threshold - 1) - remaining - var count int32 - - if int32(bitStream)&(threshold-1) < max { - count = int32(bitStream) & (threshold - 1) - if debugAsserts && nbBits < 1 { - panic("nbBits underflow") - } - bitCount += nbBits - 1 - } else { - count = int32(bitStream) & (2*threshold - 1) - if count >= threshold { - count -= max - } - bitCount += nbBits - } - - // extra accuracy - count-- - if count < 0 { - // -1 means +1 - remaining += count - gotTotal -= count - } else { - remaining -= count - gotTotal += count - } - s.norm[charnum&0xff] = int16(count) - charnum++ - previous0 = count == 0 - for remaining < threshold { - nbBits-- - threshold >>= 1 - } - - if r := b.remain(); r >= 7 || r-int(bitCount>>3) >= 4 { - b.advance(bitCount >> 3) - bitCount &= 7 - // The check above should make sure we can read 32 bits - bitStream = b.Uint32NC() >> (bitCount & 31) - } else { - bitCount -= (uint)(8 * (len(b.b) - 4 - b.off)) - b.off = len(b.b) - 4 - bitStream = b.Uint32() >> (bitCount & 31) - } - } - s.symbolLen = charnum - if s.symbolLen <= 1 { - return fmt.Errorf("symbolLen (%d) too small", s.symbolLen) - } - if s.symbolLen > maxSymbolValue+1 { - return fmt.Errorf("symbolLen (%d) too big", s.symbolLen) - } - if remaining != 1 { - return fmt.Errorf("corruption detected (remaining %d != 1)", remaining) - } - if bitCount > 32 { - return fmt.Errorf("corruption detected (bitCount %d > 32)", bitCount) - } - if gotTotal != 1<> 3) - return s.buildDtable() -} - -func (s *fseDecoder) mustReadFrom(r io.Reader) { - fatalErr := func(err error) { - if err != nil { - panic(err) - } - } - // dt [maxTablesize]decSymbol // Decompression table. - // symbolLen uint16 // Length of active part of the symbol table. - // actualTableLog uint8 // Selected tablelog. - // maxBits uint8 // Maximum number of additional bits - // // used for table creation to avoid allocations. - // stateTable [256]uint16 - // norm [maxSymbolValue + 1]int16 - // preDefined bool - fatalErr(binary.Read(r, binary.LittleEndian, &s.dt)) - fatalErr(binary.Read(r, binary.LittleEndian, &s.symbolLen)) - fatalErr(binary.Read(r, binary.LittleEndian, &s.actualTableLog)) - fatalErr(binary.Read(r, binary.LittleEndian, &s.maxBits)) - fatalErr(binary.Read(r, binary.LittleEndian, &s.stateTable)) - fatalErr(binary.Read(r, binary.LittleEndian, &s.norm)) - fatalErr(binary.Read(r, binary.LittleEndian, &s.preDefined)) -} - -// decSymbol contains information about a state entry, -// Including the state offset base, the output symbol and -// the number of bits to read for the low part of the destination state. -// Using a composite uint64 is faster than a struct with separate members. -type decSymbol uint64 - -func newDecSymbol(nbits, addBits uint8, newState uint16, baseline uint32) decSymbol { - return decSymbol(nbits) | (decSymbol(addBits) << 8) | (decSymbol(newState) << 16) | (decSymbol(baseline) << 32) -} - -func (d decSymbol) nbBits() uint8 { - return uint8(d) -} - -func (d decSymbol) addBits() uint8 { - return uint8(d >> 8) -} - -func (d decSymbol) newState() uint16 { - return uint16(d >> 16) -} - -func (d decSymbol) baselineInt() int { - return int(d >> 32) -} - -func (d *decSymbol) setNBits(nBits uint8) { - const mask = 0xffffffffffffff00 - *d = (*d & mask) | decSymbol(nBits) -} - -func (d *decSymbol) setAddBits(addBits uint8) { - const mask = 0xffffffffffff00ff - *d = (*d & mask) | (decSymbol(addBits) << 8) -} - -func (d *decSymbol) setNewState(state uint16) { - const mask = 0xffffffff0000ffff - *d = (*d & mask) | decSymbol(state)<<16 -} - -func (d *decSymbol) setExt(addBits uint8, baseline uint32) { - const mask = 0xffff00ff - *d = (*d & mask) | (decSymbol(addBits) << 8) | (decSymbol(baseline) << 32) -} - -// decSymbolValue returns the transformed decSymbol for the given symbol. -func decSymbolValue(symb uint8, t []baseOffset) (decSymbol, error) { - if int(symb) >= len(t) { - return 0, fmt.Errorf("rle symbol %d >= max %d", symb, len(t)) - } - lu := t[symb] - return newDecSymbol(0, lu.addBits, 0, lu.baseLine), nil -} - -// setRLE will set the decoder til RLE mode. -func (s *fseDecoder) setRLE(symbol decSymbol) { - s.actualTableLog = 0 - s.maxBits = symbol.addBits() - s.dt[0] = symbol -} - -// transform will transform the decoder table into a table usable for -// decoding without having to apply the transformation while decoding. -// The state will contain the base value and the number of bits to read. -func (s *fseDecoder) transform(t []baseOffset) error { - tableSize := uint16(1 << s.actualTableLog) - s.maxBits = 0 - for i, v := range s.dt[:tableSize] { - add := v.addBits() - if int(add) >= len(t) { - return fmt.Errorf("invalid decoding table entry %d, symbol %d >= max (%d)", i, v.addBits(), len(t)) - } - lu := t[add] - if lu.addBits > s.maxBits { - s.maxBits = lu.addBits - } - v.setExt(lu.addBits, lu.baseLine) - s.dt[i] = v - } - return nil -} - -type fseState struct { - dt []decSymbol - state decSymbol -} - -// Initialize and decodeAsync first state and symbol. -func (s *fseState) init(br *bitReader, tableLog uint8, dt []decSymbol) { - s.dt = dt - br.fill() - s.state = dt[br.getBits(tableLog)] -} - -// final returns the current state symbol without decoding the next. -func (s decSymbol) final() (int, uint8) { - return s.baselineInt(), s.addBits() -} diff --git a/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.go b/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.go deleted file mode 100644 index d04a829b0..000000000 --- a/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.go +++ /dev/null @@ -1,65 +0,0 @@ -//go:build amd64 && !appengine && !noasm && gc -// +build amd64,!appengine,!noasm,gc - -package zstd - -import ( - "fmt" -) - -type buildDtableAsmContext struct { - // inputs - stateTable *uint16 - norm *int16 - dt *uint64 - - // outputs --- set by the procedure in the case of error; - // for interpretation please see the error handling part below - errParam1 uint64 - errParam2 uint64 -} - -// buildDtable_asm is an x86 assembly implementation of fseDecoder.buildDtable. -// Function returns non-zero exit code on error. -// -//go:noescape -func buildDtable_asm(s *fseDecoder, ctx *buildDtableAsmContext) int - -// please keep in sync with _generate/gen_fse.go -const ( - errorCorruptedNormalizedCounter = 1 - errorNewStateTooBig = 2 - errorNewStateNoBits = 3 -) - -// buildDtable will build the decoding table. -func (s *fseDecoder) buildDtable() error { - ctx := buildDtableAsmContext{ - stateTable: &s.stateTable[0], - norm: &s.norm[0], - dt: (*uint64)(&s.dt[0]), - } - code := buildDtable_asm(s, &ctx) - - if code != 0 { - switch code { - case errorCorruptedNormalizedCounter: - position := ctx.errParam1 - return fmt.Errorf("corrupted input (position=%d, expected 0)", position) - - case errorNewStateTooBig: - newState := decSymbol(ctx.errParam1) - size := ctx.errParam2 - return fmt.Errorf("newState (%d) outside table size (%d)", newState, size) - - case errorNewStateNoBits: - newState := decSymbol(ctx.errParam1) - oldState := decSymbol(ctx.errParam2) - return fmt.Errorf("newState (%d) == oldState (%d) and no bits", newState, oldState) - - default: - return fmt.Errorf("buildDtable_asm returned unhandled nonzero code = %d", code) - } - } - return nil -} diff --git a/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.s b/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.s deleted file mode 100644 index bcde39869..000000000 --- a/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.s +++ /dev/null @@ -1,126 +0,0 @@ -// Code generated by command: go run gen_fse.go -out ../fse_decoder_amd64.s -pkg=zstd. DO NOT EDIT. - -//go:build !appengine && !noasm && gc && !noasm - -// func buildDtable_asm(s *fseDecoder, ctx *buildDtableAsmContext) int -TEXT ·buildDtable_asm(SB), $0-24 - MOVQ ctx+8(FP), CX - MOVQ s+0(FP), DI - - // Load values - MOVBQZX 4098(DI), DX - XORQ AX, AX - BTSQ DX, AX - MOVQ (CX), BX - MOVQ 16(CX), SI - LEAQ -1(AX), R8 - MOVQ 8(CX), CX - MOVWQZX 4096(DI), DI - - // End load values - // Init, lay down lowprob symbols - XORQ R9, R9 - JMP init_main_loop_condition - -init_main_loop: - MOVWQSX (CX)(R9*2), R10 - CMPW R10, $-1 - JNE do_not_update_high_threshold - MOVB R9, 1(SI)(R8*8) - DECQ R8 - MOVQ $0x0000000000000001, R10 - -do_not_update_high_threshold: - MOVW R10, (BX)(R9*2) - INCQ R9 - -init_main_loop_condition: - CMPQ R9, DI - JL init_main_loop - - // Spread symbols - // Calculate table step - MOVQ AX, R9 - SHRQ $0x01, R9 - MOVQ AX, R10 - SHRQ $0x03, R10 - LEAQ 3(R9)(R10*1), R9 - - // Fill add bits values - LEAQ -1(AX), R10 - XORQ R11, R11 - XORQ R12, R12 - JMP spread_main_loop_condition - -spread_main_loop: - XORQ R13, R13 - MOVWQSX (CX)(R12*2), R14 - JMP spread_inner_loop_condition - -spread_inner_loop: - MOVB R12, 1(SI)(R11*8) - -adjust_position: - ADDQ R9, R11 - ANDQ R10, R11 - CMPQ R11, R8 - JG adjust_position - INCQ R13 - -spread_inner_loop_condition: - CMPQ R13, R14 - JL spread_inner_loop - INCQ R12 - -spread_main_loop_condition: - CMPQ R12, DI - JL spread_main_loop - TESTQ R11, R11 - JZ spread_check_ok - MOVQ ctx+8(FP), AX - MOVQ R11, 24(AX) - MOVQ $+1, ret+16(FP) - RET - -spread_check_ok: - // Build Decoding table - XORQ DI, DI - -build_table_main_table: - MOVBQZX 1(SI)(DI*8), CX - MOVWQZX (BX)(CX*2), R8 - LEAQ 1(R8), R9 - MOVW R9, (BX)(CX*2) - MOVQ R8, R9 - BSRQ R9, R9 - MOVQ DX, CX - SUBQ R9, CX - SHLQ CL, R8 - SUBQ AX, R8 - MOVB CL, (SI)(DI*8) - MOVW R8, 2(SI)(DI*8) - CMPQ R8, AX - JLE build_table_check1_ok - MOVQ ctx+8(FP), CX - MOVQ R8, 24(CX) - MOVQ AX, 32(CX) - MOVQ $+2, ret+16(FP) - RET - -build_table_check1_ok: - TESTB CL, CL - JNZ build_table_check2_ok - CMPW R8, DI - JNE build_table_check2_ok - MOVQ ctx+8(FP), AX - MOVQ R8, 24(AX) - MOVQ DI, 32(AX) - MOVQ $+3, ret+16(FP) - RET - -build_table_check2_ok: - INCQ DI - CMPQ DI, AX - JL build_table_main_table - MOVQ $+0, ret+16(FP) - RET diff --git a/vendor/github.com/klauspost/compress/zstd/fse_decoder_generic.go b/vendor/github.com/klauspost/compress/zstd/fse_decoder_generic.go deleted file mode 100644 index 332e51fe4..000000000 --- a/vendor/github.com/klauspost/compress/zstd/fse_decoder_generic.go +++ /dev/null @@ -1,72 +0,0 @@ -//go:build !amd64 || appengine || !gc || noasm -// +build !amd64 appengine !gc noasm - -package zstd - -import ( - "errors" - "fmt" -) - -// buildDtable will build the decoding table. -func (s *fseDecoder) buildDtable() error { - tableSize := uint32(1 << s.actualTableLog) - highThreshold := tableSize - 1 - symbolNext := s.stateTable[:256] - - // Init, lay down lowprob symbols - { - for i, v := range s.norm[:s.symbolLen] { - if v == -1 { - s.dt[highThreshold].setAddBits(uint8(i)) - highThreshold-- - symbolNext[i] = 1 - } else { - symbolNext[i] = uint16(v) - } - } - } - - // Spread symbols - { - tableMask := tableSize - 1 - step := tableStep(tableSize) - position := uint32(0) - for ss, v := range s.norm[:s.symbolLen] { - for i := 0; i < int(v); i++ { - s.dt[position].setAddBits(uint8(ss)) - position = (position + step) & tableMask - for position > highThreshold { - // lowprob area - position = (position + step) & tableMask - } - } - } - if position != 0 { - // position must reach all cells once, otherwise normalizedCounter is incorrect - return errors.New("corrupted input (position != 0)") - } - } - - // Build Decoding table - { - tableSize := uint16(1 << s.actualTableLog) - for u, v := range s.dt[:tableSize] { - symbol := v.addBits() - nextState := symbolNext[symbol] - symbolNext[symbol] = nextState + 1 - nBits := s.actualTableLog - byte(highBits(uint32(nextState))) - s.dt[u&maxTableMask].setNBits(nBits) - newState := (nextState << nBits) - tableSize - if newState > tableSize { - return fmt.Errorf("newState (%d) outside table size (%d)", newState, tableSize) - } - if newState == uint16(u) && nBits == 0 { - // Seems weird that this is possible with nbits > 0. - return fmt.Errorf("newState (%d) == oldState (%d) and no bits", newState, u) - } - s.dt[u&maxTableMask].setNewState(newState) - } - } - return nil -} diff --git a/vendor/github.com/klauspost/compress/zstd/fse_encoder.go b/vendor/github.com/klauspost/compress/zstd/fse_encoder.go deleted file mode 100644 index ab26326a8..000000000 --- a/vendor/github.com/klauspost/compress/zstd/fse_encoder.go +++ /dev/null @@ -1,701 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "errors" - "fmt" - "math" -) - -const ( - // For encoding we only support up to - maxEncTableLog = 8 - maxEncTablesize = 1 << maxTableLog - maxEncTableMask = (1 << maxTableLog) - 1 - minEncTablelog = 5 - maxEncSymbolValue = maxMatchLengthSymbol -) - -// Scratch provides temporary storage for compression and decompression. -type fseEncoder struct { - symbolLen uint16 // Length of active part of the symbol table. - actualTableLog uint8 // Selected tablelog. - ct cTable // Compression tables. - maxCount int // count of the most probable symbol - zeroBits bool // no bits has prob > 50%. - clearCount bool // clear count - useRLE bool // This encoder is for RLE - preDefined bool // This encoder is predefined. - reUsed bool // Set to know when the encoder has been reused. - rleVal uint8 // RLE Symbol - maxBits uint8 // Maximum output bits after transform. - - // TODO: Technically zstd should be fine with 64 bytes. - count [256]uint32 - norm [256]int16 -} - -// cTable contains tables used for compression. -type cTable struct { - tableSymbol []byte - stateTable []uint16 - symbolTT []symbolTransform -} - -// symbolTransform contains the state transform for a symbol. -type symbolTransform struct { - deltaNbBits uint32 - deltaFindState int16 - outBits uint8 -} - -// String prints values as a human readable string. -func (s symbolTransform) String() string { - return fmt.Sprintf("{deltabits: %08x, findstate:%d outbits:%d}", s.deltaNbBits, s.deltaFindState, s.outBits) -} - -// Histogram allows to populate the histogram and skip that step in the compression, -// It otherwise allows to inspect the histogram when compression is done. -// To indicate that you have populated the histogram call HistogramFinished -// with the value of the highest populated symbol, as well as the number of entries -// in the most populated entry. These are accepted at face value. -func (s *fseEncoder) Histogram() *[256]uint32 { - return &s.count -} - -// HistogramFinished can be called to indicate that the histogram has been populated. -// maxSymbol is the index of the highest set symbol of the next data segment. -// maxCount is the number of entries in the most populated entry. -// These are accepted at face value. -func (s *fseEncoder) HistogramFinished(maxSymbol uint8, maxCount int) { - s.maxCount = maxCount - s.symbolLen = uint16(maxSymbol) + 1 - s.clearCount = maxCount != 0 -} - -// allocCtable will allocate tables needed for compression. -// If existing tables a re big enough, they are simply re-used. -func (s *fseEncoder) allocCtable() { - tableSize := 1 << s.actualTableLog - // get tableSymbol that is big enough. - if cap(s.ct.tableSymbol) < tableSize { - s.ct.tableSymbol = make([]byte, tableSize) - } - s.ct.tableSymbol = s.ct.tableSymbol[:tableSize] - - ctSize := tableSize - if cap(s.ct.stateTable) < ctSize { - s.ct.stateTable = make([]uint16, ctSize) - } - s.ct.stateTable = s.ct.stateTable[:ctSize] - - if cap(s.ct.symbolTT) < 256 { - s.ct.symbolTT = make([]symbolTransform, 256) - } - s.ct.symbolTT = s.ct.symbolTT[:256] -} - -// buildCTable will populate the compression table so it is ready to be used. -func (s *fseEncoder) buildCTable() error { - tableSize := uint32(1 << s.actualTableLog) - highThreshold := tableSize - 1 - var cumul [256]int16 - - s.allocCtable() - tableSymbol := s.ct.tableSymbol[:tableSize] - // symbol start positions - { - cumul[0] = 0 - for ui, v := range s.norm[:s.symbolLen-1] { - u := byte(ui) // one less than reference - if v == -1 { - // Low proba symbol - cumul[u+1] = cumul[u] + 1 - tableSymbol[highThreshold] = u - highThreshold-- - } else { - cumul[u+1] = cumul[u] + v - } - } - // Encode last symbol separately to avoid overflowing u - u := int(s.symbolLen - 1) - v := s.norm[s.symbolLen-1] - if v == -1 { - // Low proba symbol - cumul[u+1] = cumul[u] + 1 - tableSymbol[highThreshold] = byte(u) - highThreshold-- - } else { - cumul[u+1] = cumul[u] + v - } - if uint32(cumul[s.symbolLen]) != tableSize { - return fmt.Errorf("internal error: expected cumul[s.symbolLen] (%d) == tableSize (%d)", cumul[s.symbolLen], tableSize) - } - cumul[s.symbolLen] = int16(tableSize) + 1 - } - // Spread symbols - s.zeroBits = false - { - step := tableStep(tableSize) - tableMask := tableSize - 1 - var position uint32 - // if any symbol > largeLimit, we may have 0 bits output. - largeLimit := int16(1 << (s.actualTableLog - 1)) - for ui, v := range s.norm[:s.symbolLen] { - symbol := byte(ui) - if v > largeLimit { - s.zeroBits = true - } - for nbOccurrences := int16(0); nbOccurrences < v; nbOccurrences++ { - tableSymbol[position] = symbol - position = (position + step) & tableMask - for position > highThreshold { - position = (position + step) & tableMask - } /* Low proba area */ - } - } - - // Check if we have gone through all positions - if position != 0 { - return errors.New("position!=0") - } - } - - // Build table - table := s.ct.stateTable - { - tsi := int(tableSize) - for u, v := range tableSymbol { - // TableU16 : sorted by symbol order; gives next state value - table[cumul[v]] = uint16(tsi + u) - cumul[v]++ - } - } - - // Build Symbol Transformation Table - { - total := int16(0) - symbolTT := s.ct.symbolTT[:s.symbolLen] - tableLog := s.actualTableLog - tl := (uint32(tableLog) << 16) - (1 << tableLog) - for i, v := range s.norm[:s.symbolLen] { - switch v { - case 0: - case -1, 1: - symbolTT[i].deltaNbBits = tl - symbolTT[i].deltaFindState = total - 1 - total++ - default: - maxBitsOut := uint32(tableLog) - highBit(uint32(v-1)) - minStatePlus := uint32(v) << maxBitsOut - symbolTT[i].deltaNbBits = (maxBitsOut << 16) - minStatePlus - symbolTT[i].deltaFindState = total - v - total += v - } - } - if total != int16(tableSize) { - return fmt.Errorf("total mismatch %d (got) != %d (want)", total, tableSize) - } - } - return nil -} - -var rtbTable = [...]uint32{0, 473195, 504333, 520860, 550000, 700000, 750000, 830000} - -func (s *fseEncoder) setRLE(val byte) { - s.allocCtable() - s.actualTableLog = 0 - s.ct.stateTable = s.ct.stateTable[:1] - s.ct.symbolTT[val] = symbolTransform{ - deltaFindState: 0, - deltaNbBits: 0, - } - if debugEncoder { - println("setRLE: val", val, "symbolTT", s.ct.symbolTT[val]) - } - s.rleVal = val - s.useRLE = true -} - -// setBits will set output bits for the transform. -// if nil is provided, the number of bits is equal to the index. -func (s *fseEncoder) setBits(transform []byte) { - if s.reUsed || s.preDefined { - return - } - if s.useRLE { - if transform == nil { - s.ct.symbolTT[s.rleVal].outBits = s.rleVal - s.maxBits = s.rleVal - return - } - s.maxBits = transform[s.rleVal] - s.ct.symbolTT[s.rleVal].outBits = s.maxBits - return - } - if transform == nil { - for i := range s.ct.symbolTT[:s.symbolLen] { - s.ct.symbolTT[i].outBits = uint8(i) - } - s.maxBits = uint8(s.symbolLen - 1) - return - } - s.maxBits = 0 - for i, v := range transform[:s.symbolLen] { - s.ct.symbolTT[i].outBits = v - if v > s.maxBits { - // We could assume bits always going up, but we play safe. - s.maxBits = v - } - } -} - -// normalizeCount will normalize the count of the symbols so -// the total is equal to the table size. -// If successful, compression tables will also be made ready. -func (s *fseEncoder) normalizeCount(length int) error { - if s.reUsed { - return nil - } - s.optimalTableLog(length) - var ( - tableLog = s.actualTableLog - scale = 62 - uint64(tableLog) - step = (1 << 62) / uint64(length) - vStep = uint64(1) << (scale - 20) - stillToDistribute = int16(1 << tableLog) - largest int - largestP int16 - lowThreshold = (uint32)(length >> tableLog) - ) - if s.maxCount == length { - s.useRLE = true - return nil - } - s.useRLE = false - for i, cnt := range s.count[:s.symbolLen] { - // already handled - // if (count[s] == s.length) return 0; /* rle special case */ - - if cnt == 0 { - s.norm[i] = 0 - continue - } - if cnt <= lowThreshold { - s.norm[i] = -1 - stillToDistribute-- - } else { - proba := (int16)((uint64(cnt) * step) >> scale) - if proba < 8 { - restToBeat := vStep * uint64(rtbTable[proba]) - v := uint64(cnt)*step - (uint64(proba) << scale) - if v > restToBeat { - proba++ - } - } - if proba > largestP { - largestP = proba - largest = i - } - s.norm[i] = proba - stillToDistribute -= proba - } - } - - if -stillToDistribute >= (s.norm[largest] >> 1) { - // corner case, need another normalization method - err := s.normalizeCount2(length) - if err != nil { - return err - } - if debugAsserts { - err = s.validateNorm() - if err != nil { - return err - } - } - return s.buildCTable() - } - s.norm[largest] += stillToDistribute - if debugAsserts { - err := s.validateNorm() - if err != nil { - return err - } - } - return s.buildCTable() -} - -// Secondary normalization method. -// To be used when primary method fails. -func (s *fseEncoder) normalizeCount2(length int) error { - const notYetAssigned = -2 - var ( - distributed uint32 - total = uint32(length) - tableLog = s.actualTableLog - lowThreshold = total >> tableLog - lowOne = (total * 3) >> (tableLog + 1) - ) - for i, cnt := range s.count[:s.symbolLen] { - if cnt == 0 { - s.norm[i] = 0 - continue - } - if cnt <= lowThreshold { - s.norm[i] = -1 - distributed++ - total -= cnt - continue - } - if cnt <= lowOne { - s.norm[i] = 1 - distributed++ - total -= cnt - continue - } - s.norm[i] = notYetAssigned - } - toDistribute := (1 << tableLog) - distributed - - if (total / toDistribute) > lowOne { - // risk of rounding to zero - lowOne = (total * 3) / (toDistribute * 2) - for i, cnt := range s.count[:s.symbolLen] { - if (s.norm[i] == notYetAssigned) && (cnt <= lowOne) { - s.norm[i] = 1 - distributed++ - total -= cnt - continue - } - } - toDistribute = (1 << tableLog) - distributed - } - if distributed == uint32(s.symbolLen)+1 { - // all values are pretty poor; - // probably incompressible data (should have already been detected); - // find max, then give all remaining points to max - var maxV int - var maxC uint32 - for i, cnt := range s.count[:s.symbolLen] { - if cnt > maxC { - maxV = i - maxC = cnt - } - } - s.norm[maxV] += int16(toDistribute) - return nil - } - - if total == 0 { - // all of the symbols were low enough for the lowOne or lowThreshold - for i := uint32(0); toDistribute > 0; i = (i + 1) % (uint32(s.symbolLen)) { - if s.norm[i] > 0 { - toDistribute-- - s.norm[i]++ - } - } - return nil - } - - var ( - vStepLog = 62 - uint64(tableLog) - mid = uint64((1 << (vStepLog - 1)) - 1) - rStep = (((1 << vStepLog) * uint64(toDistribute)) + mid) / uint64(total) // scale on remaining - tmpTotal = mid - ) - for i, cnt := range s.count[:s.symbolLen] { - if s.norm[i] == notYetAssigned { - var ( - end = tmpTotal + uint64(cnt)*rStep - sStart = uint32(tmpTotal >> vStepLog) - sEnd = uint32(end >> vStepLog) - weight = sEnd - sStart - ) - if weight < 1 { - return errors.New("weight < 1") - } - s.norm[i] = int16(weight) - tmpTotal = end - } - } - return nil -} - -// optimalTableLog calculates and sets the optimal tableLog in s.actualTableLog -func (s *fseEncoder) optimalTableLog(length int) { - tableLog := uint8(maxEncTableLog) - minBitsSrc := highBit(uint32(length)) + 1 - minBitsSymbols := highBit(uint32(s.symbolLen-1)) + 2 - minBits := uint8(minBitsSymbols) - if minBitsSrc < minBitsSymbols { - minBits = uint8(minBitsSrc) - } - - maxBitsSrc := uint8(highBit(uint32(length-1))) - 2 - if maxBitsSrc < tableLog { - // Accuracy can be reduced - tableLog = maxBitsSrc - } - if minBits > tableLog { - tableLog = minBits - } - // Need a minimum to safely represent all symbol values - if tableLog < minEncTablelog { - tableLog = minEncTablelog - } - if tableLog > maxEncTableLog { - tableLog = maxEncTableLog - } - s.actualTableLog = tableLog -} - -// validateNorm validates the normalized histogram table. -func (s *fseEncoder) validateNorm() (err error) { - var total int - for _, v := range s.norm[:s.symbolLen] { - if v >= 0 { - total += int(v) - } else { - total -= int(v) - } - } - defer func() { - if err == nil { - return - } - fmt.Printf("selected TableLog: %d, Symbol length: %d\n", s.actualTableLog, s.symbolLen) - for i, v := range s.norm[:s.symbolLen] { - fmt.Printf("%3d: %5d -> %4d \n", i, s.count[i], v) - } - }() - if total != (1 << s.actualTableLog) { - return fmt.Errorf("warning: Total == %d != %d", total, 1<> 3) + 3 + 2 - - // Write Table Size - bitStream = uint32(tableLog - minEncTablelog) - bitCount = uint(4) - remaining = int16(tableSize + 1) /* +1 for extra accuracy */ - threshold = int16(tableSize) - nbBits = uint(tableLog + 1) - outP = len(out) - ) - if cap(out) < outP+maxHeaderSize { - out = append(out, make([]byte, maxHeaderSize*3)...) - out = out[:len(out)-maxHeaderSize*3] - } - out = out[:outP+maxHeaderSize] - - // stops at 1 - for remaining > 1 { - if previous0 { - start := charnum - for s.norm[charnum] == 0 { - charnum++ - } - for charnum >= start+24 { - start += 24 - bitStream += uint32(0xFFFF) << bitCount - out[outP] = byte(bitStream) - out[outP+1] = byte(bitStream >> 8) - outP += 2 - bitStream >>= 16 - } - for charnum >= start+3 { - start += 3 - bitStream += 3 << bitCount - bitCount += 2 - } - bitStream += uint32(charnum-start) << bitCount - bitCount += 2 - if bitCount > 16 { - out[outP] = byte(bitStream) - out[outP+1] = byte(bitStream >> 8) - outP += 2 - bitStream >>= 16 - bitCount -= 16 - } - } - - count := s.norm[charnum] - charnum++ - max := (2*threshold - 1) - remaining - if count < 0 { - remaining += count - } else { - remaining -= count - } - count++ // +1 for extra accuracy - if count >= threshold { - count += max // [0..max[ [max..threshold[ (...) [threshold+max 2*threshold[ - } - bitStream += uint32(count) << bitCount - bitCount += nbBits - if count < max { - bitCount-- - } - - previous0 = count == 1 - if remaining < 1 { - return nil, errors.New("internal error: remaining < 1") - } - for remaining < threshold { - nbBits-- - threshold >>= 1 - } - - if bitCount > 16 { - out[outP] = byte(bitStream) - out[outP+1] = byte(bitStream >> 8) - outP += 2 - bitStream >>= 16 - bitCount -= 16 - } - } - - if outP+2 > len(out) { - return nil, fmt.Errorf("internal error: %d > %d, maxheader: %d, sl: %d, tl: %d, normcount: %v", outP+2, len(out), maxHeaderSize, s.symbolLen, int(tableLog), s.norm[:s.symbolLen]) - } - out[outP] = byte(bitStream) - out[outP+1] = byte(bitStream >> 8) - outP += int((bitCount + 7) / 8) - - if charnum > s.symbolLen { - return nil, errors.New("internal error: charnum > s.symbolLen") - } - return out[:outP], nil -} - -// Approximate symbol cost, as fractional value, using fixed-point format (accuracyLog fractional bits) -// note 1 : assume symbolValue is valid (<= maxSymbolValue) -// note 2 : if freq[symbolValue]==0, @return a fake cost of tableLog+1 bits * -func (s *fseEncoder) bitCost(symbolValue uint8, accuracyLog uint32) uint32 { - minNbBits := s.ct.symbolTT[symbolValue].deltaNbBits >> 16 - threshold := (minNbBits + 1) << 16 - if debugAsserts { - if !(s.actualTableLog < 16) { - panic("!s.actualTableLog < 16") - } - // ensure enough room for renormalization double shift - if !(uint8(accuracyLog) < 31-s.actualTableLog) { - panic("!uint8(accuracyLog) < 31-s.actualTableLog") - } - } - tableSize := uint32(1) << s.actualTableLog - deltaFromThreshold := threshold - (s.ct.symbolTT[symbolValue].deltaNbBits + tableSize) - // linear interpolation (very approximate) - normalizedDeltaFromThreshold := (deltaFromThreshold << accuracyLog) >> s.actualTableLog - bitMultiplier := uint32(1) << accuracyLog - if debugAsserts { - if s.ct.symbolTT[symbolValue].deltaNbBits+tableSize > threshold { - panic("s.ct.symbolTT[symbolValue].deltaNbBits+tableSize > threshold") - } - if normalizedDeltaFromThreshold > bitMultiplier { - panic("normalizedDeltaFromThreshold > bitMultiplier") - } - } - return (minNbBits+1)*bitMultiplier - normalizedDeltaFromThreshold -} - -// Returns the cost in bits of encoding the distribution in count using ctable. -// Histogram should only be up to the last non-zero symbol. -// Returns an -1 if ctable cannot represent all the symbols in count. -func (s *fseEncoder) approxSize(hist []uint32) uint32 { - if int(s.symbolLen) < len(hist) { - // More symbols than we have. - return math.MaxUint32 - } - if s.useRLE { - // We will never reuse RLE encoders. - return math.MaxUint32 - } - const kAccuracyLog = 8 - badCost := (uint32(s.actualTableLog) + 1) << kAccuracyLog - var cost uint32 - for i, v := range hist { - if v == 0 { - continue - } - if s.norm[i] == 0 { - return math.MaxUint32 - } - bitCost := s.bitCost(uint8(i), kAccuracyLog) - if bitCost > badCost { - return math.MaxUint32 - } - cost += v * bitCost - } - return cost >> kAccuracyLog -} - -// maxHeaderSize returns the maximum header size in bits. -// This is not exact size, but we want a penalty for new tables anyway. -func (s *fseEncoder) maxHeaderSize() uint32 { - if s.preDefined { - return 0 - } - if s.useRLE { - return 8 - } - return (((uint32(s.symbolLen) * uint32(s.actualTableLog)) >> 3) + 3) * 8 -} - -// cState contains the compression state of a stream. -type cState struct { - bw *bitWriter - stateTable []uint16 - state uint16 -} - -// init will initialize the compression state to the first symbol of the stream. -func (c *cState) init(bw *bitWriter, ct *cTable, first symbolTransform) { - c.bw = bw - c.stateTable = ct.stateTable - if len(c.stateTable) == 1 { - // RLE - c.stateTable[0] = uint16(0) - c.state = 0 - return - } - nbBitsOut := (first.deltaNbBits + (1 << 15)) >> 16 - im := int32((nbBitsOut << 16) - first.deltaNbBits) - lu := (im >> nbBitsOut) + int32(first.deltaFindState) - c.state = c.stateTable[lu] -} - -// flush will write the tablelog to the output and flush the remaining full bytes. -func (c *cState) flush(tableLog uint8) { - c.bw.flush32() - c.bw.addBits16NC(c.state, tableLog) -} diff --git a/vendor/github.com/klauspost/compress/zstd/fse_predefined.go b/vendor/github.com/klauspost/compress/zstd/fse_predefined.go deleted file mode 100644 index 474cb77d2..000000000 --- a/vendor/github.com/klauspost/compress/zstd/fse_predefined.go +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "fmt" - "math" - "sync" -) - -var ( - // fsePredef are the predefined fse tables as defined here: - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#default-distributions - // These values are already transformed. - fsePredef [3]fseDecoder - - // fsePredefEnc are the predefined encoder based on fse tables as defined here: - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#default-distributions - // These values are already transformed. - fsePredefEnc [3]fseEncoder - - // symbolTableX contain the transformations needed for each type as defined in - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#the-codes-for-literals-lengths-match-lengths-and-offsets - symbolTableX [3][]baseOffset - - // maxTableSymbol is the biggest supported symbol for each table type - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#the-codes-for-literals-lengths-match-lengths-and-offsets - maxTableSymbol = [3]uint8{tableLiteralLengths: maxLiteralLengthSymbol, tableOffsets: maxOffsetLengthSymbol, tableMatchLengths: maxMatchLengthSymbol} - - // bitTables is the bits table for each table. - bitTables = [3][]byte{tableLiteralLengths: llBitsTable[:], tableOffsets: nil, tableMatchLengths: mlBitsTable[:]} -) - -type tableIndex uint8 - -const ( - // indexes for fsePredef and symbolTableX - tableLiteralLengths tableIndex = 0 - tableOffsets tableIndex = 1 - tableMatchLengths tableIndex = 2 - - maxLiteralLengthSymbol = 35 - maxOffsetLengthSymbol = 30 - maxMatchLengthSymbol = 52 -) - -// baseOffset is used for calculating transformations. -type baseOffset struct { - baseLine uint32 - addBits uint8 -} - -// fillBase will precalculate base offsets with the given bit distributions. -func fillBase(dst []baseOffset, base uint32, bits ...uint8) { - if len(bits) != len(dst) { - panic(fmt.Sprintf("len(dst) (%d) != len(bits) (%d)", len(dst), len(bits))) - } - for i, bit := range bits { - if base > math.MaxInt32 { - panic("invalid decoding table, base overflows int32") - } - - dst[i] = baseOffset{ - baseLine: base, - addBits: bit, - } - base += 1 << bit - } -} - -var predef sync.Once - -func initPredefined() { - predef.Do(func() { - // Literals length codes - tmp := make([]baseOffset, 36) - for i := range tmp[:16] { - tmp[i] = baseOffset{ - baseLine: uint32(i), - addBits: 0, - } - } - fillBase(tmp[16:], 16, 1, 1, 1, 1, 2, 2, 3, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16) - symbolTableX[tableLiteralLengths] = tmp - - // Match length codes - tmp = make([]baseOffset, 53) - for i := range tmp[:32] { - tmp[i] = baseOffset{ - // The transformation adds the 3 length. - baseLine: uint32(i) + 3, - addBits: 0, - } - } - fillBase(tmp[32:], 35, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16) - symbolTableX[tableMatchLengths] = tmp - - // Offset codes - tmp = make([]baseOffset, maxOffsetBits+1) - tmp[1] = baseOffset{ - baseLine: 1, - addBits: 1, - } - fillBase(tmp[2:], 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30) - symbolTableX[tableOffsets] = tmp - - // Fill predefined tables and transform them. - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#default-distributions - for i := range fsePredef[:] { - f := &fsePredef[i] - switch tableIndex(i) { - case tableLiteralLengths: - // https://github.com/facebook/zstd/blob/ededcfca57366461021c922720878c81a5854a0a/lib/decompress/zstd_decompress_block.c#L243 - f.actualTableLog = 6 - copy(f.norm[:], []int16{4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1, - -1, -1, -1, -1}) - f.symbolLen = 36 - case tableOffsets: - // https://github.com/facebook/zstd/blob/ededcfca57366461021c922720878c81a5854a0a/lib/decompress/zstd_decompress_block.c#L281 - f.actualTableLog = 5 - copy(f.norm[:], []int16{ - 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1}) - f.symbolLen = 29 - case tableMatchLengths: - //https://github.com/facebook/zstd/blob/ededcfca57366461021c922720878c81a5854a0a/lib/decompress/zstd_decompress_block.c#L304 - f.actualTableLog = 6 - copy(f.norm[:], []int16{ - 1, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, - -1, -1, -1, -1, -1}) - f.symbolLen = 53 - } - if err := f.buildDtable(); err != nil { - panic(fmt.Errorf("building table %v: %v", tableIndex(i), err)) - } - if err := f.transform(symbolTableX[i]); err != nil { - panic(fmt.Errorf("building table %v: %v", tableIndex(i), err)) - } - f.preDefined = true - - // Create encoder as well - enc := &fsePredefEnc[i] - copy(enc.norm[:], f.norm[:]) - enc.symbolLen = f.symbolLen - enc.actualTableLog = f.actualTableLog - if err := enc.buildCTable(); err != nil { - panic(fmt.Errorf("building encoding table %v: %v", tableIndex(i), err)) - } - enc.setBits(bitTables[i]) - enc.preDefined = true - } - }) -} diff --git a/vendor/github.com/klauspost/compress/zstd/hash.go b/vendor/github.com/klauspost/compress/zstd/hash.go deleted file mode 100644 index 5d73c21eb..000000000 --- a/vendor/github.com/klauspost/compress/zstd/hash.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -const ( - prime3bytes = 506832829 - prime4bytes = 2654435761 - prime5bytes = 889523592379 - prime6bytes = 227718039650203 - prime7bytes = 58295818150454627 - prime8bytes = 0xcf1bbcdcb7a56463 -) - -// hashLen returns a hash of the lowest mls bytes of with length output bits. -// mls must be >=3 and <=8. Any other value will return hash for 4 bytes. -// length should always be < 32. -// Preferably length and mls should be a constant for inlining. -func hashLen(u uint64, length, mls uint8) uint32 { - switch mls { - case 3: - return (uint32(u<<8) * prime3bytes) >> (32 - length) - case 5: - return uint32(((u << (64 - 40)) * prime5bytes) >> (64 - length)) - case 6: - return uint32(((u << (64 - 48)) * prime6bytes) >> (64 - length)) - case 7: - return uint32(((u << (64 - 56)) * prime7bytes) >> (64 - length)) - case 8: - return uint32((u * prime8bytes) >> (64 - length)) - default: - return (uint32(u) * prime4bytes) >> (32 - length) - } -} diff --git a/vendor/github.com/klauspost/compress/zstd/history.go b/vendor/github.com/klauspost/compress/zstd/history.go deleted file mode 100644 index 09164856d..000000000 --- a/vendor/github.com/klauspost/compress/zstd/history.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "github.com/klauspost/compress/huff0" -) - -// history contains the information transferred between blocks. -type history struct { - // Literal decompression - huffTree *huff0.Scratch - - // Sequence decompression - decoders sequenceDecs - recentOffsets [3]int - - // History buffer... - b []byte - - // ignoreBuffer is meant to ignore a number of bytes - // when checking for matches in history - ignoreBuffer int - - windowSize int - allocFrameBuffer int // needed? - error bool - dict *dict -} - -// reset will reset the history to initial state of a frame. -// The history must already have been initialized to the desired size. -func (h *history) reset() { - h.b = h.b[:0] - h.ignoreBuffer = 0 - h.error = false - h.recentOffsets = [3]int{1, 4, 8} - h.decoders.freeDecoders() - h.decoders = sequenceDecs{br: h.decoders.br} - h.freeHuffDecoder() - h.huffTree = nil - h.dict = nil - //printf("history created: %+v (l: %d, c: %d)", *h, len(h.b), cap(h.b)) -} - -func (h *history) freeHuffDecoder() { - if h.huffTree != nil { - if h.dict == nil || h.dict.litEnc != h.huffTree { - huffDecoderPool.Put(h.huffTree) - h.huffTree = nil - } - } -} - -func (h *history) setDict(dict *dict) { - if dict == nil { - return - } - h.dict = dict - h.decoders.litLengths = dict.llDec - h.decoders.offsets = dict.ofDec - h.decoders.matchLengths = dict.mlDec - h.decoders.dict = dict.content - h.recentOffsets = dict.offsets - h.huffTree = dict.litEnc -} - -// append bytes to history. -// This function will make sure there is space for it, -// if the buffer has been allocated with enough extra space. -func (h *history) append(b []byte) { - if len(b) >= h.windowSize { - // Discard all history by simply overwriting - h.b = h.b[:h.windowSize] - copy(h.b, b[len(b)-h.windowSize:]) - return - } - - // If there is space, append it. - if len(b) < cap(h.b)-len(h.b) { - h.b = append(h.b, b...) - return - } - - // Move data down so we only have window size left. - // We know we have less than window size in b at this point. - discard := len(b) + len(h.b) - h.windowSize - copy(h.b, h.b[discard:]) - h.b = h.b[:h.windowSize] - copy(h.b[h.windowSize-len(b):], b) -} - -// ensureBlock will ensure there is space for at least one block... -func (h *history) ensureBlock() { - if cap(h.b) < h.allocFrameBuffer { - h.b = make([]byte, 0, h.allocFrameBuffer) - return - } - - avail := cap(h.b) - len(h.b) - if avail >= h.windowSize || avail > maxCompressedBlockSize { - return - } - // Move data down so we only have window size left. - // We know we have less than window size in b at this point. - discard := len(h.b) - h.windowSize - copy(h.b, h.b[discard:]) - h.b = h.b[:h.windowSize] -} - -// append bytes to history without ever discarding anything. -func (h *history) appendKeep(b []byte) { - h.b = append(h.b, b...) -} diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/LICENSE.txt b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/LICENSE.txt deleted file mode 100644 index 24b53065f..000000000 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/LICENSE.txt +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2016 Caleb Spare - -MIT License - -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. diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/README.md b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/README.md deleted file mode 100644 index 777290d44..000000000 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/README.md +++ /dev/null @@ -1,71 +0,0 @@ -# xxhash - -VENDORED: Go to [github.com/cespare/xxhash](https://github.com/cespare/xxhash) for original package. - -xxhash is a Go implementation of the 64-bit [xxHash] algorithm, XXH64. This is a -high-quality hashing algorithm that is much faster than anything in the Go -standard library. - -This package provides a straightforward API: - -``` -func Sum64(b []byte) uint64 -func Sum64String(s string) uint64 -type Digest struct{ ... } - func New() *Digest -``` - -The `Digest` type implements hash.Hash64. Its key methods are: - -``` -func (*Digest) Write([]byte) (int, error) -func (*Digest) WriteString(string) (int, error) -func (*Digest) Sum64() uint64 -``` - -The package is written with optimized pure Go and also contains even faster -assembly implementations for amd64 and arm64. If desired, the `purego` build tag -opts into using the Go code even on those architectures. - -[xxHash]: http://cyan4973.github.io/xxHash/ - -## Compatibility - -This package is in a module and the latest code is in version 2 of the module. -You need a version of Go with at least "minimal module compatibility" to use -github.com/cespare/xxhash/v2: - -* 1.9.7+ for Go 1.9 -* 1.10.3+ for Go 1.10 -* Go 1.11 or later - -I recommend using the latest release of Go. - -## Benchmarks - -Here are some quick benchmarks comparing the pure-Go and assembly -implementations of Sum64. - -| input size | purego | asm | -| ---------- | --------- | --------- | -| 4 B | 1.3 GB/s | 1.2 GB/s | -| 16 B | 2.9 GB/s | 3.5 GB/s | -| 100 B | 6.9 GB/s | 8.1 GB/s | -| 4 KB | 11.7 GB/s | 16.7 GB/s | -| 10 MB | 12.0 GB/s | 17.3 GB/s | - -These numbers were generated on Ubuntu 20.04 with an Intel Xeon Platinum 8252C -CPU using the following commands under Go 1.19.2: - -``` -benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$') -benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$') -``` - -## Projects using this package - -- [InfluxDB](https://github.com/influxdata/influxdb) -- [Prometheus](https://github.com/prometheus/prometheus) -- [VictoriaMetrics](https://github.com/VictoriaMetrics/VictoriaMetrics) -- [FreeCache](https://github.com/coocood/freecache) -- [FastCache](https://github.com/VictoriaMetrics/fastcache) diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash.go b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash.go deleted file mode 100644 index fc40c8200..000000000 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash.go +++ /dev/null @@ -1,230 +0,0 @@ -// Package xxhash implements the 64-bit variant of xxHash (XXH64) as described -// at http://cyan4973.github.io/xxHash/. -// THIS IS VENDORED: Go to github.com/cespare/xxhash for original package. - -package xxhash - -import ( - "encoding/binary" - "errors" - "math/bits" -) - -const ( - prime1 uint64 = 11400714785074694791 - prime2 uint64 = 14029467366897019727 - prime3 uint64 = 1609587929392839161 - prime4 uint64 = 9650029242287828579 - prime5 uint64 = 2870177450012600261 -) - -// Store the primes in an array as well. -// -// The consts are used when possible in Go code to avoid MOVs but we need a -// contiguous array of the assembly code. -var primes = [...]uint64{prime1, prime2, prime3, prime4, prime5} - -// Digest implements hash.Hash64. -type Digest struct { - v1 uint64 - v2 uint64 - v3 uint64 - v4 uint64 - total uint64 - mem [32]byte - n int // how much of mem is used -} - -// New creates a new Digest that computes the 64-bit xxHash algorithm. -func New() *Digest { - var d Digest - d.Reset() - return &d -} - -// Reset clears the Digest's state so that it can be reused. -func (d *Digest) Reset() { - d.v1 = primes[0] + prime2 - d.v2 = prime2 - d.v3 = 0 - d.v4 = -primes[0] - d.total = 0 - d.n = 0 -} - -// Size always returns 8 bytes. -func (d *Digest) Size() int { return 8 } - -// BlockSize always returns 32 bytes. -func (d *Digest) BlockSize() int { return 32 } - -// Write adds more data to d. It always returns len(b), nil. -func (d *Digest) Write(b []byte) (n int, err error) { - n = len(b) - d.total += uint64(n) - - memleft := d.mem[d.n&(len(d.mem)-1):] - - if d.n+n < 32 { - // This new data doesn't even fill the current block. - copy(memleft, b) - d.n += n - return - } - - if d.n > 0 { - // Finish off the partial block. - c := copy(memleft, b) - d.v1 = round(d.v1, u64(d.mem[0:8])) - d.v2 = round(d.v2, u64(d.mem[8:16])) - d.v3 = round(d.v3, u64(d.mem[16:24])) - d.v4 = round(d.v4, u64(d.mem[24:32])) - b = b[c:] - d.n = 0 - } - - if len(b) >= 32 { - // One or more full blocks left. - nw := writeBlocks(d, b) - b = b[nw:] - } - - // Store any remaining partial block. - copy(d.mem[:], b) - d.n = len(b) - - return -} - -// Sum appends the current hash to b and returns the resulting slice. -func (d *Digest) Sum(b []byte) []byte { - s := d.Sum64() - return append( - b, - byte(s>>56), - byte(s>>48), - byte(s>>40), - byte(s>>32), - byte(s>>24), - byte(s>>16), - byte(s>>8), - byte(s), - ) -} - -// Sum64 returns the current hash. -func (d *Digest) Sum64() uint64 { - var h uint64 - - if d.total >= 32 { - v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4 - h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) - h = mergeRound(h, v1) - h = mergeRound(h, v2) - h = mergeRound(h, v3) - h = mergeRound(h, v4) - } else { - h = d.v3 + prime5 - } - - h += d.total - - b := d.mem[:d.n&(len(d.mem)-1)] - for ; len(b) >= 8; b = b[8:] { - k1 := round(0, u64(b[:8])) - h ^= k1 - h = rol27(h)*prime1 + prime4 - } - if len(b) >= 4 { - h ^= uint64(u32(b[:4])) * prime1 - h = rol23(h)*prime2 + prime3 - b = b[4:] - } - for ; len(b) > 0; b = b[1:] { - h ^= uint64(b[0]) * prime5 - h = rol11(h) * prime1 - } - - h ^= h >> 33 - h *= prime2 - h ^= h >> 29 - h *= prime3 - h ^= h >> 32 - - return h -} - -const ( - magic = "xxh\x06" - marshaledSize = len(magic) + 8*5 + 32 -) - -// MarshalBinary implements the encoding.BinaryMarshaler interface. -func (d *Digest) MarshalBinary() ([]byte, error) { - b := make([]byte, 0, marshaledSize) - b = append(b, magic...) - b = appendUint64(b, d.v1) - b = appendUint64(b, d.v2) - b = appendUint64(b, d.v3) - b = appendUint64(b, d.v4) - b = appendUint64(b, d.total) - b = append(b, d.mem[:d.n]...) - b = b[:len(b)+len(d.mem)-d.n] - return b, nil -} - -// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. -func (d *Digest) UnmarshalBinary(b []byte) error { - if len(b) < len(magic) || string(b[:len(magic)]) != magic { - return errors.New("xxhash: invalid hash state identifier") - } - if len(b) != marshaledSize { - return errors.New("xxhash: invalid hash state size") - } - b = b[len(magic):] - b, d.v1 = consumeUint64(b) - b, d.v2 = consumeUint64(b) - b, d.v3 = consumeUint64(b) - b, d.v4 = consumeUint64(b) - b, d.total = consumeUint64(b) - copy(d.mem[:], b) - d.n = int(d.total % uint64(len(d.mem))) - return nil -} - -func appendUint64(b []byte, x uint64) []byte { - var a [8]byte - binary.LittleEndian.PutUint64(a[:], x) - return append(b, a[:]...) -} - -func consumeUint64(b []byte) ([]byte, uint64) { - x := u64(b) - return b[8:], x -} - -func u64(b []byte) uint64 { return binary.LittleEndian.Uint64(b) } -func u32(b []byte) uint32 { return binary.LittleEndian.Uint32(b) } - -func round(acc, input uint64) uint64 { - acc += input * prime2 - acc = rol31(acc) - acc *= prime1 - return acc -} - -func mergeRound(acc, val uint64) uint64 { - val = round(0, val) - acc ^= val - acc = acc*prime1 + prime4 - return acc -} - -func rol1(x uint64) uint64 { return bits.RotateLeft64(x, 1) } -func rol7(x uint64) uint64 { return bits.RotateLeft64(x, 7) } -func rol11(x uint64) uint64 { return bits.RotateLeft64(x, 11) } -func rol12(x uint64) uint64 { return bits.RotateLeft64(x, 12) } -func rol18(x uint64) uint64 { return bits.RotateLeft64(x, 18) } -func rol23(x uint64) uint64 { return bits.RotateLeft64(x, 23) } -func rol27(x uint64) uint64 { return bits.RotateLeft64(x, 27) } -func rol31(x uint64) uint64 { return bits.RotateLeft64(x, 31) } diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_amd64.s b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_amd64.s deleted file mode 100644 index ddb63aa91..000000000 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_amd64.s +++ /dev/null @@ -1,210 +0,0 @@ -//go:build !appengine && gc && !purego && !noasm -// +build !appengine -// +build gc -// +build !purego -// +build !noasm - -#include "textflag.h" - -// Registers: -#define h AX -#define d AX -#define p SI // pointer to advance through b -#define n DX -#define end BX // loop end -#define v1 R8 -#define v2 R9 -#define v3 R10 -#define v4 R11 -#define x R12 -#define prime1 R13 -#define prime2 R14 -#define prime4 DI - -#define round(acc, x) \ - IMULQ prime2, x \ - ADDQ x, acc \ - ROLQ $31, acc \ - IMULQ prime1, acc - -// round0 performs the operation x = round(0, x). -#define round0(x) \ - IMULQ prime2, x \ - ROLQ $31, x \ - IMULQ prime1, x - -// mergeRound applies a merge round on the two registers acc and x. -// It assumes that prime1, prime2, and prime4 have been loaded. -#define mergeRound(acc, x) \ - round0(x) \ - XORQ x, acc \ - IMULQ prime1, acc \ - ADDQ prime4, acc - -// blockLoop processes as many 32-byte blocks as possible, -// updating v1, v2, v3, and v4. It assumes that there is at least one block -// to process. -#define blockLoop() \ -loop: \ - MOVQ +0(p), x \ - round(v1, x) \ - MOVQ +8(p), x \ - round(v2, x) \ - MOVQ +16(p), x \ - round(v3, x) \ - MOVQ +24(p), x \ - round(v4, x) \ - ADDQ $32, p \ - CMPQ p, end \ - JLE loop - -// func Sum64(b []byte) uint64 -TEXT ·Sum64(SB), NOSPLIT|NOFRAME, $0-32 - // Load fixed primes. - MOVQ ·primes+0(SB), prime1 - MOVQ ·primes+8(SB), prime2 - MOVQ ·primes+24(SB), prime4 - - // Load slice. - MOVQ b_base+0(FP), p - MOVQ b_len+8(FP), n - LEAQ (p)(n*1), end - - // The first loop limit will be len(b)-32. - SUBQ $32, end - - // Check whether we have at least one block. - CMPQ n, $32 - JLT noBlocks - - // Set up initial state (v1, v2, v3, v4). - MOVQ prime1, v1 - ADDQ prime2, v1 - MOVQ prime2, v2 - XORQ v3, v3 - XORQ v4, v4 - SUBQ prime1, v4 - - blockLoop() - - MOVQ v1, h - ROLQ $1, h - MOVQ v2, x - ROLQ $7, x - ADDQ x, h - MOVQ v3, x - ROLQ $12, x - ADDQ x, h - MOVQ v4, x - ROLQ $18, x - ADDQ x, h - - mergeRound(h, v1) - mergeRound(h, v2) - mergeRound(h, v3) - mergeRound(h, v4) - - JMP afterBlocks - -noBlocks: - MOVQ ·primes+32(SB), h - -afterBlocks: - ADDQ n, h - - ADDQ $24, end - CMPQ p, end - JG try4 - -loop8: - MOVQ (p), x - ADDQ $8, p - round0(x) - XORQ x, h - ROLQ $27, h - IMULQ prime1, h - ADDQ prime4, h - - CMPQ p, end - JLE loop8 - -try4: - ADDQ $4, end - CMPQ p, end - JG try1 - - MOVL (p), x - ADDQ $4, p - IMULQ prime1, x - XORQ x, h - - ROLQ $23, h - IMULQ prime2, h - ADDQ ·primes+16(SB), h - -try1: - ADDQ $4, end - CMPQ p, end - JGE finalize - -loop1: - MOVBQZX (p), x - ADDQ $1, p - IMULQ ·primes+32(SB), x - XORQ x, h - ROLQ $11, h - IMULQ prime1, h - - CMPQ p, end - JL loop1 - -finalize: - MOVQ h, x - SHRQ $33, x - XORQ x, h - IMULQ prime2, h - MOVQ h, x - SHRQ $29, x - XORQ x, h - IMULQ ·primes+16(SB), h - MOVQ h, x - SHRQ $32, x - XORQ x, h - - MOVQ h, ret+24(FP) - RET - -// func writeBlocks(d *Digest, b []byte) int -TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40 - // Load fixed primes needed for round. - MOVQ ·primes+0(SB), prime1 - MOVQ ·primes+8(SB), prime2 - - // Load slice. - MOVQ b_base+8(FP), p - MOVQ b_len+16(FP), n - LEAQ (p)(n*1), end - SUBQ $32, end - - // Load vN from d. - MOVQ s+0(FP), d - MOVQ 0(d), v1 - MOVQ 8(d), v2 - MOVQ 16(d), v3 - MOVQ 24(d), v4 - - // We don't need to check the loop condition here; this function is - // always called with at least one block of data to process. - blockLoop() - - // Copy vN back to d. - MOVQ v1, 0(d) - MOVQ v2, 8(d) - MOVQ v3, 16(d) - MOVQ v4, 24(d) - - // The number of bytes written is p minus the old base pointer. - SUBQ b_base+8(FP), p - MOVQ p, ret+32(FP) - - RET diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_arm64.s b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_arm64.s deleted file mode 100644 index 17901e080..000000000 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_arm64.s +++ /dev/null @@ -1,184 +0,0 @@ -//go:build !appengine && gc && !purego && !noasm -// +build !appengine -// +build gc -// +build !purego -// +build !noasm - -#include "textflag.h" - -// Registers: -#define digest R1 -#define h R2 // return value -#define p R3 // input pointer -#define n R4 // input length -#define nblocks R5 // n / 32 -#define prime1 R7 -#define prime2 R8 -#define prime3 R9 -#define prime4 R10 -#define prime5 R11 -#define v1 R12 -#define v2 R13 -#define v3 R14 -#define v4 R15 -#define x1 R20 -#define x2 R21 -#define x3 R22 -#define x4 R23 - -#define round(acc, x) \ - MADD prime2, acc, x, acc \ - ROR $64-31, acc \ - MUL prime1, acc - -// round0 performs the operation x = round(0, x). -#define round0(x) \ - MUL prime2, x \ - ROR $64-31, x \ - MUL prime1, x - -#define mergeRound(acc, x) \ - round0(x) \ - EOR x, acc \ - MADD acc, prime4, prime1, acc - -// blockLoop processes as many 32-byte blocks as possible, -// updating v1, v2, v3, and v4. It assumes that n >= 32. -#define blockLoop() \ - LSR $5, n, nblocks \ - PCALIGN $16 \ - loop: \ - LDP.P 16(p), (x1, x2) \ - LDP.P 16(p), (x3, x4) \ - round(v1, x1) \ - round(v2, x2) \ - round(v3, x3) \ - round(v4, x4) \ - SUB $1, nblocks \ - CBNZ nblocks, loop - -// func Sum64(b []byte) uint64 -TEXT ·Sum64(SB), NOSPLIT|NOFRAME, $0-32 - LDP b_base+0(FP), (p, n) - - LDP ·primes+0(SB), (prime1, prime2) - LDP ·primes+16(SB), (prime3, prime4) - MOVD ·primes+32(SB), prime5 - - CMP $32, n - CSEL LT, prime5, ZR, h // if n < 32 { h = prime5 } else { h = 0 } - BLT afterLoop - - ADD prime1, prime2, v1 - MOVD prime2, v2 - MOVD $0, v3 - NEG prime1, v4 - - blockLoop() - - ROR $64-1, v1, x1 - ROR $64-7, v2, x2 - ADD x1, x2 - ROR $64-12, v3, x3 - ROR $64-18, v4, x4 - ADD x3, x4 - ADD x2, x4, h - - mergeRound(h, v1) - mergeRound(h, v2) - mergeRound(h, v3) - mergeRound(h, v4) - -afterLoop: - ADD n, h - - TBZ $4, n, try8 - LDP.P 16(p), (x1, x2) - - round0(x1) - - // NOTE: here and below, sequencing the EOR after the ROR (using a - // rotated register) is worth a small but measurable speedup for small - // inputs. - ROR $64-27, h - EOR x1 @> 64-27, h, h - MADD h, prime4, prime1, h - - round0(x2) - ROR $64-27, h - EOR x2 @> 64-27, h, h - MADD h, prime4, prime1, h - -try8: - TBZ $3, n, try4 - MOVD.P 8(p), x1 - - round0(x1) - ROR $64-27, h - EOR x1 @> 64-27, h, h - MADD h, prime4, prime1, h - -try4: - TBZ $2, n, try2 - MOVWU.P 4(p), x2 - - MUL prime1, x2 - ROR $64-23, h - EOR x2 @> 64-23, h, h - MADD h, prime3, prime2, h - -try2: - TBZ $1, n, try1 - MOVHU.P 2(p), x3 - AND $255, x3, x1 - LSR $8, x3, x2 - - MUL prime5, x1 - ROR $64-11, h - EOR x1 @> 64-11, h, h - MUL prime1, h - - MUL prime5, x2 - ROR $64-11, h - EOR x2 @> 64-11, h, h - MUL prime1, h - -try1: - TBZ $0, n, finalize - MOVBU (p), x4 - - MUL prime5, x4 - ROR $64-11, h - EOR x4 @> 64-11, h, h - MUL prime1, h - -finalize: - EOR h >> 33, h - MUL prime2, h - EOR h >> 29, h - MUL prime3, h - EOR h >> 32, h - - MOVD h, ret+24(FP) - RET - -// func writeBlocks(d *Digest, b []byte) int -TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40 - LDP ·primes+0(SB), (prime1, prime2) - - // Load state. Assume v[1-4] are stored contiguously. - MOVD d+0(FP), digest - LDP 0(digest), (v1, v2) - LDP 16(digest), (v3, v4) - - LDP b_base+8(FP), (p, n) - - blockLoop() - - // Store updated state. - STP (v1, v2), 0(digest) - STP (v3, v4), 16(digest) - - BIC $31, n - MOVD n, ret+32(FP) - RET diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_asm.go b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_asm.go deleted file mode 100644 index d4221edf4..000000000 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_asm.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build (amd64 || arm64) && !appengine && gc && !purego && !noasm -// +build amd64 arm64 -// +build !appengine -// +build gc -// +build !purego -// +build !noasm - -package xxhash - -// Sum64 computes the 64-bit xxHash digest of b. -// -//go:noescape -func Sum64(b []byte) uint64 - -//go:noescape -func writeBlocks(s *Digest, b []byte) int diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_other.go b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_other.go deleted file mode 100644 index 0be16cefc..000000000 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_other.go +++ /dev/null @@ -1,76 +0,0 @@ -//go:build (!amd64 && !arm64) || appengine || !gc || purego || noasm -// +build !amd64,!arm64 appengine !gc purego noasm - -package xxhash - -// Sum64 computes the 64-bit xxHash digest of b. -func Sum64(b []byte) uint64 { - // A simpler version would be - // d := New() - // d.Write(b) - // return d.Sum64() - // but this is faster, particularly for small inputs. - - n := len(b) - var h uint64 - - if n >= 32 { - v1 := primes[0] + prime2 - v2 := prime2 - v3 := uint64(0) - v4 := -primes[0] - for len(b) >= 32 { - v1 = round(v1, u64(b[0:8:len(b)])) - v2 = round(v2, u64(b[8:16:len(b)])) - v3 = round(v3, u64(b[16:24:len(b)])) - v4 = round(v4, u64(b[24:32:len(b)])) - b = b[32:len(b):len(b)] - } - h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) - h = mergeRound(h, v1) - h = mergeRound(h, v2) - h = mergeRound(h, v3) - h = mergeRound(h, v4) - } else { - h = prime5 - } - - h += uint64(n) - - for ; len(b) >= 8; b = b[8:] { - k1 := round(0, u64(b[:8])) - h ^= k1 - h = rol27(h)*prime1 + prime4 - } - if len(b) >= 4 { - h ^= uint64(u32(b[:4])) * prime1 - h = rol23(h)*prime2 + prime3 - b = b[4:] - } - for ; len(b) > 0; b = b[1:] { - h ^= uint64(b[0]) * prime5 - h = rol11(h) * prime1 - } - - h ^= h >> 33 - h *= prime2 - h ^= h >> 29 - h *= prime3 - h ^= h >> 32 - - return h -} - -func writeBlocks(d *Digest, b []byte) int { - v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4 - n := len(b) - for len(b) >= 32 { - v1 = round(v1, u64(b[0:8:len(b)])) - v2 = round(v2, u64(b[8:16:len(b)])) - v3 = round(v3, u64(b[16:24:len(b)])) - v4 = round(v4, u64(b[24:32:len(b)])) - b = b[32:len(b):len(b)] - } - d.v1, d.v2, d.v3, d.v4 = v1, v2, v3, v4 - return n - len(b) -} diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_safe.go b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_safe.go deleted file mode 100644 index 6f3b0cb10..000000000 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_safe.go +++ /dev/null @@ -1,11 +0,0 @@ -package xxhash - -// Sum64String computes the 64-bit xxHash digest of s. -func Sum64String(s string) uint64 { - return Sum64([]byte(s)) -} - -// WriteString adds more data to d. It always returns len(s), nil. -func (d *Digest) WriteString(s string) (n int, err error) { - return d.Write([]byte(s)) -} diff --git a/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.go b/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.go deleted file mode 100644 index f41932b7a..000000000 --- a/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build amd64 && !appengine && !noasm && gc -// +build amd64,!appengine,!noasm,gc - -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. - -package zstd - -// matchLen returns how many bytes match in a and b -// -// It assumes that: -// -// len(a) <= len(b) and len(a) > 0 -// -//go:noescape -func matchLen(a []byte, b []byte) int diff --git a/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.s b/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.s deleted file mode 100644 index 9a7655c0f..000000000 --- a/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.s +++ /dev/null @@ -1,68 +0,0 @@ -// Copied from S2 implementation. - -//go:build !appengine && !noasm && gc && !noasm - -#include "textflag.h" - -// func matchLen(a []byte, b []byte) int -// Requires: BMI -TEXT ·matchLen(SB), NOSPLIT, $0-56 - MOVQ a_base+0(FP), AX - MOVQ b_base+24(FP), CX - MOVQ a_len+8(FP), DX - - // matchLen - XORL SI, SI - CMPL DX, $0x08 - JB matchlen_match4_standalone - -matchlen_loopback_standalone: - MOVQ (AX)(SI*1), BX - XORQ (CX)(SI*1), BX - TESTQ BX, BX - JZ matchlen_loop_standalone - -#ifdef GOAMD64_v3 - TZCNTQ BX, BX -#else - BSFQ BX, BX -#endif - SARQ $0x03, BX - LEAL (SI)(BX*1), SI - JMP gen_match_len_end - -matchlen_loop_standalone: - LEAL -8(DX), DX - LEAL 8(SI), SI - CMPL DX, $0x08 - JAE matchlen_loopback_standalone - -matchlen_match4_standalone: - CMPL DX, $0x04 - JB matchlen_match2_standalone - MOVL (AX)(SI*1), BX - CMPL (CX)(SI*1), BX - JNE matchlen_match2_standalone - LEAL -4(DX), DX - LEAL 4(SI), SI - -matchlen_match2_standalone: - CMPL DX, $0x02 - JB matchlen_match1_standalone - MOVW (AX)(SI*1), BX - CMPW (CX)(SI*1), BX - JNE matchlen_match1_standalone - LEAL -2(DX), DX - LEAL 2(SI), SI - -matchlen_match1_standalone: - CMPL DX, $0x01 - JB gen_match_len_end - MOVB (AX)(SI*1), BL - CMPB (CX)(SI*1), BL - JNE gen_match_len_end - INCL SI - -gen_match_len_end: - MOVQ SI, ret+48(FP) - RET diff --git a/vendor/github.com/klauspost/compress/zstd/matchlen_generic.go b/vendor/github.com/klauspost/compress/zstd/matchlen_generic.go deleted file mode 100644 index 57b9c31c0..000000000 --- a/vendor/github.com/klauspost/compress/zstd/matchlen_generic.go +++ /dev/null @@ -1,33 +0,0 @@ -//go:build !amd64 || appengine || !gc || noasm -// +build !amd64 appengine !gc noasm - -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. - -package zstd - -import ( - "encoding/binary" - "math/bits" -) - -// matchLen returns the maximum common prefix length of a and b. -// a must be the shortest of the two. -func matchLen(a, b []byte) (n int) { - for ; len(a) >= 8 && len(b) >= 8; a, b = a[8:], b[8:] { - diff := binary.LittleEndian.Uint64(a) ^ binary.LittleEndian.Uint64(b) - if diff != 0 { - return n + bits.TrailingZeros64(diff)>>3 - } - n += 8 - } - - for i := range a { - if a[i] != b[i] { - break - } - n++ - } - return n - -} diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec.go b/vendor/github.com/klauspost/compress/zstd/seqdec.go deleted file mode 100644 index d7fe6d82d..000000000 --- a/vendor/github.com/klauspost/compress/zstd/seqdec.go +++ /dev/null @@ -1,503 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "errors" - "fmt" - "io" -) - -type seq struct { - litLen uint32 - matchLen uint32 - offset uint32 - - // Codes are stored here for the encoder - // so they only have to be looked up once. - llCode, mlCode, ofCode uint8 -} - -type seqVals struct { - ll, ml, mo int -} - -func (s seq) String() string { - if s.offset <= 3 { - if s.offset == 0 { - return fmt.Sprint("litLen:", s.litLen, ", matchLen:", s.matchLen+zstdMinMatch, ", offset: INVALID (0)") - } - return fmt.Sprint("litLen:", s.litLen, ", matchLen:", s.matchLen+zstdMinMatch, ", offset:", s.offset, " (repeat)") - } - return fmt.Sprint("litLen:", s.litLen, ", matchLen:", s.matchLen+zstdMinMatch, ", offset:", s.offset-3, " (new)") -} - -type seqCompMode uint8 - -const ( - compModePredefined seqCompMode = iota - compModeRLE - compModeFSE - compModeRepeat -) - -type sequenceDec struct { - // decoder keeps track of the current state and updates it from the bitstream. - fse *fseDecoder - state fseState - repeat bool -} - -// init the state of the decoder with input from stream. -func (s *sequenceDec) init(br *bitReader) error { - if s.fse == nil { - return errors.New("sequence decoder not defined") - } - s.state.init(br, s.fse.actualTableLog, s.fse.dt[:1< cap(s.out) { - addBytes := s.seqSize + len(s.out) - s.out = append(s.out, make([]byte, addBytes)...) - s.out = s.out[:len(s.out)-addBytes] - } - - if debugDecoder { - printf("Execute %d seqs with hist %d, dict %d, literals: %d into %d bytes\n", len(seqs), len(hist), len(s.dict), len(s.literals), s.seqSize) - } - - var t = len(s.out) - out := s.out[:t+s.seqSize] - - for _, seq := range seqs { - // Add literals - copy(out[t:], s.literals[:seq.ll]) - t += seq.ll - s.literals = s.literals[seq.ll:] - - // Copy from dictionary... - if seq.mo > t+len(hist) || seq.mo > s.windowSize { - if len(s.dict) == 0 { - return fmt.Errorf("match offset (%d) bigger than current history (%d)", seq.mo, t+len(hist)) - } - - // we may be in dictionary. - dictO := len(s.dict) - (seq.mo - (t + len(hist))) - if dictO < 0 || dictO >= len(s.dict) { - return fmt.Errorf("match offset (%d) bigger than current history+dict (%d)", seq.mo, t+len(hist)+len(s.dict)) - } - end := dictO + seq.ml - if end > len(s.dict) { - n := len(s.dict) - dictO - copy(out[t:], s.dict[dictO:]) - t += n - seq.ml -= n - } else { - copy(out[t:], s.dict[dictO:end]) - t += end - dictO - continue - } - } - - // Copy from history. - if v := seq.mo - t; v > 0 { - // v is the start position in history from end. - start := len(hist) - v - if seq.ml > v { - // Some goes into current block. - // Copy remainder of history - copy(out[t:], hist[start:]) - t += v - seq.ml -= v - } else { - copy(out[t:], hist[start:start+seq.ml]) - t += seq.ml - continue - } - } - // We must be in current buffer now - if seq.ml > 0 { - start := t - seq.mo - if seq.ml <= t-start { - // No overlap - copy(out[t:], out[start:start+seq.ml]) - t += seq.ml - continue - } else { - // Overlapping copy - // Extend destination slice and copy one byte at the time. - src := out[start : start+seq.ml] - dst := out[t:] - dst = dst[:len(src)] - t += len(src) - // Destination is the space we just added. - for i := range src { - dst[i] = src[i] - } - } - } - } - - // Add final literals - copy(out[t:], s.literals) - if debugDecoder { - t += len(s.literals) - if t != len(out) { - panic(fmt.Errorf("length mismatch, want %d, got %d, ss: %d", len(out), t, s.seqSize)) - } - } - s.out = out - - return nil -} - -// decode sequences from the stream with the provided history. -func (s *sequenceDecs) decodeSync(hist []byte) error { - supported, err := s.decodeSyncSimple(hist) - if supported { - return err - } - - br := s.br - seqs := s.nSeqs - startSize := len(s.out) - // Grab full sizes tables, to avoid bounds checks. - llTable, mlTable, ofTable := s.litLengths.fse.dt[:maxTablesize], s.matchLengths.fse.dt[:maxTablesize], s.offsets.fse.dt[:maxTablesize] - llState, mlState, ofState := s.litLengths.state.state, s.matchLengths.state.state, s.offsets.state.state - out := s.out - maxBlockSize := maxCompressedBlockSize - if s.windowSize < maxBlockSize { - maxBlockSize = s.windowSize - } - - if debugDecoder { - println("decodeSync: decoding", seqs, "sequences", br.remain(), "bits remain on stream") - } - for i := seqs - 1; i >= 0; i-- { - if br.overread() { - printf("reading sequence %d, exceeded available data. Overread by %d\n", seqs-i, -br.remain()) - return io.ErrUnexpectedEOF - } - var ll, mo, ml int - if len(br.in) > 4+((maxOffsetBits+16+16)>>3) { - // inlined function: - // ll, mo, ml = s.nextFast(br, llState, mlState, ofState) - - // Final will not read from stream. - var llB, mlB, moB uint8 - ll, llB = llState.final() - ml, mlB = mlState.final() - mo, moB = ofState.final() - - // extra bits are stored in reverse order. - br.fillFast() - mo += br.getBits(moB) - if s.maxBits > 32 { - br.fillFast() - } - ml += br.getBits(mlB) - ll += br.getBits(llB) - - if moB > 1 { - s.prevOffset[2] = s.prevOffset[1] - s.prevOffset[1] = s.prevOffset[0] - s.prevOffset[0] = mo - } else { - // mo = s.adjustOffset(mo, ll, moB) - // Inlined for rather big speedup - if ll == 0 { - // There is an exception though, when current sequence's literals_length = 0. - // In this case, repeated offsets are shifted by one, so an offset_value of 1 means Repeated_Offset2, - // an offset_value of 2 means Repeated_Offset3, and an offset_value of 3 means Repeated_Offset1 - 1_byte. - mo++ - } - - if mo == 0 { - mo = s.prevOffset[0] - } else { - var temp int - if mo == 3 { - temp = s.prevOffset[0] - 1 - } else { - temp = s.prevOffset[mo] - } - - if temp == 0 { - // 0 is not valid; input is corrupted; force offset to 1 - println("WARNING: temp was 0") - temp = 1 - } - - if mo != 1 { - s.prevOffset[2] = s.prevOffset[1] - } - s.prevOffset[1] = s.prevOffset[0] - s.prevOffset[0] = temp - mo = temp - } - } - br.fillFast() - } else { - ll, mo, ml = s.next(br, llState, mlState, ofState) - br.fill() - } - - if debugSequences { - println("Seq", seqs-i-1, "Litlen:", ll, "mo:", mo, "(abs) ml:", ml) - } - - if ll > len(s.literals) { - return fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", ll, len(s.literals)) - } - size := ll + ml + len(out) - if size-startSize > maxBlockSize { - return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) - } - if size > cap(out) { - // Not enough size, which can happen under high volume block streaming conditions - // but could be if destination slice is too small for sync operations. - // over-allocating here can create a large amount of GC pressure so we try to keep - // it as contained as possible - used := len(out) - startSize - addBytes := 256 + ll + ml + used>>2 - // Clamp to max block size. - if used+addBytes > maxBlockSize { - addBytes = maxBlockSize - used - } - out = append(out, make([]byte, addBytes)...) - out = out[:len(out)-addBytes] - } - if ml > maxMatchLen { - return fmt.Errorf("match len (%d) bigger than max allowed length", ml) - } - - // Add literals - out = append(out, s.literals[:ll]...) - s.literals = s.literals[ll:] - - if mo == 0 && ml > 0 { - return fmt.Errorf("zero matchoff and matchlen (%d) > 0", ml) - } - - if mo > len(out)+len(hist) || mo > s.windowSize { - if len(s.dict) == 0 { - return fmt.Errorf("match offset (%d) bigger than current history (%d)", mo, len(out)+len(hist)-startSize) - } - - // we may be in dictionary. - dictO := len(s.dict) - (mo - (len(out) + len(hist))) - if dictO < 0 || dictO >= len(s.dict) { - return fmt.Errorf("match offset (%d) bigger than current history (%d)", mo, len(out)+len(hist)-startSize) - } - end := dictO + ml - if end > len(s.dict) { - out = append(out, s.dict[dictO:]...) - ml -= len(s.dict) - dictO - } else { - out = append(out, s.dict[dictO:end]...) - mo = 0 - ml = 0 - } - } - - // Copy from history. - // TODO: Blocks without history could be made to ignore this completely. - if v := mo - len(out); v > 0 { - // v is the start position in history from end. - start := len(hist) - v - if ml > v { - // Some goes into current block. - // Copy remainder of history - out = append(out, hist[start:]...) - ml -= v - } else { - out = append(out, hist[start:start+ml]...) - ml = 0 - } - } - // We must be in current buffer now - if ml > 0 { - start := len(out) - mo - if ml <= len(out)-start { - // No overlap - out = append(out, out[start:start+ml]...) - } else { - // Overlapping copy - // Extend destination slice and copy one byte at the time. - out = out[:len(out)+ml] - src := out[start : start+ml] - // Destination is the space we just added. - dst := out[len(out)-ml:] - dst = dst[:len(src)] - for i := range src { - dst[i] = src[i] - } - } - } - if i == 0 { - // This is the last sequence, so we shouldn't update state. - break - } - - // Manually inlined, ~ 5-20% faster - // Update all 3 states at once. Approx 20% faster. - nBits := llState.nbBits() + mlState.nbBits() + ofState.nbBits() - if nBits == 0 { - llState = llTable[llState.newState()&maxTableMask] - mlState = mlTable[mlState.newState()&maxTableMask] - ofState = ofTable[ofState.newState()&maxTableMask] - } else { - bits := br.get32BitsFast(nBits) - - lowBits := uint16(bits >> ((ofState.nbBits() + mlState.nbBits()) & 31)) - llState = llTable[(llState.newState()+lowBits)&maxTableMask] - - lowBits = uint16(bits >> (ofState.nbBits() & 31)) - lowBits &= bitMask[mlState.nbBits()&15] - mlState = mlTable[(mlState.newState()+lowBits)&maxTableMask] - - lowBits = uint16(bits) & bitMask[ofState.nbBits()&15] - ofState = ofTable[(ofState.newState()+lowBits)&maxTableMask] - } - } - - if size := len(s.literals) + len(out) - startSize; size > maxBlockSize { - return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) - } - - // Add final literals - s.out = append(out, s.literals...) - return br.close() -} - -var bitMask [16]uint16 - -func init() { - for i := range bitMask[:] { - bitMask[i] = uint16((1 << uint(i)) - 1) - } -} - -func (s *sequenceDecs) next(br *bitReader, llState, mlState, ofState decSymbol) (ll, mo, ml int) { - // Final will not read from stream. - ll, llB := llState.final() - ml, mlB := mlState.final() - mo, moB := ofState.final() - - // extra bits are stored in reverse order. - br.fill() - mo += br.getBits(moB) - if s.maxBits > 32 { - br.fill() - } - // matchlength+literal length, max 32 bits - ml += br.getBits(mlB) - ll += br.getBits(llB) - mo = s.adjustOffset(mo, ll, moB) - return -} - -func (s *sequenceDecs) adjustOffset(offset, litLen int, offsetB uint8) int { - if offsetB > 1 { - s.prevOffset[2] = s.prevOffset[1] - s.prevOffset[1] = s.prevOffset[0] - s.prevOffset[0] = offset - return offset - } - - if litLen == 0 { - // There is an exception though, when current sequence's literals_length = 0. - // In this case, repeated offsets are shifted by one, so an offset_value of 1 means Repeated_Offset2, - // an offset_value of 2 means Repeated_Offset3, and an offset_value of 3 means Repeated_Offset1 - 1_byte. - offset++ - } - - if offset == 0 { - return s.prevOffset[0] - } - var temp int - if offset == 3 { - temp = s.prevOffset[0] - 1 - } else { - temp = s.prevOffset[offset] - } - - if temp == 0 { - // 0 is not valid; input is corrupted; force offset to 1 - println("temp was 0") - temp = 1 - } - - if offset != 1 { - s.prevOffset[2] = s.prevOffset[1] - } - s.prevOffset[1] = s.prevOffset[0] - s.prevOffset[0] = temp - return temp -} diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go b/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go deleted file mode 100644 index 8adabd828..000000000 --- a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go +++ /dev/null @@ -1,394 +0,0 @@ -//go:build amd64 && !appengine && !noasm && gc -// +build amd64,!appengine,!noasm,gc - -package zstd - -import ( - "fmt" - "io" - - "github.com/klauspost/compress/internal/cpuinfo" -) - -type decodeSyncAsmContext struct { - llTable []decSymbol - mlTable []decSymbol - ofTable []decSymbol - llState uint64 - mlState uint64 - ofState uint64 - iteration int - litRemain int - out []byte - outPosition int - literals []byte - litPosition int - history []byte - windowSize int - ll int // set on error (not for all errors, please refer to _generate/gen.go) - ml int // set on error (not for all errors, please refer to _generate/gen.go) - mo int // set on error (not for all errors, please refer to _generate/gen.go) -} - -// sequenceDecs_decodeSync_amd64 implements the main loop of sequenceDecs.decodeSync in x86 asm. -// -// Please refer to seqdec_generic.go for the reference implementation. -// -//go:noescape -func sequenceDecs_decodeSync_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int - -// sequenceDecs_decodeSync_bmi2 implements the main loop of sequenceDecs.decodeSync in x86 asm with BMI2 extensions. -// -//go:noescape -func sequenceDecs_decodeSync_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int - -// sequenceDecs_decodeSync_safe_amd64 does the same as above, but does not write more than output buffer. -// -//go:noescape -func sequenceDecs_decodeSync_safe_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int - -// sequenceDecs_decodeSync_safe_bmi2 does the same as above, but does not write more than output buffer. -// -//go:noescape -func sequenceDecs_decodeSync_safe_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int - -// decode sequences from the stream with the provided history but without a dictionary. -func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) { - if len(s.dict) > 0 { - return false, nil - } - if s.maxSyncLen == 0 && cap(s.out)-len(s.out) < maxCompressedBlockSize { - return false, nil - } - - // FIXME: Using unsafe memory copies leads to rare, random crashes - // with fuzz testing. It is therefore disabled for now. - const useSafe = true - /* - useSafe := false - if s.maxSyncLen == 0 && cap(s.out)-len(s.out) < maxCompressedBlockSizeAlloc { - useSafe = true - } - if s.maxSyncLen > 0 && cap(s.out)-len(s.out)-compressedBlockOverAlloc < int(s.maxSyncLen) { - useSafe = true - } - if cap(s.literals) < len(s.literals)+compressedBlockOverAlloc { - useSafe = true - } - */ - - br := s.br - - maxBlockSize := maxCompressedBlockSize - if s.windowSize < maxBlockSize { - maxBlockSize = s.windowSize - } - - ctx := decodeSyncAsmContext{ - llTable: s.litLengths.fse.dt[:maxTablesize], - mlTable: s.matchLengths.fse.dt[:maxTablesize], - ofTable: s.offsets.fse.dt[:maxTablesize], - llState: uint64(s.litLengths.state.state), - mlState: uint64(s.matchLengths.state.state), - ofState: uint64(s.offsets.state.state), - iteration: s.nSeqs - 1, - litRemain: len(s.literals), - out: s.out, - outPosition: len(s.out), - literals: s.literals, - windowSize: s.windowSize, - history: hist, - } - - s.seqSize = 0 - startSize := len(s.out) - - var errCode int - if cpuinfo.HasBMI2() { - if useSafe { - errCode = sequenceDecs_decodeSync_safe_bmi2(s, br, &ctx) - } else { - errCode = sequenceDecs_decodeSync_bmi2(s, br, &ctx) - } - } else { - if useSafe { - errCode = sequenceDecs_decodeSync_safe_amd64(s, br, &ctx) - } else { - errCode = sequenceDecs_decodeSync_amd64(s, br, &ctx) - } - } - switch errCode { - case noError: - break - - case errorMatchLenOfsMismatch: - return true, fmt.Errorf("zero matchoff and matchlen (%d) > 0", ctx.ml) - - case errorMatchLenTooBig: - return true, fmt.Errorf("match len (%d) bigger than max allowed length", ctx.ml) - - case errorMatchOffTooBig: - return true, fmt.Errorf("match offset (%d) bigger than current history (%d)", - ctx.mo, ctx.outPosition+len(hist)-startSize) - - case errorNotEnoughLiterals: - return true, fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", - ctx.ll, ctx.litRemain+ctx.ll) - - case errorOverread: - return true, io.ErrUnexpectedEOF - - case errorNotEnoughSpace: - size := ctx.outPosition + ctx.ll + ctx.ml - if debugDecoder { - println("msl:", s.maxSyncLen, "cap", cap(s.out), "bef:", startSize, "sz:", size-startSize, "mbs:", maxBlockSize, "outsz:", cap(s.out)-startSize) - } - return true, fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) - - default: - return true, fmt.Errorf("sequenceDecs_decode returned erronous code %d", errCode) - } - - s.seqSize += ctx.litRemain - if s.seqSize > maxBlockSize { - return true, fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) - } - err := br.close() - if err != nil { - printf("Closing sequences: %v, %+v\n", err, *br) - return true, err - } - - s.literals = s.literals[ctx.litPosition:] - t := ctx.outPosition - s.out = s.out[:t] - - // Add final literals - s.out = append(s.out, s.literals...) - if debugDecoder { - t += len(s.literals) - if t != len(s.out) { - panic(fmt.Errorf("length mismatch, want %d, got %d", len(s.out), t)) - } - } - - return true, nil -} - -// -------------------------------------------------------------------------------- - -type decodeAsmContext struct { - llTable []decSymbol - mlTable []decSymbol - ofTable []decSymbol - llState uint64 - mlState uint64 - ofState uint64 - iteration int - seqs []seqVals - litRemain int -} - -const noError = 0 - -// error reported when mo == 0 && ml > 0 -const errorMatchLenOfsMismatch = 1 - -// error reported when ml > maxMatchLen -const errorMatchLenTooBig = 2 - -// error reported when mo > available history or mo > s.windowSize -const errorMatchOffTooBig = 3 - -// error reported when the sum of literal lengths exeeceds the literal buffer size -const errorNotEnoughLiterals = 4 - -// error reported when capacity of `out` is too small -const errorNotEnoughSpace = 5 - -// error reported when bits are overread. -const errorOverread = 6 - -// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm. -// -// Please refer to seqdec_generic.go for the reference implementation. -// -//go:noescape -func sequenceDecs_decode_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int - -// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm. -// -// Please refer to seqdec_generic.go for the reference implementation. -// -//go:noescape -func sequenceDecs_decode_56_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int - -// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm with BMI2 extensions. -// -//go:noescape -func sequenceDecs_decode_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int - -// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm with BMI2 extensions. -// -//go:noescape -func sequenceDecs_decode_56_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int - -// decode sequences from the stream without the provided history. -func (s *sequenceDecs) decode(seqs []seqVals) error { - br := s.br - - maxBlockSize := maxCompressedBlockSize - if s.windowSize < maxBlockSize { - maxBlockSize = s.windowSize - } - - ctx := decodeAsmContext{ - llTable: s.litLengths.fse.dt[:maxTablesize], - mlTable: s.matchLengths.fse.dt[:maxTablesize], - ofTable: s.offsets.fse.dt[:maxTablesize], - llState: uint64(s.litLengths.state.state), - mlState: uint64(s.matchLengths.state.state), - ofState: uint64(s.offsets.state.state), - seqs: seqs, - iteration: len(seqs) - 1, - litRemain: len(s.literals), - } - - if debugDecoder { - println("decode: decoding", len(seqs), "sequences", br.remain(), "bits remain on stream") - } - - s.seqSize = 0 - lte56bits := s.maxBits+s.offsets.fse.actualTableLog+s.matchLengths.fse.actualTableLog+s.litLengths.fse.actualTableLog <= 56 - var errCode int - if cpuinfo.HasBMI2() { - if lte56bits { - errCode = sequenceDecs_decode_56_bmi2(s, br, &ctx) - } else { - errCode = sequenceDecs_decode_bmi2(s, br, &ctx) - } - } else { - if lte56bits { - errCode = sequenceDecs_decode_56_amd64(s, br, &ctx) - } else { - errCode = sequenceDecs_decode_amd64(s, br, &ctx) - } - } - if errCode != 0 { - i := len(seqs) - ctx.iteration - 1 - switch errCode { - case errorMatchLenOfsMismatch: - ml := ctx.seqs[i].ml - return fmt.Errorf("zero matchoff and matchlen (%d) > 0", ml) - - case errorMatchLenTooBig: - ml := ctx.seqs[i].ml - return fmt.Errorf("match len (%d) bigger than max allowed length", ml) - - case errorNotEnoughLiterals: - ll := ctx.seqs[i].ll - return fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", ll, ctx.litRemain+ll) - case errorOverread: - return io.ErrUnexpectedEOF - } - - return fmt.Errorf("sequenceDecs_decode_amd64 returned erronous code %d", errCode) - } - - if ctx.litRemain < 0 { - return fmt.Errorf("literal count is too big: total available %d, total requested %d", - len(s.literals), len(s.literals)-ctx.litRemain) - } - - s.seqSize += ctx.litRemain - if s.seqSize > maxBlockSize { - return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) - } - if debugDecoder { - println("decode: ", br.remain(), "bits remain on stream. code:", errCode) - } - err := br.close() - if err != nil { - printf("Closing sequences: %v, %+v\n", err, *br) - } - return err -} - -// -------------------------------------------------------------------------------- - -type executeAsmContext struct { - seqs []seqVals - seqIndex int - out []byte - history []byte - literals []byte - outPosition int - litPosition int - windowSize int -} - -// sequenceDecs_executeSimple_amd64 implements the main loop of sequenceDecs.executeSimple in x86 asm. -// -// Returns false if a match offset is too big. -// -// Please refer to seqdec_generic.go for the reference implementation. -// -//go:noescape -func sequenceDecs_executeSimple_amd64(ctx *executeAsmContext) bool - -// Same as above, but with safe memcopies -// -//go:noescape -func sequenceDecs_executeSimple_safe_amd64(ctx *executeAsmContext) bool - -// executeSimple handles cases when dictionary is not used. -func (s *sequenceDecs) executeSimple(seqs []seqVals, hist []byte) error { - // Ensure we have enough output size... - if len(s.out)+s.seqSize+compressedBlockOverAlloc > cap(s.out) { - addBytes := s.seqSize + len(s.out) + compressedBlockOverAlloc - s.out = append(s.out, make([]byte, addBytes)...) - s.out = s.out[:len(s.out)-addBytes] - } - - if debugDecoder { - printf("Execute %d seqs with literals: %d into %d bytes\n", len(seqs), len(s.literals), s.seqSize) - } - - var t = len(s.out) - out := s.out[:t+s.seqSize] - - ctx := executeAsmContext{ - seqs: seqs, - seqIndex: 0, - out: out, - history: hist, - outPosition: t, - litPosition: 0, - literals: s.literals, - windowSize: s.windowSize, - } - var ok bool - if cap(s.literals) < len(s.literals)+compressedBlockOverAlloc { - ok = sequenceDecs_executeSimple_safe_amd64(&ctx) - } else { - ok = sequenceDecs_executeSimple_amd64(&ctx) - } - if !ok { - return fmt.Errorf("match offset (%d) bigger than current history (%d)", - seqs[ctx.seqIndex].mo, ctx.outPosition+len(hist)) - } - s.literals = s.literals[ctx.litPosition:] - t = ctx.outPosition - - // Add final literals - copy(out[t:], s.literals) - if debugDecoder { - t += len(s.literals) - if t != len(out) { - panic(fmt.Errorf("length mismatch, want %d, got %d, ss: %d", len(out), t, s.seqSize)) - } - } - s.out = out - - return nil -} diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s b/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s deleted file mode 100644 index 974b99725..000000000 --- a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s +++ /dev/null @@ -1,4175 +0,0 @@ -// Code generated by command: go run gen.go -out ../seqdec_amd64.s -pkg=zstd. DO NOT EDIT. - -//go:build !appengine && !noasm && gc && !noasm - -// func sequenceDecs_decode_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int -// Requires: CMOV -TEXT ·sequenceDecs_decode_amd64(SB), $8-32 - MOVQ br+8(FP), CX - MOVQ 24(CX), DX - MOVBQZX 32(CX), BX - MOVQ (CX), AX - MOVQ 8(CX), SI - ADDQ SI, AX - MOVQ AX, (SP) - MOVQ ctx+16(FP), AX - MOVQ 72(AX), DI - MOVQ 80(AX), R8 - MOVQ 88(AX), R9 - MOVQ 104(AX), R10 - MOVQ s+0(FP), AX - MOVQ 144(AX), R11 - MOVQ 152(AX), R12 - MOVQ 160(AX), R13 - -sequenceDecs_decode_amd64_main_loop: - MOVQ (SP), R14 - - // Fill bitreader to have enough for the offset and match length. - CMPQ SI, $0x08 - JL sequenceDecs_decode_amd64_fill_byte_by_byte - MOVQ BX, AX - SHRQ $0x03, AX - SUBQ AX, R14 - MOVQ (R14), DX - SUBQ AX, SI - ANDQ $0x07, BX - JMP sequenceDecs_decode_amd64_fill_end - -sequenceDecs_decode_amd64_fill_byte_by_byte: - CMPQ SI, $0x00 - JLE sequenceDecs_decode_amd64_fill_check_overread - CMPQ BX, $0x07 - JLE sequenceDecs_decode_amd64_fill_end - SHLQ $0x08, DX - SUBQ $0x01, R14 - SUBQ $0x01, SI - SUBQ $0x08, BX - MOVBQZX (R14), AX - ORQ AX, DX - JMP sequenceDecs_decode_amd64_fill_byte_by_byte - -sequenceDecs_decode_amd64_fill_check_overread: - CMPQ BX, $0x40 - JA error_overread - -sequenceDecs_decode_amd64_fill_end: - // Update offset - MOVQ R9, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_amd64_of_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_amd64_of_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_amd64_of_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_amd64_of_update_zero: - MOVQ AX, 16(R10) - - // Update match length - MOVQ R8, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_amd64_ml_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_amd64_ml_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_amd64_ml_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_amd64_ml_update_zero: - MOVQ AX, 8(R10) - - // Fill bitreader to have enough for the remaining - CMPQ SI, $0x08 - JL sequenceDecs_decode_amd64_fill_2_byte_by_byte - MOVQ BX, AX - SHRQ $0x03, AX - SUBQ AX, R14 - MOVQ (R14), DX - SUBQ AX, SI - ANDQ $0x07, BX - JMP sequenceDecs_decode_amd64_fill_2_end - -sequenceDecs_decode_amd64_fill_2_byte_by_byte: - CMPQ SI, $0x00 - JLE sequenceDecs_decode_amd64_fill_2_check_overread - CMPQ BX, $0x07 - JLE sequenceDecs_decode_amd64_fill_2_end - SHLQ $0x08, DX - SUBQ $0x01, R14 - SUBQ $0x01, SI - SUBQ $0x08, BX - MOVBQZX (R14), AX - ORQ AX, DX - JMP sequenceDecs_decode_amd64_fill_2_byte_by_byte - -sequenceDecs_decode_amd64_fill_2_check_overread: - CMPQ BX, $0x40 - JA error_overread - -sequenceDecs_decode_amd64_fill_2_end: - // Update literal length - MOVQ DI, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_amd64_ll_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_amd64_ll_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_amd64_ll_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_amd64_ll_update_zero: - MOVQ AX, (R10) - - // Fill bitreader for state updates - MOVQ R14, (SP) - MOVQ R9, AX - SHRQ $0x08, AX - MOVBQZX AL, AX - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 - JZ sequenceDecs_decode_amd64_skip_update - - // Update Literal Length State - MOVBQZX DI, R14 - SHRQ $0x10, DI - MOVWQZX DI, DI - LEAQ (BX)(R14*1), CX - MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 - ADDQ R15, DI - - // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX - MOVQ (CX)(DI*8), DI - - // Update Match Length State - MOVBQZX R8, R14 - SHRQ $0x10, R8 - MOVWQZX R8, R8 - LEAQ (BX)(R14*1), CX - MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 - ADDQ R15, R8 - - // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX - MOVQ (CX)(R8*8), R8 - - // Update Offset State - MOVBQZX R9, R14 - SHRQ $0x10, R9 - MOVWQZX R9, R9 - LEAQ (BX)(R14*1), CX - MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 - ADDQ R15, R9 - - // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX - MOVQ (CX)(R9*8), R9 - -sequenceDecs_decode_amd64_skip_update: - // Adjust offset - MOVQ 16(R10), CX - CMPQ AX, $0x01 - JBE sequenceDecs_decode_amd64_adjust_offsetB_1_or_0 - MOVQ R12, R13 - MOVQ R11, R12 - MOVQ CX, R11 - JMP sequenceDecs_decode_amd64_after_adjust - -sequenceDecs_decode_amd64_adjust_offsetB_1_or_0: - CMPQ (R10), $0x00000000 - JNE sequenceDecs_decode_amd64_adjust_offset_maybezero - INCQ CX - JMP sequenceDecs_decode_amd64_adjust_offset_nonzero - -sequenceDecs_decode_amd64_adjust_offset_maybezero: - TESTQ CX, CX - JNZ sequenceDecs_decode_amd64_adjust_offset_nonzero - MOVQ R11, CX - JMP sequenceDecs_decode_amd64_after_adjust - -sequenceDecs_decode_amd64_adjust_offset_nonzero: - CMPQ CX, $0x01 - JB sequenceDecs_decode_amd64_adjust_zero - JEQ sequenceDecs_decode_amd64_adjust_one - CMPQ CX, $0x02 - JA sequenceDecs_decode_amd64_adjust_three - JMP sequenceDecs_decode_amd64_adjust_two - -sequenceDecs_decode_amd64_adjust_zero: - MOVQ R11, AX - JMP sequenceDecs_decode_amd64_adjust_test_temp_valid - -sequenceDecs_decode_amd64_adjust_one: - MOVQ R12, AX - JMP sequenceDecs_decode_amd64_adjust_test_temp_valid - -sequenceDecs_decode_amd64_adjust_two: - MOVQ R13, AX - JMP sequenceDecs_decode_amd64_adjust_test_temp_valid - -sequenceDecs_decode_amd64_adjust_three: - LEAQ -1(R11), AX - -sequenceDecs_decode_amd64_adjust_test_temp_valid: - TESTQ AX, AX - JNZ sequenceDecs_decode_amd64_adjust_temp_valid - MOVQ $0x00000001, AX - -sequenceDecs_decode_amd64_adjust_temp_valid: - CMPQ CX, $0x01 - CMOVQNE R12, R13 - MOVQ R11, R12 - MOVQ AX, R11 - MOVQ AX, CX - -sequenceDecs_decode_amd64_after_adjust: - MOVQ CX, 16(R10) - - // Check values - MOVQ 8(R10), AX - MOVQ (R10), R14 - LEAQ (AX)(R14*1), R15 - MOVQ s+0(FP), BP - ADDQ R15, 256(BP) - MOVQ ctx+16(FP), R15 - SUBQ R14, 128(R15) - JS error_not_enough_literals - CMPQ AX, $0x00020002 - JA sequenceDecs_decode_amd64_error_match_len_too_big - TESTQ CX, CX - JNZ sequenceDecs_decode_amd64_match_len_ofs_ok - TESTQ AX, AX - JNZ sequenceDecs_decode_amd64_error_match_len_ofs_mismatch - -sequenceDecs_decode_amd64_match_len_ofs_ok: - ADDQ $0x18, R10 - MOVQ ctx+16(FP), AX - DECQ 96(AX) - JNS sequenceDecs_decode_amd64_main_loop - MOVQ s+0(FP), AX - MOVQ R11, 144(AX) - MOVQ R12, 152(AX) - MOVQ R13, 160(AX) - MOVQ br+8(FP), AX - MOVQ DX, 24(AX) - MOVB BL, 32(AX) - MOVQ SI, 8(AX) - - // Return success - MOVQ $0x00000000, ret+24(FP) - RET - - // Return with match length error -sequenceDecs_decode_amd64_error_match_len_ofs_mismatch: - MOVQ $0x00000001, ret+24(FP) - RET - - // Return with match too long error -sequenceDecs_decode_amd64_error_match_len_too_big: - MOVQ $0x00000002, ret+24(FP) - RET - - // Return with match offset too long error - MOVQ $0x00000003, ret+24(FP) - RET - - // Return with not enough literals error -error_not_enough_literals: - MOVQ $0x00000004, ret+24(FP) - RET - - // Return with overread error -error_overread: - MOVQ $0x00000006, ret+24(FP) - RET - -// func sequenceDecs_decode_56_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int -// Requires: CMOV -TEXT ·sequenceDecs_decode_56_amd64(SB), $8-32 - MOVQ br+8(FP), CX - MOVQ 24(CX), DX - MOVBQZX 32(CX), BX - MOVQ (CX), AX - MOVQ 8(CX), SI - ADDQ SI, AX - MOVQ AX, (SP) - MOVQ ctx+16(FP), AX - MOVQ 72(AX), DI - MOVQ 80(AX), R8 - MOVQ 88(AX), R9 - MOVQ 104(AX), R10 - MOVQ s+0(FP), AX - MOVQ 144(AX), R11 - MOVQ 152(AX), R12 - MOVQ 160(AX), R13 - -sequenceDecs_decode_56_amd64_main_loop: - MOVQ (SP), R14 - - // Fill bitreader to have enough for the offset and match length. - CMPQ SI, $0x08 - JL sequenceDecs_decode_56_amd64_fill_byte_by_byte - MOVQ BX, AX - SHRQ $0x03, AX - SUBQ AX, R14 - MOVQ (R14), DX - SUBQ AX, SI - ANDQ $0x07, BX - JMP sequenceDecs_decode_56_amd64_fill_end - -sequenceDecs_decode_56_amd64_fill_byte_by_byte: - CMPQ SI, $0x00 - JLE sequenceDecs_decode_56_amd64_fill_check_overread - CMPQ BX, $0x07 - JLE sequenceDecs_decode_56_amd64_fill_end - SHLQ $0x08, DX - SUBQ $0x01, R14 - SUBQ $0x01, SI - SUBQ $0x08, BX - MOVBQZX (R14), AX - ORQ AX, DX - JMP sequenceDecs_decode_56_amd64_fill_byte_by_byte - -sequenceDecs_decode_56_amd64_fill_check_overread: - CMPQ BX, $0x40 - JA error_overread - -sequenceDecs_decode_56_amd64_fill_end: - // Update offset - MOVQ R9, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_56_amd64_of_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_56_amd64_of_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_56_amd64_of_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_56_amd64_of_update_zero: - MOVQ AX, 16(R10) - - // Update match length - MOVQ R8, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_56_amd64_ml_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_56_amd64_ml_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_56_amd64_ml_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_56_amd64_ml_update_zero: - MOVQ AX, 8(R10) - - // Update literal length - MOVQ DI, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_56_amd64_ll_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_56_amd64_ll_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_56_amd64_ll_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_56_amd64_ll_update_zero: - MOVQ AX, (R10) - - // Fill bitreader for state updates - MOVQ R14, (SP) - MOVQ R9, AX - SHRQ $0x08, AX - MOVBQZX AL, AX - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 - JZ sequenceDecs_decode_56_amd64_skip_update - - // Update Literal Length State - MOVBQZX DI, R14 - SHRQ $0x10, DI - MOVWQZX DI, DI - LEAQ (BX)(R14*1), CX - MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 - ADDQ R15, DI - - // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX - MOVQ (CX)(DI*8), DI - - // Update Match Length State - MOVBQZX R8, R14 - SHRQ $0x10, R8 - MOVWQZX R8, R8 - LEAQ (BX)(R14*1), CX - MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 - ADDQ R15, R8 - - // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX - MOVQ (CX)(R8*8), R8 - - // Update Offset State - MOVBQZX R9, R14 - SHRQ $0x10, R9 - MOVWQZX R9, R9 - LEAQ (BX)(R14*1), CX - MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 - ADDQ R15, R9 - - // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX - MOVQ (CX)(R9*8), R9 - -sequenceDecs_decode_56_amd64_skip_update: - // Adjust offset - MOVQ 16(R10), CX - CMPQ AX, $0x01 - JBE sequenceDecs_decode_56_amd64_adjust_offsetB_1_or_0 - MOVQ R12, R13 - MOVQ R11, R12 - MOVQ CX, R11 - JMP sequenceDecs_decode_56_amd64_after_adjust - -sequenceDecs_decode_56_amd64_adjust_offsetB_1_or_0: - CMPQ (R10), $0x00000000 - JNE sequenceDecs_decode_56_amd64_adjust_offset_maybezero - INCQ CX - JMP sequenceDecs_decode_56_amd64_adjust_offset_nonzero - -sequenceDecs_decode_56_amd64_adjust_offset_maybezero: - TESTQ CX, CX - JNZ sequenceDecs_decode_56_amd64_adjust_offset_nonzero - MOVQ R11, CX - JMP sequenceDecs_decode_56_amd64_after_adjust - -sequenceDecs_decode_56_amd64_adjust_offset_nonzero: - CMPQ CX, $0x01 - JB sequenceDecs_decode_56_amd64_adjust_zero - JEQ sequenceDecs_decode_56_amd64_adjust_one - CMPQ CX, $0x02 - JA sequenceDecs_decode_56_amd64_adjust_three - JMP sequenceDecs_decode_56_amd64_adjust_two - -sequenceDecs_decode_56_amd64_adjust_zero: - MOVQ R11, AX - JMP sequenceDecs_decode_56_amd64_adjust_test_temp_valid - -sequenceDecs_decode_56_amd64_adjust_one: - MOVQ R12, AX - JMP sequenceDecs_decode_56_amd64_adjust_test_temp_valid - -sequenceDecs_decode_56_amd64_adjust_two: - MOVQ R13, AX - JMP sequenceDecs_decode_56_amd64_adjust_test_temp_valid - -sequenceDecs_decode_56_amd64_adjust_three: - LEAQ -1(R11), AX - -sequenceDecs_decode_56_amd64_adjust_test_temp_valid: - TESTQ AX, AX - JNZ sequenceDecs_decode_56_amd64_adjust_temp_valid - MOVQ $0x00000001, AX - -sequenceDecs_decode_56_amd64_adjust_temp_valid: - CMPQ CX, $0x01 - CMOVQNE R12, R13 - MOVQ R11, R12 - MOVQ AX, R11 - MOVQ AX, CX - -sequenceDecs_decode_56_amd64_after_adjust: - MOVQ CX, 16(R10) - - // Check values - MOVQ 8(R10), AX - MOVQ (R10), R14 - LEAQ (AX)(R14*1), R15 - MOVQ s+0(FP), BP - ADDQ R15, 256(BP) - MOVQ ctx+16(FP), R15 - SUBQ R14, 128(R15) - JS error_not_enough_literals - CMPQ AX, $0x00020002 - JA sequenceDecs_decode_56_amd64_error_match_len_too_big - TESTQ CX, CX - JNZ sequenceDecs_decode_56_amd64_match_len_ofs_ok - TESTQ AX, AX - JNZ sequenceDecs_decode_56_amd64_error_match_len_ofs_mismatch - -sequenceDecs_decode_56_amd64_match_len_ofs_ok: - ADDQ $0x18, R10 - MOVQ ctx+16(FP), AX - DECQ 96(AX) - JNS sequenceDecs_decode_56_amd64_main_loop - MOVQ s+0(FP), AX - MOVQ R11, 144(AX) - MOVQ R12, 152(AX) - MOVQ R13, 160(AX) - MOVQ br+8(FP), AX - MOVQ DX, 24(AX) - MOVB BL, 32(AX) - MOVQ SI, 8(AX) - - // Return success - MOVQ $0x00000000, ret+24(FP) - RET - - // Return with match length error -sequenceDecs_decode_56_amd64_error_match_len_ofs_mismatch: - MOVQ $0x00000001, ret+24(FP) - RET - - // Return with match too long error -sequenceDecs_decode_56_amd64_error_match_len_too_big: - MOVQ $0x00000002, ret+24(FP) - RET - - // Return with match offset too long error - MOVQ $0x00000003, ret+24(FP) - RET - - // Return with not enough literals error -error_not_enough_literals: - MOVQ $0x00000004, ret+24(FP) - RET - - // Return with overread error -error_overread: - MOVQ $0x00000006, ret+24(FP) - RET - -// func sequenceDecs_decode_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int -// Requires: BMI, BMI2, CMOV -TEXT ·sequenceDecs_decode_bmi2(SB), $8-32 - MOVQ br+8(FP), BX - MOVQ 24(BX), AX - MOVBQZX 32(BX), DX - MOVQ (BX), CX - MOVQ 8(BX), BX - ADDQ BX, CX - MOVQ CX, (SP) - MOVQ ctx+16(FP), CX - MOVQ 72(CX), SI - MOVQ 80(CX), DI - MOVQ 88(CX), R8 - MOVQ 104(CX), R9 - MOVQ s+0(FP), CX - MOVQ 144(CX), R10 - MOVQ 152(CX), R11 - MOVQ 160(CX), R12 - -sequenceDecs_decode_bmi2_main_loop: - MOVQ (SP), R13 - - // Fill bitreader to have enough for the offset and match length. - CMPQ BX, $0x08 - JL sequenceDecs_decode_bmi2_fill_byte_by_byte - MOVQ DX, CX - SHRQ $0x03, CX - SUBQ CX, R13 - MOVQ (R13), AX - SUBQ CX, BX - ANDQ $0x07, DX - JMP sequenceDecs_decode_bmi2_fill_end - -sequenceDecs_decode_bmi2_fill_byte_by_byte: - CMPQ BX, $0x00 - JLE sequenceDecs_decode_bmi2_fill_check_overread - CMPQ DX, $0x07 - JLE sequenceDecs_decode_bmi2_fill_end - SHLQ $0x08, AX - SUBQ $0x01, R13 - SUBQ $0x01, BX - SUBQ $0x08, DX - MOVBQZX (R13), CX - ORQ CX, AX - JMP sequenceDecs_decode_bmi2_fill_byte_by_byte - -sequenceDecs_decode_bmi2_fill_check_overread: - CMPQ DX, $0x40 - JA error_overread - -sequenceDecs_decode_bmi2_fill_end: - // Update offset - MOVQ $0x00000808, CX - BEXTRQ CX, R8, R14 - MOVQ AX, R15 - LEAQ (DX)(R14*1), CX - ROLQ CL, R15 - BZHIQ R14, R15, R15 - MOVQ CX, DX - MOVQ R8, CX - SHRQ $0x20, CX - ADDQ R15, CX - MOVQ CX, 16(R9) - - // Update match length - MOVQ $0x00000808, CX - BEXTRQ CX, DI, R14 - MOVQ AX, R15 - LEAQ (DX)(R14*1), CX - ROLQ CL, R15 - BZHIQ R14, R15, R15 - MOVQ CX, DX - MOVQ DI, CX - SHRQ $0x20, CX - ADDQ R15, CX - MOVQ CX, 8(R9) - - // Fill bitreader to have enough for the remaining - CMPQ BX, $0x08 - JL sequenceDecs_decode_bmi2_fill_2_byte_by_byte - MOVQ DX, CX - SHRQ $0x03, CX - SUBQ CX, R13 - MOVQ (R13), AX - SUBQ CX, BX - ANDQ $0x07, DX - JMP sequenceDecs_decode_bmi2_fill_2_end - -sequenceDecs_decode_bmi2_fill_2_byte_by_byte: - CMPQ BX, $0x00 - JLE sequenceDecs_decode_bmi2_fill_2_check_overread - CMPQ DX, $0x07 - JLE sequenceDecs_decode_bmi2_fill_2_end - SHLQ $0x08, AX - SUBQ $0x01, R13 - SUBQ $0x01, BX - SUBQ $0x08, DX - MOVBQZX (R13), CX - ORQ CX, AX - JMP sequenceDecs_decode_bmi2_fill_2_byte_by_byte - -sequenceDecs_decode_bmi2_fill_2_check_overread: - CMPQ DX, $0x40 - JA error_overread - -sequenceDecs_decode_bmi2_fill_2_end: - // Update literal length - MOVQ $0x00000808, CX - BEXTRQ CX, SI, R14 - MOVQ AX, R15 - LEAQ (DX)(R14*1), CX - ROLQ CL, R15 - BZHIQ R14, R15, R15 - MOVQ CX, DX - MOVQ SI, CX - SHRQ $0x20, CX - ADDQ R15, CX - MOVQ CX, (R9) - - // Fill bitreader for state updates - MOVQ R13, (SP) - MOVQ $0x00000808, CX - BEXTRQ CX, R8, R13 - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 - JZ sequenceDecs_decode_bmi2_skip_update - LEAQ (SI)(DI*1), R14 - ADDQ R8, R14 - MOVBQZX R14, R14 - LEAQ (DX)(R14*1), CX - MOVQ AX, R15 - MOVQ CX, DX - ROLQ CL, R15 - BZHIQ R14, R15, R15 - - // Update Offset State - BZHIQ R8, R15, CX - SHRXQ R8, R15, R15 - MOVQ $0x00001010, R14 - BEXTRQ R14, R8, R8 - ADDQ CX, R8 - - // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX - MOVQ (CX)(R8*8), R8 - - // Update Match Length State - BZHIQ DI, R15, CX - SHRXQ DI, R15, R15 - MOVQ $0x00001010, R14 - BEXTRQ R14, DI, DI - ADDQ CX, DI - - // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX - MOVQ (CX)(DI*8), DI - - // Update Literal Length State - BZHIQ SI, R15, CX - MOVQ $0x00001010, R14 - BEXTRQ R14, SI, SI - ADDQ CX, SI - - // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX - MOVQ (CX)(SI*8), SI - -sequenceDecs_decode_bmi2_skip_update: - // Adjust offset - MOVQ 16(R9), CX - CMPQ R13, $0x01 - JBE sequenceDecs_decode_bmi2_adjust_offsetB_1_or_0 - MOVQ R11, R12 - MOVQ R10, R11 - MOVQ CX, R10 - JMP sequenceDecs_decode_bmi2_after_adjust - -sequenceDecs_decode_bmi2_adjust_offsetB_1_or_0: - CMPQ (R9), $0x00000000 - JNE sequenceDecs_decode_bmi2_adjust_offset_maybezero - INCQ CX - JMP sequenceDecs_decode_bmi2_adjust_offset_nonzero - -sequenceDecs_decode_bmi2_adjust_offset_maybezero: - TESTQ CX, CX - JNZ sequenceDecs_decode_bmi2_adjust_offset_nonzero - MOVQ R10, CX - JMP sequenceDecs_decode_bmi2_after_adjust - -sequenceDecs_decode_bmi2_adjust_offset_nonzero: - CMPQ CX, $0x01 - JB sequenceDecs_decode_bmi2_adjust_zero - JEQ sequenceDecs_decode_bmi2_adjust_one - CMPQ CX, $0x02 - JA sequenceDecs_decode_bmi2_adjust_three - JMP sequenceDecs_decode_bmi2_adjust_two - -sequenceDecs_decode_bmi2_adjust_zero: - MOVQ R10, R13 - JMP sequenceDecs_decode_bmi2_adjust_test_temp_valid - -sequenceDecs_decode_bmi2_adjust_one: - MOVQ R11, R13 - JMP sequenceDecs_decode_bmi2_adjust_test_temp_valid - -sequenceDecs_decode_bmi2_adjust_two: - MOVQ R12, R13 - JMP sequenceDecs_decode_bmi2_adjust_test_temp_valid - -sequenceDecs_decode_bmi2_adjust_three: - LEAQ -1(R10), R13 - -sequenceDecs_decode_bmi2_adjust_test_temp_valid: - TESTQ R13, R13 - JNZ sequenceDecs_decode_bmi2_adjust_temp_valid - MOVQ $0x00000001, R13 - -sequenceDecs_decode_bmi2_adjust_temp_valid: - CMPQ CX, $0x01 - CMOVQNE R11, R12 - MOVQ R10, R11 - MOVQ R13, R10 - MOVQ R13, CX - -sequenceDecs_decode_bmi2_after_adjust: - MOVQ CX, 16(R9) - - // Check values - MOVQ 8(R9), R13 - MOVQ (R9), R14 - LEAQ (R13)(R14*1), R15 - MOVQ s+0(FP), BP - ADDQ R15, 256(BP) - MOVQ ctx+16(FP), R15 - SUBQ R14, 128(R15) - JS error_not_enough_literals - CMPQ R13, $0x00020002 - JA sequenceDecs_decode_bmi2_error_match_len_too_big - TESTQ CX, CX - JNZ sequenceDecs_decode_bmi2_match_len_ofs_ok - TESTQ R13, R13 - JNZ sequenceDecs_decode_bmi2_error_match_len_ofs_mismatch - -sequenceDecs_decode_bmi2_match_len_ofs_ok: - ADDQ $0x18, R9 - MOVQ ctx+16(FP), CX - DECQ 96(CX) - JNS sequenceDecs_decode_bmi2_main_loop - MOVQ s+0(FP), CX - MOVQ R10, 144(CX) - MOVQ R11, 152(CX) - MOVQ R12, 160(CX) - MOVQ br+8(FP), CX - MOVQ AX, 24(CX) - MOVB DL, 32(CX) - MOVQ BX, 8(CX) - - // Return success - MOVQ $0x00000000, ret+24(FP) - RET - - // Return with match length error -sequenceDecs_decode_bmi2_error_match_len_ofs_mismatch: - MOVQ $0x00000001, ret+24(FP) - RET - - // Return with match too long error -sequenceDecs_decode_bmi2_error_match_len_too_big: - MOVQ $0x00000002, ret+24(FP) - RET - - // Return with match offset too long error - MOVQ $0x00000003, ret+24(FP) - RET - - // Return with not enough literals error -error_not_enough_literals: - MOVQ $0x00000004, ret+24(FP) - RET - - // Return with overread error -error_overread: - MOVQ $0x00000006, ret+24(FP) - RET - -// func sequenceDecs_decode_56_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int -// Requires: BMI, BMI2, CMOV -TEXT ·sequenceDecs_decode_56_bmi2(SB), $8-32 - MOVQ br+8(FP), BX - MOVQ 24(BX), AX - MOVBQZX 32(BX), DX - MOVQ (BX), CX - MOVQ 8(BX), BX - ADDQ BX, CX - MOVQ CX, (SP) - MOVQ ctx+16(FP), CX - MOVQ 72(CX), SI - MOVQ 80(CX), DI - MOVQ 88(CX), R8 - MOVQ 104(CX), R9 - MOVQ s+0(FP), CX - MOVQ 144(CX), R10 - MOVQ 152(CX), R11 - MOVQ 160(CX), R12 - -sequenceDecs_decode_56_bmi2_main_loop: - MOVQ (SP), R13 - - // Fill bitreader to have enough for the offset and match length. - CMPQ BX, $0x08 - JL sequenceDecs_decode_56_bmi2_fill_byte_by_byte - MOVQ DX, CX - SHRQ $0x03, CX - SUBQ CX, R13 - MOVQ (R13), AX - SUBQ CX, BX - ANDQ $0x07, DX - JMP sequenceDecs_decode_56_bmi2_fill_end - -sequenceDecs_decode_56_bmi2_fill_byte_by_byte: - CMPQ BX, $0x00 - JLE sequenceDecs_decode_56_bmi2_fill_check_overread - CMPQ DX, $0x07 - JLE sequenceDecs_decode_56_bmi2_fill_end - SHLQ $0x08, AX - SUBQ $0x01, R13 - SUBQ $0x01, BX - SUBQ $0x08, DX - MOVBQZX (R13), CX - ORQ CX, AX - JMP sequenceDecs_decode_56_bmi2_fill_byte_by_byte - -sequenceDecs_decode_56_bmi2_fill_check_overread: - CMPQ DX, $0x40 - JA error_overread - -sequenceDecs_decode_56_bmi2_fill_end: - // Update offset - MOVQ $0x00000808, CX - BEXTRQ CX, R8, R14 - MOVQ AX, R15 - LEAQ (DX)(R14*1), CX - ROLQ CL, R15 - BZHIQ R14, R15, R15 - MOVQ CX, DX - MOVQ R8, CX - SHRQ $0x20, CX - ADDQ R15, CX - MOVQ CX, 16(R9) - - // Update match length - MOVQ $0x00000808, CX - BEXTRQ CX, DI, R14 - MOVQ AX, R15 - LEAQ (DX)(R14*1), CX - ROLQ CL, R15 - BZHIQ R14, R15, R15 - MOVQ CX, DX - MOVQ DI, CX - SHRQ $0x20, CX - ADDQ R15, CX - MOVQ CX, 8(R9) - - // Update literal length - MOVQ $0x00000808, CX - BEXTRQ CX, SI, R14 - MOVQ AX, R15 - LEAQ (DX)(R14*1), CX - ROLQ CL, R15 - BZHIQ R14, R15, R15 - MOVQ CX, DX - MOVQ SI, CX - SHRQ $0x20, CX - ADDQ R15, CX - MOVQ CX, (R9) - - // Fill bitreader for state updates - MOVQ R13, (SP) - MOVQ $0x00000808, CX - BEXTRQ CX, R8, R13 - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 - JZ sequenceDecs_decode_56_bmi2_skip_update - LEAQ (SI)(DI*1), R14 - ADDQ R8, R14 - MOVBQZX R14, R14 - LEAQ (DX)(R14*1), CX - MOVQ AX, R15 - MOVQ CX, DX - ROLQ CL, R15 - BZHIQ R14, R15, R15 - - // Update Offset State - BZHIQ R8, R15, CX - SHRXQ R8, R15, R15 - MOVQ $0x00001010, R14 - BEXTRQ R14, R8, R8 - ADDQ CX, R8 - - // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX - MOVQ (CX)(R8*8), R8 - - // Update Match Length State - BZHIQ DI, R15, CX - SHRXQ DI, R15, R15 - MOVQ $0x00001010, R14 - BEXTRQ R14, DI, DI - ADDQ CX, DI - - // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX - MOVQ (CX)(DI*8), DI - - // Update Literal Length State - BZHIQ SI, R15, CX - MOVQ $0x00001010, R14 - BEXTRQ R14, SI, SI - ADDQ CX, SI - - // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX - MOVQ (CX)(SI*8), SI - -sequenceDecs_decode_56_bmi2_skip_update: - // Adjust offset - MOVQ 16(R9), CX - CMPQ R13, $0x01 - JBE sequenceDecs_decode_56_bmi2_adjust_offsetB_1_or_0 - MOVQ R11, R12 - MOVQ R10, R11 - MOVQ CX, R10 - JMP sequenceDecs_decode_56_bmi2_after_adjust - -sequenceDecs_decode_56_bmi2_adjust_offsetB_1_or_0: - CMPQ (R9), $0x00000000 - JNE sequenceDecs_decode_56_bmi2_adjust_offset_maybezero - INCQ CX - JMP sequenceDecs_decode_56_bmi2_adjust_offset_nonzero - -sequenceDecs_decode_56_bmi2_adjust_offset_maybezero: - TESTQ CX, CX - JNZ sequenceDecs_decode_56_bmi2_adjust_offset_nonzero - MOVQ R10, CX - JMP sequenceDecs_decode_56_bmi2_after_adjust - -sequenceDecs_decode_56_bmi2_adjust_offset_nonzero: - CMPQ CX, $0x01 - JB sequenceDecs_decode_56_bmi2_adjust_zero - JEQ sequenceDecs_decode_56_bmi2_adjust_one - CMPQ CX, $0x02 - JA sequenceDecs_decode_56_bmi2_adjust_three - JMP sequenceDecs_decode_56_bmi2_adjust_two - -sequenceDecs_decode_56_bmi2_adjust_zero: - MOVQ R10, R13 - JMP sequenceDecs_decode_56_bmi2_adjust_test_temp_valid - -sequenceDecs_decode_56_bmi2_adjust_one: - MOVQ R11, R13 - JMP sequenceDecs_decode_56_bmi2_adjust_test_temp_valid - -sequenceDecs_decode_56_bmi2_adjust_two: - MOVQ R12, R13 - JMP sequenceDecs_decode_56_bmi2_adjust_test_temp_valid - -sequenceDecs_decode_56_bmi2_adjust_three: - LEAQ -1(R10), R13 - -sequenceDecs_decode_56_bmi2_adjust_test_temp_valid: - TESTQ R13, R13 - JNZ sequenceDecs_decode_56_bmi2_adjust_temp_valid - MOVQ $0x00000001, R13 - -sequenceDecs_decode_56_bmi2_adjust_temp_valid: - CMPQ CX, $0x01 - CMOVQNE R11, R12 - MOVQ R10, R11 - MOVQ R13, R10 - MOVQ R13, CX - -sequenceDecs_decode_56_bmi2_after_adjust: - MOVQ CX, 16(R9) - - // Check values - MOVQ 8(R9), R13 - MOVQ (R9), R14 - LEAQ (R13)(R14*1), R15 - MOVQ s+0(FP), BP - ADDQ R15, 256(BP) - MOVQ ctx+16(FP), R15 - SUBQ R14, 128(R15) - JS error_not_enough_literals - CMPQ R13, $0x00020002 - JA sequenceDecs_decode_56_bmi2_error_match_len_too_big - TESTQ CX, CX - JNZ sequenceDecs_decode_56_bmi2_match_len_ofs_ok - TESTQ R13, R13 - JNZ sequenceDecs_decode_56_bmi2_error_match_len_ofs_mismatch - -sequenceDecs_decode_56_bmi2_match_len_ofs_ok: - ADDQ $0x18, R9 - MOVQ ctx+16(FP), CX - DECQ 96(CX) - JNS sequenceDecs_decode_56_bmi2_main_loop - MOVQ s+0(FP), CX - MOVQ R10, 144(CX) - MOVQ R11, 152(CX) - MOVQ R12, 160(CX) - MOVQ br+8(FP), CX - MOVQ AX, 24(CX) - MOVB DL, 32(CX) - MOVQ BX, 8(CX) - - // Return success - MOVQ $0x00000000, ret+24(FP) - RET - - // Return with match length error -sequenceDecs_decode_56_bmi2_error_match_len_ofs_mismatch: - MOVQ $0x00000001, ret+24(FP) - RET - - // Return with match too long error -sequenceDecs_decode_56_bmi2_error_match_len_too_big: - MOVQ $0x00000002, ret+24(FP) - RET - - // Return with match offset too long error - MOVQ $0x00000003, ret+24(FP) - RET - - // Return with not enough literals error -error_not_enough_literals: - MOVQ $0x00000004, ret+24(FP) - RET - - // Return with overread error -error_overread: - MOVQ $0x00000006, ret+24(FP) - RET - -// func sequenceDecs_executeSimple_amd64(ctx *executeAsmContext) bool -// Requires: SSE -TEXT ·sequenceDecs_executeSimple_amd64(SB), $8-9 - MOVQ ctx+0(FP), R10 - MOVQ 8(R10), CX - TESTQ CX, CX - JZ empty_seqs - MOVQ (R10), AX - MOVQ 24(R10), DX - MOVQ 32(R10), BX - MOVQ 80(R10), SI - MOVQ 104(R10), DI - MOVQ 120(R10), R8 - MOVQ 56(R10), R9 - MOVQ 64(R10), R10 - ADDQ R10, R9 - - // seqsBase += 24 * seqIndex - LEAQ (DX)(DX*2), R11 - SHLQ $0x03, R11 - ADDQ R11, AX - - // outBase += outPosition - ADDQ DI, BX - -main_loop: - MOVQ (AX), R11 - MOVQ 16(AX), R12 - MOVQ 8(AX), R13 - - // Copy literals - TESTQ R11, R11 - JZ check_offset - XORQ R14, R14 - -copy_1: - MOVUPS (SI)(R14*1), X0 - MOVUPS X0, (BX)(R14*1) - ADDQ $0x10, R14 - CMPQ R14, R11 - JB copy_1 - ADDQ R11, SI - ADDQ R11, BX - ADDQ R11, DI - - // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: - LEAQ (DI)(R10*1), R11 - CMPQ R12, R11 - JG error_match_off_too_big - CMPQ R12, R8 - JG error_match_off_too_big - - // Copy match from history - MOVQ R12, R11 - SUBQ DI, R11 - JLS copy_match - MOVQ R9, R14 - SUBQ R11, R14 - CMPQ R13, R11 - JG copy_all_from_history - MOVQ R13, R11 - SUBQ $0x10, R11 - JB copy_4_small - -copy_4_loop: - MOVUPS (R14), X0 - MOVUPS X0, (BX) - ADDQ $0x10, R14 - ADDQ $0x10, BX - SUBQ $0x10, R11 - JAE copy_4_loop - LEAQ 16(R14)(R11*1), R14 - LEAQ 16(BX)(R11*1), BX - MOVUPS -16(R14), X0 - MOVUPS X0, -16(BX) - JMP copy_4_end - -copy_4_small: - CMPQ R13, $0x03 - JE copy_4_move_3 - CMPQ R13, $0x08 - JB copy_4_move_4through7 - JMP copy_4_move_8through16 - -copy_4_move_3: - MOVW (R14), R11 - MOVB 2(R14), R12 - MOVW R11, (BX) - MOVB R12, 2(BX) - ADDQ R13, R14 - ADDQ R13, BX - JMP copy_4_end - -copy_4_move_4through7: - MOVL (R14), R11 - MOVL -4(R14)(R13*1), R12 - MOVL R11, (BX) - MOVL R12, -4(BX)(R13*1) - ADDQ R13, R14 - ADDQ R13, BX - JMP copy_4_end - -copy_4_move_8through16: - MOVQ (R14), R11 - MOVQ -8(R14)(R13*1), R12 - MOVQ R11, (BX) - MOVQ R12, -8(BX)(R13*1) - ADDQ R13, R14 - ADDQ R13, BX - -copy_4_end: - ADDQ R13, DI - ADDQ $0x18, AX - INCQ DX - CMPQ DX, CX - JB main_loop - JMP loop_finished - -copy_all_from_history: - MOVQ R11, R15 - SUBQ $0x10, R15 - JB copy_5_small - -copy_5_loop: - MOVUPS (R14), X0 - MOVUPS X0, (BX) - ADDQ $0x10, R14 - ADDQ $0x10, BX - SUBQ $0x10, R15 - JAE copy_5_loop - LEAQ 16(R14)(R15*1), R14 - LEAQ 16(BX)(R15*1), BX - MOVUPS -16(R14), X0 - MOVUPS X0, -16(BX) - JMP copy_5_end - -copy_5_small: - CMPQ R11, $0x03 - JE copy_5_move_3 - JB copy_5_move_1or2 - CMPQ R11, $0x08 - JB copy_5_move_4through7 - JMP copy_5_move_8through16 - -copy_5_move_1or2: - MOVB (R14), R15 - MOVB -1(R14)(R11*1), BP - MOVB R15, (BX) - MOVB BP, -1(BX)(R11*1) - ADDQ R11, R14 - ADDQ R11, BX - JMP copy_5_end - -copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (BX) - MOVB BP, 2(BX) - ADDQ R11, R14 - ADDQ R11, BX - JMP copy_5_end - -copy_5_move_4through7: - MOVL (R14), R15 - MOVL -4(R14)(R11*1), BP - MOVL R15, (BX) - MOVL BP, -4(BX)(R11*1) - ADDQ R11, R14 - ADDQ R11, BX - JMP copy_5_end - -copy_5_move_8through16: - MOVQ (R14), R15 - MOVQ -8(R14)(R11*1), BP - MOVQ R15, (BX) - MOVQ BP, -8(BX)(R11*1) - ADDQ R11, R14 - ADDQ R11, BX - -copy_5_end: - ADDQ R11, DI - SUBQ R11, R13 - - // Copy match from the current buffer -copy_match: - MOVQ BX, R11 - SUBQ R12, R11 - - // ml <= mo - CMPQ R13, R12 - JA copy_overlapping_match - - // Copy non-overlapping match - ADDQ R13, DI - MOVQ BX, R12 - ADDQ R13, BX - -copy_2: - MOVUPS (R11), X0 - MOVUPS X0, (R12) - ADDQ $0x10, R11 - ADDQ $0x10, R12 - SUBQ $0x10, R13 - JHI copy_2 - JMP handle_loop - - // Copy overlapping match -copy_overlapping_match: - ADDQ R13, DI - -copy_slow_3: - MOVB (R11), R12 - MOVB R12, (BX) - INCQ R11 - INCQ BX - DECQ R13 - JNZ copy_slow_3 - -handle_loop: - ADDQ $0x18, AX - INCQ DX - CMPQ DX, CX - JB main_loop - -loop_finished: - // Return value - MOVB $0x01, ret+8(FP) - - // Update the context - MOVQ ctx+0(FP), AX - MOVQ DX, 24(AX) - MOVQ DI, 104(AX) - SUBQ 80(AX), SI - MOVQ SI, 112(AX) - RET - -error_match_off_too_big: - // Return value - MOVB $0x00, ret+8(FP) - - // Update the context - MOVQ ctx+0(FP), AX - MOVQ DX, 24(AX) - MOVQ DI, 104(AX) - SUBQ 80(AX), SI - MOVQ SI, 112(AX) - RET - -empty_seqs: - // Return value - MOVB $0x01, ret+8(FP) - RET - -// func sequenceDecs_executeSimple_safe_amd64(ctx *executeAsmContext) bool -// Requires: SSE -TEXT ·sequenceDecs_executeSimple_safe_amd64(SB), $8-9 - MOVQ ctx+0(FP), R10 - MOVQ 8(R10), CX - TESTQ CX, CX - JZ empty_seqs - MOVQ (R10), AX - MOVQ 24(R10), DX - MOVQ 32(R10), BX - MOVQ 80(R10), SI - MOVQ 104(R10), DI - MOVQ 120(R10), R8 - MOVQ 56(R10), R9 - MOVQ 64(R10), R10 - ADDQ R10, R9 - - // seqsBase += 24 * seqIndex - LEAQ (DX)(DX*2), R11 - SHLQ $0x03, R11 - ADDQ R11, AX - - // outBase += outPosition - ADDQ DI, BX - -main_loop: - MOVQ (AX), R11 - MOVQ 16(AX), R12 - MOVQ 8(AX), R13 - - // Copy literals - TESTQ R11, R11 - JZ check_offset - MOVQ R11, R14 - SUBQ $0x10, R14 - JB copy_1_small - -copy_1_loop: - MOVUPS (SI), X0 - MOVUPS X0, (BX) - ADDQ $0x10, SI - ADDQ $0x10, BX - SUBQ $0x10, R14 - JAE copy_1_loop - LEAQ 16(SI)(R14*1), SI - LEAQ 16(BX)(R14*1), BX - MOVUPS -16(SI), X0 - MOVUPS X0, -16(BX) - JMP copy_1_end - -copy_1_small: - CMPQ R11, $0x03 - JE copy_1_move_3 - JB copy_1_move_1or2 - CMPQ R11, $0x08 - JB copy_1_move_4through7 - JMP copy_1_move_8through16 - -copy_1_move_1or2: - MOVB (SI), R14 - MOVB -1(SI)(R11*1), R15 - MOVB R14, (BX) - MOVB R15, -1(BX)(R11*1) - ADDQ R11, SI - ADDQ R11, BX - JMP copy_1_end - -copy_1_move_3: - MOVW (SI), R14 - MOVB 2(SI), R15 - MOVW R14, (BX) - MOVB R15, 2(BX) - ADDQ R11, SI - ADDQ R11, BX - JMP copy_1_end - -copy_1_move_4through7: - MOVL (SI), R14 - MOVL -4(SI)(R11*1), R15 - MOVL R14, (BX) - MOVL R15, -4(BX)(R11*1) - ADDQ R11, SI - ADDQ R11, BX - JMP copy_1_end - -copy_1_move_8through16: - MOVQ (SI), R14 - MOVQ -8(SI)(R11*1), R15 - MOVQ R14, (BX) - MOVQ R15, -8(BX)(R11*1) - ADDQ R11, SI - ADDQ R11, BX - -copy_1_end: - ADDQ R11, DI - - // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: - LEAQ (DI)(R10*1), R11 - CMPQ R12, R11 - JG error_match_off_too_big - CMPQ R12, R8 - JG error_match_off_too_big - - // Copy match from history - MOVQ R12, R11 - SUBQ DI, R11 - JLS copy_match - MOVQ R9, R14 - SUBQ R11, R14 - CMPQ R13, R11 - JG copy_all_from_history - MOVQ R13, R11 - SUBQ $0x10, R11 - JB copy_4_small - -copy_4_loop: - MOVUPS (R14), X0 - MOVUPS X0, (BX) - ADDQ $0x10, R14 - ADDQ $0x10, BX - SUBQ $0x10, R11 - JAE copy_4_loop - LEAQ 16(R14)(R11*1), R14 - LEAQ 16(BX)(R11*1), BX - MOVUPS -16(R14), X0 - MOVUPS X0, -16(BX) - JMP copy_4_end - -copy_4_small: - CMPQ R13, $0x03 - JE copy_4_move_3 - CMPQ R13, $0x08 - JB copy_4_move_4through7 - JMP copy_4_move_8through16 - -copy_4_move_3: - MOVW (R14), R11 - MOVB 2(R14), R12 - MOVW R11, (BX) - MOVB R12, 2(BX) - ADDQ R13, R14 - ADDQ R13, BX - JMP copy_4_end - -copy_4_move_4through7: - MOVL (R14), R11 - MOVL -4(R14)(R13*1), R12 - MOVL R11, (BX) - MOVL R12, -4(BX)(R13*1) - ADDQ R13, R14 - ADDQ R13, BX - JMP copy_4_end - -copy_4_move_8through16: - MOVQ (R14), R11 - MOVQ -8(R14)(R13*1), R12 - MOVQ R11, (BX) - MOVQ R12, -8(BX)(R13*1) - ADDQ R13, R14 - ADDQ R13, BX - -copy_4_end: - ADDQ R13, DI - ADDQ $0x18, AX - INCQ DX - CMPQ DX, CX - JB main_loop - JMP loop_finished - -copy_all_from_history: - MOVQ R11, R15 - SUBQ $0x10, R15 - JB copy_5_small - -copy_5_loop: - MOVUPS (R14), X0 - MOVUPS X0, (BX) - ADDQ $0x10, R14 - ADDQ $0x10, BX - SUBQ $0x10, R15 - JAE copy_5_loop - LEAQ 16(R14)(R15*1), R14 - LEAQ 16(BX)(R15*1), BX - MOVUPS -16(R14), X0 - MOVUPS X0, -16(BX) - JMP copy_5_end - -copy_5_small: - CMPQ R11, $0x03 - JE copy_5_move_3 - JB copy_5_move_1or2 - CMPQ R11, $0x08 - JB copy_5_move_4through7 - JMP copy_5_move_8through16 - -copy_5_move_1or2: - MOVB (R14), R15 - MOVB -1(R14)(R11*1), BP - MOVB R15, (BX) - MOVB BP, -1(BX)(R11*1) - ADDQ R11, R14 - ADDQ R11, BX - JMP copy_5_end - -copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (BX) - MOVB BP, 2(BX) - ADDQ R11, R14 - ADDQ R11, BX - JMP copy_5_end - -copy_5_move_4through7: - MOVL (R14), R15 - MOVL -4(R14)(R11*1), BP - MOVL R15, (BX) - MOVL BP, -4(BX)(R11*1) - ADDQ R11, R14 - ADDQ R11, BX - JMP copy_5_end - -copy_5_move_8through16: - MOVQ (R14), R15 - MOVQ -8(R14)(R11*1), BP - MOVQ R15, (BX) - MOVQ BP, -8(BX)(R11*1) - ADDQ R11, R14 - ADDQ R11, BX - -copy_5_end: - ADDQ R11, DI - SUBQ R11, R13 - - // Copy match from the current buffer -copy_match: - MOVQ BX, R11 - SUBQ R12, R11 - - // ml <= mo - CMPQ R13, R12 - JA copy_overlapping_match - - // Copy non-overlapping match - ADDQ R13, DI - MOVQ R13, R12 - SUBQ $0x10, R12 - JB copy_2_small - -copy_2_loop: - MOVUPS (R11), X0 - MOVUPS X0, (BX) - ADDQ $0x10, R11 - ADDQ $0x10, BX - SUBQ $0x10, R12 - JAE copy_2_loop - LEAQ 16(R11)(R12*1), R11 - LEAQ 16(BX)(R12*1), BX - MOVUPS -16(R11), X0 - MOVUPS X0, -16(BX) - JMP copy_2_end - -copy_2_small: - CMPQ R13, $0x03 - JE copy_2_move_3 - JB copy_2_move_1or2 - CMPQ R13, $0x08 - JB copy_2_move_4through7 - JMP copy_2_move_8through16 - -copy_2_move_1or2: - MOVB (R11), R12 - MOVB -1(R11)(R13*1), R14 - MOVB R12, (BX) - MOVB R14, -1(BX)(R13*1) - ADDQ R13, R11 - ADDQ R13, BX - JMP copy_2_end - -copy_2_move_3: - MOVW (R11), R12 - MOVB 2(R11), R14 - MOVW R12, (BX) - MOVB R14, 2(BX) - ADDQ R13, R11 - ADDQ R13, BX - JMP copy_2_end - -copy_2_move_4through7: - MOVL (R11), R12 - MOVL -4(R11)(R13*1), R14 - MOVL R12, (BX) - MOVL R14, -4(BX)(R13*1) - ADDQ R13, R11 - ADDQ R13, BX - JMP copy_2_end - -copy_2_move_8through16: - MOVQ (R11), R12 - MOVQ -8(R11)(R13*1), R14 - MOVQ R12, (BX) - MOVQ R14, -8(BX)(R13*1) - ADDQ R13, R11 - ADDQ R13, BX - -copy_2_end: - JMP handle_loop - - // Copy overlapping match -copy_overlapping_match: - ADDQ R13, DI - -copy_slow_3: - MOVB (R11), R12 - MOVB R12, (BX) - INCQ R11 - INCQ BX - DECQ R13 - JNZ copy_slow_3 - -handle_loop: - ADDQ $0x18, AX - INCQ DX - CMPQ DX, CX - JB main_loop - -loop_finished: - // Return value - MOVB $0x01, ret+8(FP) - - // Update the context - MOVQ ctx+0(FP), AX - MOVQ DX, 24(AX) - MOVQ DI, 104(AX) - SUBQ 80(AX), SI - MOVQ SI, 112(AX) - RET - -error_match_off_too_big: - // Return value - MOVB $0x00, ret+8(FP) - - // Update the context - MOVQ ctx+0(FP), AX - MOVQ DX, 24(AX) - MOVQ DI, 104(AX) - SUBQ 80(AX), SI - MOVQ SI, 112(AX) - RET - -empty_seqs: - // Return value - MOVB $0x01, ret+8(FP) - RET - -// func sequenceDecs_decodeSync_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int -// Requires: CMOV, SSE -TEXT ·sequenceDecs_decodeSync_amd64(SB), $64-32 - MOVQ br+8(FP), CX - MOVQ 24(CX), DX - MOVBQZX 32(CX), BX - MOVQ (CX), AX - MOVQ 8(CX), SI - ADDQ SI, AX - MOVQ AX, (SP) - MOVQ ctx+16(FP), AX - MOVQ 72(AX), DI - MOVQ 80(AX), R8 - MOVQ 88(AX), R9 - XORQ CX, CX - MOVQ CX, 8(SP) - MOVQ CX, 16(SP) - MOVQ CX, 24(SP) - MOVQ 112(AX), R10 - MOVQ 128(AX), CX - MOVQ CX, 32(SP) - MOVQ 144(AX), R11 - MOVQ 136(AX), R12 - MOVQ 200(AX), CX - MOVQ CX, 56(SP) - MOVQ 176(AX), CX - MOVQ CX, 48(SP) - MOVQ 184(AX), AX - MOVQ AX, 40(SP) - MOVQ 40(SP), AX - ADDQ AX, 48(SP) - - // Calculate poiter to s.out[cap(s.out)] (a past-end pointer) - ADDQ R10, 32(SP) - - // outBase += outPosition - ADDQ R12, R10 - -sequenceDecs_decodeSync_amd64_main_loop: - MOVQ (SP), R13 - - // Fill bitreader to have enough for the offset and match length. - CMPQ SI, $0x08 - JL sequenceDecs_decodeSync_amd64_fill_byte_by_byte - MOVQ BX, AX - SHRQ $0x03, AX - SUBQ AX, R13 - MOVQ (R13), DX - SUBQ AX, SI - ANDQ $0x07, BX - JMP sequenceDecs_decodeSync_amd64_fill_end - -sequenceDecs_decodeSync_amd64_fill_byte_by_byte: - CMPQ SI, $0x00 - JLE sequenceDecs_decodeSync_amd64_fill_check_overread - CMPQ BX, $0x07 - JLE sequenceDecs_decodeSync_amd64_fill_end - SHLQ $0x08, DX - SUBQ $0x01, R13 - SUBQ $0x01, SI - SUBQ $0x08, BX - MOVBQZX (R13), AX - ORQ AX, DX - JMP sequenceDecs_decodeSync_amd64_fill_byte_by_byte - -sequenceDecs_decodeSync_amd64_fill_check_overread: - CMPQ BX, $0x40 - JA error_overread - -sequenceDecs_decodeSync_amd64_fill_end: - // Update offset - MOVQ R9, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_amd64_of_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_amd64_of_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_amd64_of_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_amd64_of_update_zero: - MOVQ AX, 8(SP) - - // Update match length - MOVQ R8, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_amd64_ml_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_amd64_ml_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_amd64_ml_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_amd64_ml_update_zero: - MOVQ AX, 16(SP) - - // Fill bitreader to have enough for the remaining - CMPQ SI, $0x08 - JL sequenceDecs_decodeSync_amd64_fill_2_byte_by_byte - MOVQ BX, AX - SHRQ $0x03, AX - SUBQ AX, R13 - MOVQ (R13), DX - SUBQ AX, SI - ANDQ $0x07, BX - JMP sequenceDecs_decodeSync_amd64_fill_2_end - -sequenceDecs_decodeSync_amd64_fill_2_byte_by_byte: - CMPQ SI, $0x00 - JLE sequenceDecs_decodeSync_amd64_fill_2_check_overread - CMPQ BX, $0x07 - JLE sequenceDecs_decodeSync_amd64_fill_2_end - SHLQ $0x08, DX - SUBQ $0x01, R13 - SUBQ $0x01, SI - SUBQ $0x08, BX - MOVBQZX (R13), AX - ORQ AX, DX - JMP sequenceDecs_decodeSync_amd64_fill_2_byte_by_byte - -sequenceDecs_decodeSync_amd64_fill_2_check_overread: - CMPQ BX, $0x40 - JA error_overread - -sequenceDecs_decodeSync_amd64_fill_2_end: - // Update literal length - MOVQ DI, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_amd64_ll_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_amd64_ll_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_amd64_ll_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_amd64_ll_update_zero: - MOVQ AX, 24(SP) - - // Fill bitreader for state updates - MOVQ R13, (SP) - MOVQ R9, AX - SHRQ $0x08, AX - MOVBQZX AL, AX - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 - JZ sequenceDecs_decodeSync_amd64_skip_update - - // Update Literal Length State - MOVBQZX DI, R13 - SHRQ $0x10, DI - MOVWQZX DI, DI - LEAQ (BX)(R13*1), CX - MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 - ADDQ R14, DI - - // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX - MOVQ (CX)(DI*8), DI - - // Update Match Length State - MOVBQZX R8, R13 - SHRQ $0x10, R8 - MOVWQZX R8, R8 - LEAQ (BX)(R13*1), CX - MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 - ADDQ R14, R8 - - // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX - MOVQ (CX)(R8*8), R8 - - // Update Offset State - MOVBQZX R9, R13 - SHRQ $0x10, R9 - MOVWQZX R9, R9 - LEAQ (BX)(R13*1), CX - MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 - ADDQ R14, R9 - - // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX - MOVQ (CX)(R9*8), R9 - -sequenceDecs_decodeSync_amd64_skip_update: - // Adjust offset - MOVQ s+0(FP), CX - MOVQ 8(SP), R13 - CMPQ AX, $0x01 - JBE sequenceDecs_decodeSync_amd64_adjust_offsetB_1_or_0 - MOVUPS 144(CX), X0 - MOVQ R13, 144(CX) - MOVUPS X0, 152(CX) - JMP sequenceDecs_decodeSync_amd64_after_adjust - -sequenceDecs_decodeSync_amd64_adjust_offsetB_1_or_0: - CMPQ 24(SP), $0x00000000 - JNE sequenceDecs_decodeSync_amd64_adjust_offset_maybezero - INCQ R13 - JMP sequenceDecs_decodeSync_amd64_adjust_offset_nonzero - -sequenceDecs_decodeSync_amd64_adjust_offset_maybezero: - TESTQ R13, R13 - JNZ sequenceDecs_decodeSync_amd64_adjust_offset_nonzero - MOVQ 144(CX), R13 - JMP sequenceDecs_decodeSync_amd64_after_adjust - -sequenceDecs_decodeSync_amd64_adjust_offset_nonzero: - MOVQ R13, AX - XORQ R14, R14 - MOVQ $-1, R15 - CMPQ R13, $0x03 - CMOVQEQ R14, AX - CMOVQEQ R15, R14 - ADDQ 144(CX)(AX*8), R14 - JNZ sequenceDecs_decodeSync_amd64_adjust_temp_valid - MOVQ $0x00000001, R14 - -sequenceDecs_decodeSync_amd64_adjust_temp_valid: - CMPQ R13, $0x01 - JZ sequenceDecs_decodeSync_amd64_adjust_skip - MOVQ 152(CX), AX - MOVQ AX, 160(CX) - -sequenceDecs_decodeSync_amd64_adjust_skip: - MOVQ 144(CX), AX - MOVQ AX, 152(CX) - MOVQ R14, 144(CX) - MOVQ R14, R13 - -sequenceDecs_decodeSync_amd64_after_adjust: - MOVQ R13, 8(SP) - - // Check values - MOVQ 16(SP), AX - MOVQ 24(SP), CX - LEAQ (AX)(CX*1), R14 - MOVQ s+0(FP), R15 - ADDQ R14, 256(R15) - MOVQ ctx+16(FP), R14 - SUBQ CX, 104(R14) - JS error_not_enough_literals - CMPQ AX, $0x00020002 - JA sequenceDecs_decodeSync_amd64_error_match_len_too_big - TESTQ R13, R13 - JNZ sequenceDecs_decodeSync_amd64_match_len_ofs_ok - TESTQ AX, AX - JNZ sequenceDecs_decodeSync_amd64_error_match_len_ofs_mismatch - -sequenceDecs_decodeSync_amd64_match_len_ofs_ok: - MOVQ 24(SP), AX - MOVQ 8(SP), CX - MOVQ 16(SP), R13 - - // Check if we have enough space in s.out - LEAQ (AX)(R13*1), R14 - ADDQ R10, R14 - CMPQ R14, 32(SP) - JA error_not_enough_space - - // Copy literals - TESTQ AX, AX - JZ check_offset - XORQ R14, R14 - -copy_1: - MOVUPS (R11)(R14*1), X0 - MOVUPS X0, (R10)(R14*1) - ADDQ $0x10, R14 - CMPQ R14, AX - JB copy_1 - ADDQ AX, R11 - ADDQ AX, R10 - ADDQ AX, R12 - - // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: - MOVQ R12, AX - ADDQ 40(SP), AX - CMPQ CX, AX - JG error_match_off_too_big - CMPQ CX, 56(SP) - JG error_match_off_too_big - - // Copy match from history - MOVQ CX, AX - SUBQ R12, AX - JLS copy_match - MOVQ 48(SP), R14 - SUBQ AX, R14 - CMPQ R13, AX - JG copy_all_from_history - MOVQ R13, AX - SUBQ $0x10, AX - JB copy_4_small - -copy_4_loop: - MOVUPS (R14), X0 - MOVUPS X0, (R10) - ADDQ $0x10, R14 - ADDQ $0x10, R10 - SUBQ $0x10, AX - JAE copy_4_loop - LEAQ 16(R14)(AX*1), R14 - LEAQ 16(R10)(AX*1), R10 - MOVUPS -16(R14), X0 - MOVUPS X0, -16(R10) - JMP copy_4_end - -copy_4_small: - CMPQ R13, $0x03 - JE copy_4_move_3 - CMPQ R13, $0x08 - JB copy_4_move_4through7 - JMP copy_4_move_8through16 - -copy_4_move_3: - MOVW (R14), AX - MOVB 2(R14), CL - MOVW AX, (R10) - MOVB CL, 2(R10) - ADDQ R13, R14 - ADDQ R13, R10 - JMP copy_4_end - -copy_4_move_4through7: - MOVL (R14), AX - MOVL -4(R14)(R13*1), CX - MOVL AX, (R10) - MOVL CX, -4(R10)(R13*1) - ADDQ R13, R14 - ADDQ R13, R10 - JMP copy_4_end - -copy_4_move_8through16: - MOVQ (R14), AX - MOVQ -8(R14)(R13*1), CX - MOVQ AX, (R10) - MOVQ CX, -8(R10)(R13*1) - ADDQ R13, R14 - ADDQ R13, R10 - -copy_4_end: - ADDQ R13, R12 - JMP handle_loop - JMP loop_finished - -copy_all_from_history: - MOVQ AX, R15 - SUBQ $0x10, R15 - JB copy_5_small - -copy_5_loop: - MOVUPS (R14), X0 - MOVUPS X0, (R10) - ADDQ $0x10, R14 - ADDQ $0x10, R10 - SUBQ $0x10, R15 - JAE copy_5_loop - LEAQ 16(R14)(R15*1), R14 - LEAQ 16(R10)(R15*1), R10 - MOVUPS -16(R14), X0 - MOVUPS X0, -16(R10) - JMP copy_5_end - -copy_5_small: - CMPQ AX, $0x03 - JE copy_5_move_3 - JB copy_5_move_1or2 - CMPQ AX, $0x08 - JB copy_5_move_4through7 - JMP copy_5_move_8through16 - -copy_5_move_1or2: - MOVB (R14), R15 - MOVB -1(R14)(AX*1), BP - MOVB R15, (R10) - MOVB BP, -1(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 - JMP copy_5_end - -copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (R10) - MOVB BP, 2(R10) - ADDQ AX, R14 - ADDQ AX, R10 - JMP copy_5_end - -copy_5_move_4through7: - MOVL (R14), R15 - MOVL -4(R14)(AX*1), BP - MOVL R15, (R10) - MOVL BP, -4(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 - JMP copy_5_end - -copy_5_move_8through16: - MOVQ (R14), R15 - MOVQ -8(R14)(AX*1), BP - MOVQ R15, (R10) - MOVQ BP, -8(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 - -copy_5_end: - ADDQ AX, R12 - SUBQ AX, R13 - - // Copy match from the current buffer -copy_match: - MOVQ R10, AX - SUBQ CX, AX - - // ml <= mo - CMPQ R13, CX - JA copy_overlapping_match - - // Copy non-overlapping match - ADDQ R13, R12 - MOVQ R10, CX - ADDQ R13, R10 - -copy_2: - MOVUPS (AX), X0 - MOVUPS X0, (CX) - ADDQ $0x10, AX - ADDQ $0x10, CX - SUBQ $0x10, R13 - JHI copy_2 - JMP handle_loop - - // Copy overlapping match -copy_overlapping_match: - ADDQ R13, R12 - -copy_slow_3: - MOVB (AX), CL - MOVB CL, (R10) - INCQ AX - INCQ R10 - DECQ R13 - JNZ copy_slow_3 - -handle_loop: - MOVQ ctx+16(FP), AX - DECQ 96(AX) - JNS sequenceDecs_decodeSync_amd64_main_loop - -loop_finished: - MOVQ br+8(FP), AX - MOVQ DX, 24(AX) - MOVB BL, 32(AX) - MOVQ SI, 8(AX) - - // Update the context - MOVQ ctx+16(FP), AX - MOVQ R12, 136(AX) - MOVQ 144(AX), CX - SUBQ CX, R11 - MOVQ R11, 168(AX) - - // Return success - MOVQ $0x00000000, ret+24(FP) - RET - - // Return with match length error -sequenceDecs_decodeSync_amd64_error_match_len_ofs_mismatch: - MOVQ 16(SP), AX - MOVQ ctx+16(FP), CX - MOVQ AX, 216(CX) - MOVQ $0x00000001, ret+24(FP) - RET - - // Return with match too long error -sequenceDecs_decodeSync_amd64_error_match_len_too_big: - MOVQ ctx+16(FP), AX - MOVQ 16(SP), CX - MOVQ CX, 216(AX) - MOVQ $0x00000002, ret+24(FP) - RET - - // Return with match offset too long error -error_match_off_too_big: - MOVQ ctx+16(FP), AX - MOVQ 8(SP), CX - MOVQ CX, 224(AX) - MOVQ R12, 136(AX) - MOVQ $0x00000003, ret+24(FP) - RET - - // Return with not enough literals error -error_not_enough_literals: - MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX - MOVQ CX, 208(AX) - MOVQ $0x00000004, ret+24(FP) - RET - - // Return with overread error -error_overread: - MOVQ $0x00000006, ret+24(FP) - RET - - // Return with not enough output space error -error_not_enough_space: - MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX - MOVQ CX, 208(AX) - MOVQ 16(SP), CX - MOVQ CX, 216(AX) - MOVQ R12, 136(AX) - MOVQ $0x00000005, ret+24(FP) - RET - -// func sequenceDecs_decodeSync_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int -// Requires: BMI, BMI2, CMOV, SSE -TEXT ·sequenceDecs_decodeSync_bmi2(SB), $64-32 - MOVQ br+8(FP), BX - MOVQ 24(BX), AX - MOVBQZX 32(BX), DX - MOVQ (BX), CX - MOVQ 8(BX), BX - ADDQ BX, CX - MOVQ CX, (SP) - MOVQ ctx+16(FP), CX - MOVQ 72(CX), SI - MOVQ 80(CX), DI - MOVQ 88(CX), R8 - XORQ R9, R9 - MOVQ R9, 8(SP) - MOVQ R9, 16(SP) - MOVQ R9, 24(SP) - MOVQ 112(CX), R9 - MOVQ 128(CX), R10 - MOVQ R10, 32(SP) - MOVQ 144(CX), R10 - MOVQ 136(CX), R11 - MOVQ 200(CX), R12 - MOVQ R12, 56(SP) - MOVQ 176(CX), R12 - MOVQ R12, 48(SP) - MOVQ 184(CX), CX - MOVQ CX, 40(SP) - MOVQ 40(SP), CX - ADDQ CX, 48(SP) - - // Calculate poiter to s.out[cap(s.out)] (a past-end pointer) - ADDQ R9, 32(SP) - - // outBase += outPosition - ADDQ R11, R9 - -sequenceDecs_decodeSync_bmi2_main_loop: - MOVQ (SP), R12 - - // Fill bitreader to have enough for the offset and match length. - CMPQ BX, $0x08 - JL sequenceDecs_decodeSync_bmi2_fill_byte_by_byte - MOVQ DX, CX - SHRQ $0x03, CX - SUBQ CX, R12 - MOVQ (R12), AX - SUBQ CX, BX - ANDQ $0x07, DX - JMP sequenceDecs_decodeSync_bmi2_fill_end - -sequenceDecs_decodeSync_bmi2_fill_byte_by_byte: - CMPQ BX, $0x00 - JLE sequenceDecs_decodeSync_bmi2_fill_check_overread - CMPQ DX, $0x07 - JLE sequenceDecs_decodeSync_bmi2_fill_end - SHLQ $0x08, AX - SUBQ $0x01, R12 - SUBQ $0x01, BX - SUBQ $0x08, DX - MOVBQZX (R12), CX - ORQ CX, AX - JMP sequenceDecs_decodeSync_bmi2_fill_byte_by_byte - -sequenceDecs_decodeSync_bmi2_fill_check_overread: - CMPQ DX, $0x40 - JA error_overread - -sequenceDecs_decodeSync_bmi2_fill_end: - // Update offset - MOVQ $0x00000808, CX - BEXTRQ CX, R8, R13 - MOVQ AX, R14 - LEAQ (DX)(R13*1), CX - ROLQ CL, R14 - BZHIQ R13, R14, R14 - MOVQ CX, DX - MOVQ R8, CX - SHRQ $0x20, CX - ADDQ R14, CX - MOVQ CX, 8(SP) - - // Update match length - MOVQ $0x00000808, CX - BEXTRQ CX, DI, R13 - MOVQ AX, R14 - LEAQ (DX)(R13*1), CX - ROLQ CL, R14 - BZHIQ R13, R14, R14 - MOVQ CX, DX - MOVQ DI, CX - SHRQ $0x20, CX - ADDQ R14, CX - MOVQ CX, 16(SP) - - // Fill bitreader to have enough for the remaining - CMPQ BX, $0x08 - JL sequenceDecs_decodeSync_bmi2_fill_2_byte_by_byte - MOVQ DX, CX - SHRQ $0x03, CX - SUBQ CX, R12 - MOVQ (R12), AX - SUBQ CX, BX - ANDQ $0x07, DX - JMP sequenceDecs_decodeSync_bmi2_fill_2_end - -sequenceDecs_decodeSync_bmi2_fill_2_byte_by_byte: - CMPQ BX, $0x00 - JLE sequenceDecs_decodeSync_bmi2_fill_2_check_overread - CMPQ DX, $0x07 - JLE sequenceDecs_decodeSync_bmi2_fill_2_end - SHLQ $0x08, AX - SUBQ $0x01, R12 - SUBQ $0x01, BX - SUBQ $0x08, DX - MOVBQZX (R12), CX - ORQ CX, AX - JMP sequenceDecs_decodeSync_bmi2_fill_2_byte_by_byte - -sequenceDecs_decodeSync_bmi2_fill_2_check_overread: - CMPQ DX, $0x40 - JA error_overread - -sequenceDecs_decodeSync_bmi2_fill_2_end: - // Update literal length - MOVQ $0x00000808, CX - BEXTRQ CX, SI, R13 - MOVQ AX, R14 - LEAQ (DX)(R13*1), CX - ROLQ CL, R14 - BZHIQ R13, R14, R14 - MOVQ CX, DX - MOVQ SI, CX - SHRQ $0x20, CX - ADDQ R14, CX - MOVQ CX, 24(SP) - - // Fill bitreader for state updates - MOVQ R12, (SP) - MOVQ $0x00000808, CX - BEXTRQ CX, R8, R12 - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 - JZ sequenceDecs_decodeSync_bmi2_skip_update - LEAQ (SI)(DI*1), R13 - ADDQ R8, R13 - MOVBQZX R13, R13 - LEAQ (DX)(R13*1), CX - MOVQ AX, R14 - MOVQ CX, DX - ROLQ CL, R14 - BZHIQ R13, R14, R14 - - // Update Offset State - BZHIQ R8, R14, CX - SHRXQ R8, R14, R14 - MOVQ $0x00001010, R13 - BEXTRQ R13, R8, R8 - ADDQ CX, R8 - - // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX - MOVQ (CX)(R8*8), R8 - - // Update Match Length State - BZHIQ DI, R14, CX - SHRXQ DI, R14, R14 - MOVQ $0x00001010, R13 - BEXTRQ R13, DI, DI - ADDQ CX, DI - - // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX - MOVQ (CX)(DI*8), DI - - // Update Literal Length State - BZHIQ SI, R14, CX - MOVQ $0x00001010, R13 - BEXTRQ R13, SI, SI - ADDQ CX, SI - - // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX - MOVQ (CX)(SI*8), SI - -sequenceDecs_decodeSync_bmi2_skip_update: - // Adjust offset - MOVQ s+0(FP), CX - MOVQ 8(SP), R13 - CMPQ R12, $0x01 - JBE sequenceDecs_decodeSync_bmi2_adjust_offsetB_1_or_0 - MOVUPS 144(CX), X0 - MOVQ R13, 144(CX) - MOVUPS X0, 152(CX) - JMP sequenceDecs_decodeSync_bmi2_after_adjust - -sequenceDecs_decodeSync_bmi2_adjust_offsetB_1_or_0: - CMPQ 24(SP), $0x00000000 - JNE sequenceDecs_decodeSync_bmi2_adjust_offset_maybezero - INCQ R13 - JMP sequenceDecs_decodeSync_bmi2_adjust_offset_nonzero - -sequenceDecs_decodeSync_bmi2_adjust_offset_maybezero: - TESTQ R13, R13 - JNZ sequenceDecs_decodeSync_bmi2_adjust_offset_nonzero - MOVQ 144(CX), R13 - JMP sequenceDecs_decodeSync_bmi2_after_adjust - -sequenceDecs_decodeSync_bmi2_adjust_offset_nonzero: - MOVQ R13, R12 - XORQ R14, R14 - MOVQ $-1, R15 - CMPQ R13, $0x03 - CMOVQEQ R14, R12 - CMOVQEQ R15, R14 - ADDQ 144(CX)(R12*8), R14 - JNZ sequenceDecs_decodeSync_bmi2_adjust_temp_valid - MOVQ $0x00000001, R14 - -sequenceDecs_decodeSync_bmi2_adjust_temp_valid: - CMPQ R13, $0x01 - JZ sequenceDecs_decodeSync_bmi2_adjust_skip - MOVQ 152(CX), R12 - MOVQ R12, 160(CX) - -sequenceDecs_decodeSync_bmi2_adjust_skip: - MOVQ 144(CX), R12 - MOVQ R12, 152(CX) - MOVQ R14, 144(CX) - MOVQ R14, R13 - -sequenceDecs_decodeSync_bmi2_after_adjust: - MOVQ R13, 8(SP) - - // Check values - MOVQ 16(SP), CX - MOVQ 24(SP), R12 - LEAQ (CX)(R12*1), R14 - MOVQ s+0(FP), R15 - ADDQ R14, 256(R15) - MOVQ ctx+16(FP), R14 - SUBQ R12, 104(R14) - JS error_not_enough_literals - CMPQ CX, $0x00020002 - JA sequenceDecs_decodeSync_bmi2_error_match_len_too_big - TESTQ R13, R13 - JNZ sequenceDecs_decodeSync_bmi2_match_len_ofs_ok - TESTQ CX, CX - JNZ sequenceDecs_decodeSync_bmi2_error_match_len_ofs_mismatch - -sequenceDecs_decodeSync_bmi2_match_len_ofs_ok: - MOVQ 24(SP), CX - MOVQ 8(SP), R12 - MOVQ 16(SP), R13 - - // Check if we have enough space in s.out - LEAQ (CX)(R13*1), R14 - ADDQ R9, R14 - CMPQ R14, 32(SP) - JA error_not_enough_space - - // Copy literals - TESTQ CX, CX - JZ check_offset - XORQ R14, R14 - -copy_1: - MOVUPS (R10)(R14*1), X0 - MOVUPS X0, (R9)(R14*1) - ADDQ $0x10, R14 - CMPQ R14, CX - JB copy_1 - ADDQ CX, R10 - ADDQ CX, R9 - ADDQ CX, R11 - - // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: - MOVQ R11, CX - ADDQ 40(SP), CX - CMPQ R12, CX - JG error_match_off_too_big - CMPQ R12, 56(SP) - JG error_match_off_too_big - - // Copy match from history - MOVQ R12, CX - SUBQ R11, CX - JLS copy_match - MOVQ 48(SP), R14 - SUBQ CX, R14 - CMPQ R13, CX - JG copy_all_from_history - MOVQ R13, CX - SUBQ $0x10, CX - JB copy_4_small - -copy_4_loop: - MOVUPS (R14), X0 - MOVUPS X0, (R9) - ADDQ $0x10, R14 - ADDQ $0x10, R9 - SUBQ $0x10, CX - JAE copy_4_loop - LEAQ 16(R14)(CX*1), R14 - LEAQ 16(R9)(CX*1), R9 - MOVUPS -16(R14), X0 - MOVUPS X0, -16(R9) - JMP copy_4_end - -copy_4_small: - CMPQ R13, $0x03 - JE copy_4_move_3 - CMPQ R13, $0x08 - JB copy_4_move_4through7 - JMP copy_4_move_8through16 - -copy_4_move_3: - MOVW (R14), CX - MOVB 2(R14), R12 - MOVW CX, (R9) - MOVB R12, 2(R9) - ADDQ R13, R14 - ADDQ R13, R9 - JMP copy_4_end - -copy_4_move_4through7: - MOVL (R14), CX - MOVL -4(R14)(R13*1), R12 - MOVL CX, (R9) - MOVL R12, -4(R9)(R13*1) - ADDQ R13, R14 - ADDQ R13, R9 - JMP copy_4_end - -copy_4_move_8through16: - MOVQ (R14), CX - MOVQ -8(R14)(R13*1), R12 - MOVQ CX, (R9) - MOVQ R12, -8(R9)(R13*1) - ADDQ R13, R14 - ADDQ R13, R9 - -copy_4_end: - ADDQ R13, R11 - JMP handle_loop - JMP loop_finished - -copy_all_from_history: - MOVQ CX, R15 - SUBQ $0x10, R15 - JB copy_5_small - -copy_5_loop: - MOVUPS (R14), X0 - MOVUPS X0, (R9) - ADDQ $0x10, R14 - ADDQ $0x10, R9 - SUBQ $0x10, R15 - JAE copy_5_loop - LEAQ 16(R14)(R15*1), R14 - LEAQ 16(R9)(R15*1), R9 - MOVUPS -16(R14), X0 - MOVUPS X0, -16(R9) - JMP copy_5_end - -copy_5_small: - CMPQ CX, $0x03 - JE copy_5_move_3 - JB copy_5_move_1or2 - CMPQ CX, $0x08 - JB copy_5_move_4through7 - JMP copy_5_move_8through16 - -copy_5_move_1or2: - MOVB (R14), R15 - MOVB -1(R14)(CX*1), BP - MOVB R15, (R9) - MOVB BP, -1(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 - JMP copy_5_end - -copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (R9) - MOVB BP, 2(R9) - ADDQ CX, R14 - ADDQ CX, R9 - JMP copy_5_end - -copy_5_move_4through7: - MOVL (R14), R15 - MOVL -4(R14)(CX*1), BP - MOVL R15, (R9) - MOVL BP, -4(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 - JMP copy_5_end - -copy_5_move_8through16: - MOVQ (R14), R15 - MOVQ -8(R14)(CX*1), BP - MOVQ R15, (R9) - MOVQ BP, -8(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 - -copy_5_end: - ADDQ CX, R11 - SUBQ CX, R13 - - // Copy match from the current buffer -copy_match: - MOVQ R9, CX - SUBQ R12, CX - - // ml <= mo - CMPQ R13, R12 - JA copy_overlapping_match - - // Copy non-overlapping match - ADDQ R13, R11 - MOVQ R9, R12 - ADDQ R13, R9 - -copy_2: - MOVUPS (CX), X0 - MOVUPS X0, (R12) - ADDQ $0x10, CX - ADDQ $0x10, R12 - SUBQ $0x10, R13 - JHI copy_2 - JMP handle_loop - - // Copy overlapping match -copy_overlapping_match: - ADDQ R13, R11 - -copy_slow_3: - MOVB (CX), R12 - MOVB R12, (R9) - INCQ CX - INCQ R9 - DECQ R13 - JNZ copy_slow_3 - -handle_loop: - MOVQ ctx+16(FP), CX - DECQ 96(CX) - JNS sequenceDecs_decodeSync_bmi2_main_loop - -loop_finished: - MOVQ br+8(FP), CX - MOVQ AX, 24(CX) - MOVB DL, 32(CX) - MOVQ BX, 8(CX) - - // Update the context - MOVQ ctx+16(FP), AX - MOVQ R11, 136(AX) - MOVQ 144(AX), CX - SUBQ CX, R10 - MOVQ R10, 168(AX) - - // Return success - MOVQ $0x00000000, ret+24(FP) - RET - - // Return with match length error -sequenceDecs_decodeSync_bmi2_error_match_len_ofs_mismatch: - MOVQ 16(SP), AX - MOVQ ctx+16(FP), CX - MOVQ AX, 216(CX) - MOVQ $0x00000001, ret+24(FP) - RET - - // Return with match too long error -sequenceDecs_decodeSync_bmi2_error_match_len_too_big: - MOVQ ctx+16(FP), AX - MOVQ 16(SP), CX - MOVQ CX, 216(AX) - MOVQ $0x00000002, ret+24(FP) - RET - - // Return with match offset too long error -error_match_off_too_big: - MOVQ ctx+16(FP), AX - MOVQ 8(SP), CX - MOVQ CX, 224(AX) - MOVQ R11, 136(AX) - MOVQ $0x00000003, ret+24(FP) - RET - - // Return with not enough literals error -error_not_enough_literals: - MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX - MOVQ CX, 208(AX) - MOVQ $0x00000004, ret+24(FP) - RET - - // Return with overread error -error_overread: - MOVQ $0x00000006, ret+24(FP) - RET - - // Return with not enough output space error -error_not_enough_space: - MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX - MOVQ CX, 208(AX) - MOVQ 16(SP), CX - MOVQ CX, 216(AX) - MOVQ R11, 136(AX) - MOVQ $0x00000005, ret+24(FP) - RET - -// func sequenceDecs_decodeSync_safe_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int -// Requires: CMOV, SSE -TEXT ·sequenceDecs_decodeSync_safe_amd64(SB), $64-32 - MOVQ br+8(FP), CX - MOVQ 24(CX), DX - MOVBQZX 32(CX), BX - MOVQ (CX), AX - MOVQ 8(CX), SI - ADDQ SI, AX - MOVQ AX, (SP) - MOVQ ctx+16(FP), AX - MOVQ 72(AX), DI - MOVQ 80(AX), R8 - MOVQ 88(AX), R9 - XORQ CX, CX - MOVQ CX, 8(SP) - MOVQ CX, 16(SP) - MOVQ CX, 24(SP) - MOVQ 112(AX), R10 - MOVQ 128(AX), CX - MOVQ CX, 32(SP) - MOVQ 144(AX), R11 - MOVQ 136(AX), R12 - MOVQ 200(AX), CX - MOVQ CX, 56(SP) - MOVQ 176(AX), CX - MOVQ CX, 48(SP) - MOVQ 184(AX), AX - MOVQ AX, 40(SP) - MOVQ 40(SP), AX - ADDQ AX, 48(SP) - - // Calculate poiter to s.out[cap(s.out)] (a past-end pointer) - ADDQ R10, 32(SP) - - // outBase += outPosition - ADDQ R12, R10 - -sequenceDecs_decodeSync_safe_amd64_main_loop: - MOVQ (SP), R13 - - // Fill bitreader to have enough for the offset and match length. - CMPQ SI, $0x08 - JL sequenceDecs_decodeSync_safe_amd64_fill_byte_by_byte - MOVQ BX, AX - SHRQ $0x03, AX - SUBQ AX, R13 - MOVQ (R13), DX - SUBQ AX, SI - ANDQ $0x07, BX - JMP sequenceDecs_decodeSync_safe_amd64_fill_end - -sequenceDecs_decodeSync_safe_amd64_fill_byte_by_byte: - CMPQ SI, $0x00 - JLE sequenceDecs_decodeSync_safe_amd64_fill_check_overread - CMPQ BX, $0x07 - JLE sequenceDecs_decodeSync_safe_amd64_fill_end - SHLQ $0x08, DX - SUBQ $0x01, R13 - SUBQ $0x01, SI - SUBQ $0x08, BX - MOVBQZX (R13), AX - ORQ AX, DX - JMP sequenceDecs_decodeSync_safe_amd64_fill_byte_by_byte - -sequenceDecs_decodeSync_safe_amd64_fill_check_overread: - CMPQ BX, $0x40 - JA error_overread - -sequenceDecs_decodeSync_safe_amd64_fill_end: - // Update offset - MOVQ R9, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_safe_amd64_of_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_safe_amd64_of_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_safe_amd64_of_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_safe_amd64_of_update_zero: - MOVQ AX, 8(SP) - - // Update match length - MOVQ R8, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_safe_amd64_ml_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_safe_amd64_ml_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_safe_amd64_ml_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_safe_amd64_ml_update_zero: - MOVQ AX, 16(SP) - - // Fill bitreader to have enough for the remaining - CMPQ SI, $0x08 - JL sequenceDecs_decodeSync_safe_amd64_fill_2_byte_by_byte - MOVQ BX, AX - SHRQ $0x03, AX - SUBQ AX, R13 - MOVQ (R13), DX - SUBQ AX, SI - ANDQ $0x07, BX - JMP sequenceDecs_decodeSync_safe_amd64_fill_2_end - -sequenceDecs_decodeSync_safe_amd64_fill_2_byte_by_byte: - CMPQ SI, $0x00 - JLE sequenceDecs_decodeSync_safe_amd64_fill_2_check_overread - CMPQ BX, $0x07 - JLE sequenceDecs_decodeSync_safe_amd64_fill_2_end - SHLQ $0x08, DX - SUBQ $0x01, R13 - SUBQ $0x01, SI - SUBQ $0x08, BX - MOVBQZX (R13), AX - ORQ AX, DX - JMP sequenceDecs_decodeSync_safe_amd64_fill_2_byte_by_byte - -sequenceDecs_decodeSync_safe_amd64_fill_2_check_overread: - CMPQ BX, $0x40 - JA error_overread - -sequenceDecs_decodeSync_safe_amd64_fill_2_end: - // Update literal length - MOVQ DI, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_safe_amd64_ll_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_safe_amd64_ll_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_safe_amd64_ll_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_safe_amd64_ll_update_zero: - MOVQ AX, 24(SP) - - // Fill bitreader for state updates - MOVQ R13, (SP) - MOVQ R9, AX - SHRQ $0x08, AX - MOVBQZX AL, AX - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 - JZ sequenceDecs_decodeSync_safe_amd64_skip_update - - // Update Literal Length State - MOVBQZX DI, R13 - SHRQ $0x10, DI - MOVWQZX DI, DI - LEAQ (BX)(R13*1), CX - MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 - ADDQ R14, DI - - // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX - MOVQ (CX)(DI*8), DI - - // Update Match Length State - MOVBQZX R8, R13 - SHRQ $0x10, R8 - MOVWQZX R8, R8 - LEAQ (BX)(R13*1), CX - MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 - ADDQ R14, R8 - - // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX - MOVQ (CX)(R8*8), R8 - - // Update Offset State - MOVBQZX R9, R13 - SHRQ $0x10, R9 - MOVWQZX R9, R9 - LEAQ (BX)(R13*1), CX - MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 - ADDQ R14, R9 - - // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX - MOVQ (CX)(R9*8), R9 - -sequenceDecs_decodeSync_safe_amd64_skip_update: - // Adjust offset - MOVQ s+0(FP), CX - MOVQ 8(SP), R13 - CMPQ AX, $0x01 - JBE sequenceDecs_decodeSync_safe_amd64_adjust_offsetB_1_or_0 - MOVUPS 144(CX), X0 - MOVQ R13, 144(CX) - MOVUPS X0, 152(CX) - JMP sequenceDecs_decodeSync_safe_amd64_after_adjust - -sequenceDecs_decodeSync_safe_amd64_adjust_offsetB_1_or_0: - CMPQ 24(SP), $0x00000000 - JNE sequenceDecs_decodeSync_safe_amd64_adjust_offset_maybezero - INCQ R13 - JMP sequenceDecs_decodeSync_safe_amd64_adjust_offset_nonzero - -sequenceDecs_decodeSync_safe_amd64_adjust_offset_maybezero: - TESTQ R13, R13 - JNZ sequenceDecs_decodeSync_safe_amd64_adjust_offset_nonzero - MOVQ 144(CX), R13 - JMP sequenceDecs_decodeSync_safe_amd64_after_adjust - -sequenceDecs_decodeSync_safe_amd64_adjust_offset_nonzero: - MOVQ R13, AX - XORQ R14, R14 - MOVQ $-1, R15 - CMPQ R13, $0x03 - CMOVQEQ R14, AX - CMOVQEQ R15, R14 - ADDQ 144(CX)(AX*8), R14 - JNZ sequenceDecs_decodeSync_safe_amd64_adjust_temp_valid - MOVQ $0x00000001, R14 - -sequenceDecs_decodeSync_safe_amd64_adjust_temp_valid: - CMPQ R13, $0x01 - JZ sequenceDecs_decodeSync_safe_amd64_adjust_skip - MOVQ 152(CX), AX - MOVQ AX, 160(CX) - -sequenceDecs_decodeSync_safe_amd64_adjust_skip: - MOVQ 144(CX), AX - MOVQ AX, 152(CX) - MOVQ R14, 144(CX) - MOVQ R14, R13 - -sequenceDecs_decodeSync_safe_amd64_after_adjust: - MOVQ R13, 8(SP) - - // Check values - MOVQ 16(SP), AX - MOVQ 24(SP), CX - LEAQ (AX)(CX*1), R14 - MOVQ s+0(FP), R15 - ADDQ R14, 256(R15) - MOVQ ctx+16(FP), R14 - SUBQ CX, 104(R14) - JS error_not_enough_literals - CMPQ AX, $0x00020002 - JA sequenceDecs_decodeSync_safe_amd64_error_match_len_too_big - TESTQ R13, R13 - JNZ sequenceDecs_decodeSync_safe_amd64_match_len_ofs_ok - TESTQ AX, AX - JNZ sequenceDecs_decodeSync_safe_amd64_error_match_len_ofs_mismatch - -sequenceDecs_decodeSync_safe_amd64_match_len_ofs_ok: - MOVQ 24(SP), AX - MOVQ 8(SP), CX - MOVQ 16(SP), R13 - - // Check if we have enough space in s.out - LEAQ (AX)(R13*1), R14 - ADDQ R10, R14 - CMPQ R14, 32(SP) - JA error_not_enough_space - - // Copy literals - TESTQ AX, AX - JZ check_offset - MOVQ AX, R14 - SUBQ $0x10, R14 - JB copy_1_small - -copy_1_loop: - MOVUPS (R11), X0 - MOVUPS X0, (R10) - ADDQ $0x10, R11 - ADDQ $0x10, R10 - SUBQ $0x10, R14 - JAE copy_1_loop - LEAQ 16(R11)(R14*1), R11 - LEAQ 16(R10)(R14*1), R10 - MOVUPS -16(R11), X0 - MOVUPS X0, -16(R10) - JMP copy_1_end - -copy_1_small: - CMPQ AX, $0x03 - JE copy_1_move_3 - JB copy_1_move_1or2 - CMPQ AX, $0x08 - JB copy_1_move_4through7 - JMP copy_1_move_8through16 - -copy_1_move_1or2: - MOVB (R11), R14 - MOVB -1(R11)(AX*1), R15 - MOVB R14, (R10) - MOVB R15, -1(R10)(AX*1) - ADDQ AX, R11 - ADDQ AX, R10 - JMP copy_1_end - -copy_1_move_3: - MOVW (R11), R14 - MOVB 2(R11), R15 - MOVW R14, (R10) - MOVB R15, 2(R10) - ADDQ AX, R11 - ADDQ AX, R10 - JMP copy_1_end - -copy_1_move_4through7: - MOVL (R11), R14 - MOVL -4(R11)(AX*1), R15 - MOVL R14, (R10) - MOVL R15, -4(R10)(AX*1) - ADDQ AX, R11 - ADDQ AX, R10 - JMP copy_1_end - -copy_1_move_8through16: - MOVQ (R11), R14 - MOVQ -8(R11)(AX*1), R15 - MOVQ R14, (R10) - MOVQ R15, -8(R10)(AX*1) - ADDQ AX, R11 - ADDQ AX, R10 - -copy_1_end: - ADDQ AX, R12 - - // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: - MOVQ R12, AX - ADDQ 40(SP), AX - CMPQ CX, AX - JG error_match_off_too_big - CMPQ CX, 56(SP) - JG error_match_off_too_big - - // Copy match from history - MOVQ CX, AX - SUBQ R12, AX - JLS copy_match - MOVQ 48(SP), R14 - SUBQ AX, R14 - CMPQ R13, AX - JG copy_all_from_history - MOVQ R13, AX - SUBQ $0x10, AX - JB copy_4_small - -copy_4_loop: - MOVUPS (R14), X0 - MOVUPS X0, (R10) - ADDQ $0x10, R14 - ADDQ $0x10, R10 - SUBQ $0x10, AX - JAE copy_4_loop - LEAQ 16(R14)(AX*1), R14 - LEAQ 16(R10)(AX*1), R10 - MOVUPS -16(R14), X0 - MOVUPS X0, -16(R10) - JMP copy_4_end - -copy_4_small: - CMPQ R13, $0x03 - JE copy_4_move_3 - CMPQ R13, $0x08 - JB copy_4_move_4through7 - JMP copy_4_move_8through16 - -copy_4_move_3: - MOVW (R14), AX - MOVB 2(R14), CL - MOVW AX, (R10) - MOVB CL, 2(R10) - ADDQ R13, R14 - ADDQ R13, R10 - JMP copy_4_end - -copy_4_move_4through7: - MOVL (R14), AX - MOVL -4(R14)(R13*1), CX - MOVL AX, (R10) - MOVL CX, -4(R10)(R13*1) - ADDQ R13, R14 - ADDQ R13, R10 - JMP copy_4_end - -copy_4_move_8through16: - MOVQ (R14), AX - MOVQ -8(R14)(R13*1), CX - MOVQ AX, (R10) - MOVQ CX, -8(R10)(R13*1) - ADDQ R13, R14 - ADDQ R13, R10 - -copy_4_end: - ADDQ R13, R12 - JMP handle_loop - JMP loop_finished - -copy_all_from_history: - MOVQ AX, R15 - SUBQ $0x10, R15 - JB copy_5_small - -copy_5_loop: - MOVUPS (R14), X0 - MOVUPS X0, (R10) - ADDQ $0x10, R14 - ADDQ $0x10, R10 - SUBQ $0x10, R15 - JAE copy_5_loop - LEAQ 16(R14)(R15*1), R14 - LEAQ 16(R10)(R15*1), R10 - MOVUPS -16(R14), X0 - MOVUPS X0, -16(R10) - JMP copy_5_end - -copy_5_small: - CMPQ AX, $0x03 - JE copy_5_move_3 - JB copy_5_move_1or2 - CMPQ AX, $0x08 - JB copy_5_move_4through7 - JMP copy_5_move_8through16 - -copy_5_move_1or2: - MOVB (R14), R15 - MOVB -1(R14)(AX*1), BP - MOVB R15, (R10) - MOVB BP, -1(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 - JMP copy_5_end - -copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (R10) - MOVB BP, 2(R10) - ADDQ AX, R14 - ADDQ AX, R10 - JMP copy_5_end - -copy_5_move_4through7: - MOVL (R14), R15 - MOVL -4(R14)(AX*1), BP - MOVL R15, (R10) - MOVL BP, -4(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 - JMP copy_5_end - -copy_5_move_8through16: - MOVQ (R14), R15 - MOVQ -8(R14)(AX*1), BP - MOVQ R15, (R10) - MOVQ BP, -8(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 - -copy_5_end: - ADDQ AX, R12 - SUBQ AX, R13 - - // Copy match from the current buffer -copy_match: - MOVQ R10, AX - SUBQ CX, AX - - // ml <= mo - CMPQ R13, CX - JA copy_overlapping_match - - // Copy non-overlapping match - ADDQ R13, R12 - MOVQ R13, CX - SUBQ $0x10, CX - JB copy_2_small - -copy_2_loop: - MOVUPS (AX), X0 - MOVUPS X0, (R10) - ADDQ $0x10, AX - ADDQ $0x10, R10 - SUBQ $0x10, CX - JAE copy_2_loop - LEAQ 16(AX)(CX*1), AX - LEAQ 16(R10)(CX*1), R10 - MOVUPS -16(AX), X0 - MOVUPS X0, -16(R10) - JMP copy_2_end - -copy_2_small: - CMPQ R13, $0x03 - JE copy_2_move_3 - JB copy_2_move_1or2 - CMPQ R13, $0x08 - JB copy_2_move_4through7 - JMP copy_2_move_8through16 - -copy_2_move_1or2: - MOVB (AX), CL - MOVB -1(AX)(R13*1), R14 - MOVB CL, (R10) - MOVB R14, -1(R10)(R13*1) - ADDQ R13, AX - ADDQ R13, R10 - JMP copy_2_end - -copy_2_move_3: - MOVW (AX), CX - MOVB 2(AX), R14 - MOVW CX, (R10) - MOVB R14, 2(R10) - ADDQ R13, AX - ADDQ R13, R10 - JMP copy_2_end - -copy_2_move_4through7: - MOVL (AX), CX - MOVL -4(AX)(R13*1), R14 - MOVL CX, (R10) - MOVL R14, -4(R10)(R13*1) - ADDQ R13, AX - ADDQ R13, R10 - JMP copy_2_end - -copy_2_move_8through16: - MOVQ (AX), CX - MOVQ -8(AX)(R13*1), R14 - MOVQ CX, (R10) - MOVQ R14, -8(R10)(R13*1) - ADDQ R13, AX - ADDQ R13, R10 - -copy_2_end: - JMP handle_loop - - // Copy overlapping match -copy_overlapping_match: - ADDQ R13, R12 - -copy_slow_3: - MOVB (AX), CL - MOVB CL, (R10) - INCQ AX - INCQ R10 - DECQ R13 - JNZ copy_slow_3 - -handle_loop: - MOVQ ctx+16(FP), AX - DECQ 96(AX) - JNS sequenceDecs_decodeSync_safe_amd64_main_loop - -loop_finished: - MOVQ br+8(FP), AX - MOVQ DX, 24(AX) - MOVB BL, 32(AX) - MOVQ SI, 8(AX) - - // Update the context - MOVQ ctx+16(FP), AX - MOVQ R12, 136(AX) - MOVQ 144(AX), CX - SUBQ CX, R11 - MOVQ R11, 168(AX) - - // Return success - MOVQ $0x00000000, ret+24(FP) - RET - - // Return with match length error -sequenceDecs_decodeSync_safe_amd64_error_match_len_ofs_mismatch: - MOVQ 16(SP), AX - MOVQ ctx+16(FP), CX - MOVQ AX, 216(CX) - MOVQ $0x00000001, ret+24(FP) - RET - - // Return with match too long error -sequenceDecs_decodeSync_safe_amd64_error_match_len_too_big: - MOVQ ctx+16(FP), AX - MOVQ 16(SP), CX - MOVQ CX, 216(AX) - MOVQ $0x00000002, ret+24(FP) - RET - - // Return with match offset too long error -error_match_off_too_big: - MOVQ ctx+16(FP), AX - MOVQ 8(SP), CX - MOVQ CX, 224(AX) - MOVQ R12, 136(AX) - MOVQ $0x00000003, ret+24(FP) - RET - - // Return with not enough literals error -error_not_enough_literals: - MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX - MOVQ CX, 208(AX) - MOVQ $0x00000004, ret+24(FP) - RET - - // Return with overread error -error_overread: - MOVQ $0x00000006, ret+24(FP) - RET - - // Return with not enough output space error -error_not_enough_space: - MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX - MOVQ CX, 208(AX) - MOVQ 16(SP), CX - MOVQ CX, 216(AX) - MOVQ R12, 136(AX) - MOVQ $0x00000005, ret+24(FP) - RET - -// func sequenceDecs_decodeSync_safe_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int -// Requires: BMI, BMI2, CMOV, SSE -TEXT ·sequenceDecs_decodeSync_safe_bmi2(SB), $64-32 - MOVQ br+8(FP), BX - MOVQ 24(BX), AX - MOVBQZX 32(BX), DX - MOVQ (BX), CX - MOVQ 8(BX), BX - ADDQ BX, CX - MOVQ CX, (SP) - MOVQ ctx+16(FP), CX - MOVQ 72(CX), SI - MOVQ 80(CX), DI - MOVQ 88(CX), R8 - XORQ R9, R9 - MOVQ R9, 8(SP) - MOVQ R9, 16(SP) - MOVQ R9, 24(SP) - MOVQ 112(CX), R9 - MOVQ 128(CX), R10 - MOVQ R10, 32(SP) - MOVQ 144(CX), R10 - MOVQ 136(CX), R11 - MOVQ 200(CX), R12 - MOVQ R12, 56(SP) - MOVQ 176(CX), R12 - MOVQ R12, 48(SP) - MOVQ 184(CX), CX - MOVQ CX, 40(SP) - MOVQ 40(SP), CX - ADDQ CX, 48(SP) - - // Calculate poiter to s.out[cap(s.out)] (a past-end pointer) - ADDQ R9, 32(SP) - - // outBase += outPosition - ADDQ R11, R9 - -sequenceDecs_decodeSync_safe_bmi2_main_loop: - MOVQ (SP), R12 - - // Fill bitreader to have enough for the offset and match length. - CMPQ BX, $0x08 - JL sequenceDecs_decodeSync_safe_bmi2_fill_byte_by_byte - MOVQ DX, CX - SHRQ $0x03, CX - SUBQ CX, R12 - MOVQ (R12), AX - SUBQ CX, BX - ANDQ $0x07, DX - JMP sequenceDecs_decodeSync_safe_bmi2_fill_end - -sequenceDecs_decodeSync_safe_bmi2_fill_byte_by_byte: - CMPQ BX, $0x00 - JLE sequenceDecs_decodeSync_safe_bmi2_fill_check_overread - CMPQ DX, $0x07 - JLE sequenceDecs_decodeSync_safe_bmi2_fill_end - SHLQ $0x08, AX - SUBQ $0x01, R12 - SUBQ $0x01, BX - SUBQ $0x08, DX - MOVBQZX (R12), CX - ORQ CX, AX - JMP sequenceDecs_decodeSync_safe_bmi2_fill_byte_by_byte - -sequenceDecs_decodeSync_safe_bmi2_fill_check_overread: - CMPQ DX, $0x40 - JA error_overread - -sequenceDecs_decodeSync_safe_bmi2_fill_end: - // Update offset - MOVQ $0x00000808, CX - BEXTRQ CX, R8, R13 - MOVQ AX, R14 - LEAQ (DX)(R13*1), CX - ROLQ CL, R14 - BZHIQ R13, R14, R14 - MOVQ CX, DX - MOVQ R8, CX - SHRQ $0x20, CX - ADDQ R14, CX - MOVQ CX, 8(SP) - - // Update match length - MOVQ $0x00000808, CX - BEXTRQ CX, DI, R13 - MOVQ AX, R14 - LEAQ (DX)(R13*1), CX - ROLQ CL, R14 - BZHIQ R13, R14, R14 - MOVQ CX, DX - MOVQ DI, CX - SHRQ $0x20, CX - ADDQ R14, CX - MOVQ CX, 16(SP) - - // Fill bitreader to have enough for the remaining - CMPQ BX, $0x08 - JL sequenceDecs_decodeSync_safe_bmi2_fill_2_byte_by_byte - MOVQ DX, CX - SHRQ $0x03, CX - SUBQ CX, R12 - MOVQ (R12), AX - SUBQ CX, BX - ANDQ $0x07, DX - JMP sequenceDecs_decodeSync_safe_bmi2_fill_2_end - -sequenceDecs_decodeSync_safe_bmi2_fill_2_byte_by_byte: - CMPQ BX, $0x00 - JLE sequenceDecs_decodeSync_safe_bmi2_fill_2_check_overread - CMPQ DX, $0x07 - JLE sequenceDecs_decodeSync_safe_bmi2_fill_2_end - SHLQ $0x08, AX - SUBQ $0x01, R12 - SUBQ $0x01, BX - SUBQ $0x08, DX - MOVBQZX (R12), CX - ORQ CX, AX - JMP sequenceDecs_decodeSync_safe_bmi2_fill_2_byte_by_byte - -sequenceDecs_decodeSync_safe_bmi2_fill_2_check_overread: - CMPQ DX, $0x40 - JA error_overread - -sequenceDecs_decodeSync_safe_bmi2_fill_2_end: - // Update literal length - MOVQ $0x00000808, CX - BEXTRQ CX, SI, R13 - MOVQ AX, R14 - LEAQ (DX)(R13*1), CX - ROLQ CL, R14 - BZHIQ R13, R14, R14 - MOVQ CX, DX - MOVQ SI, CX - SHRQ $0x20, CX - ADDQ R14, CX - MOVQ CX, 24(SP) - - // Fill bitreader for state updates - MOVQ R12, (SP) - MOVQ $0x00000808, CX - BEXTRQ CX, R8, R12 - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 - JZ sequenceDecs_decodeSync_safe_bmi2_skip_update - LEAQ (SI)(DI*1), R13 - ADDQ R8, R13 - MOVBQZX R13, R13 - LEAQ (DX)(R13*1), CX - MOVQ AX, R14 - MOVQ CX, DX - ROLQ CL, R14 - BZHIQ R13, R14, R14 - - // Update Offset State - BZHIQ R8, R14, CX - SHRXQ R8, R14, R14 - MOVQ $0x00001010, R13 - BEXTRQ R13, R8, R8 - ADDQ CX, R8 - - // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX - MOVQ (CX)(R8*8), R8 - - // Update Match Length State - BZHIQ DI, R14, CX - SHRXQ DI, R14, R14 - MOVQ $0x00001010, R13 - BEXTRQ R13, DI, DI - ADDQ CX, DI - - // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX - MOVQ (CX)(DI*8), DI - - // Update Literal Length State - BZHIQ SI, R14, CX - MOVQ $0x00001010, R13 - BEXTRQ R13, SI, SI - ADDQ CX, SI - - // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX - MOVQ (CX)(SI*8), SI - -sequenceDecs_decodeSync_safe_bmi2_skip_update: - // Adjust offset - MOVQ s+0(FP), CX - MOVQ 8(SP), R13 - CMPQ R12, $0x01 - JBE sequenceDecs_decodeSync_safe_bmi2_adjust_offsetB_1_or_0 - MOVUPS 144(CX), X0 - MOVQ R13, 144(CX) - MOVUPS X0, 152(CX) - JMP sequenceDecs_decodeSync_safe_bmi2_after_adjust - -sequenceDecs_decodeSync_safe_bmi2_adjust_offsetB_1_or_0: - CMPQ 24(SP), $0x00000000 - JNE sequenceDecs_decodeSync_safe_bmi2_adjust_offset_maybezero - INCQ R13 - JMP sequenceDecs_decodeSync_safe_bmi2_adjust_offset_nonzero - -sequenceDecs_decodeSync_safe_bmi2_adjust_offset_maybezero: - TESTQ R13, R13 - JNZ sequenceDecs_decodeSync_safe_bmi2_adjust_offset_nonzero - MOVQ 144(CX), R13 - JMP sequenceDecs_decodeSync_safe_bmi2_after_adjust - -sequenceDecs_decodeSync_safe_bmi2_adjust_offset_nonzero: - MOVQ R13, R12 - XORQ R14, R14 - MOVQ $-1, R15 - CMPQ R13, $0x03 - CMOVQEQ R14, R12 - CMOVQEQ R15, R14 - ADDQ 144(CX)(R12*8), R14 - JNZ sequenceDecs_decodeSync_safe_bmi2_adjust_temp_valid - MOVQ $0x00000001, R14 - -sequenceDecs_decodeSync_safe_bmi2_adjust_temp_valid: - CMPQ R13, $0x01 - JZ sequenceDecs_decodeSync_safe_bmi2_adjust_skip - MOVQ 152(CX), R12 - MOVQ R12, 160(CX) - -sequenceDecs_decodeSync_safe_bmi2_adjust_skip: - MOVQ 144(CX), R12 - MOVQ R12, 152(CX) - MOVQ R14, 144(CX) - MOVQ R14, R13 - -sequenceDecs_decodeSync_safe_bmi2_after_adjust: - MOVQ R13, 8(SP) - - // Check values - MOVQ 16(SP), CX - MOVQ 24(SP), R12 - LEAQ (CX)(R12*1), R14 - MOVQ s+0(FP), R15 - ADDQ R14, 256(R15) - MOVQ ctx+16(FP), R14 - SUBQ R12, 104(R14) - JS error_not_enough_literals - CMPQ CX, $0x00020002 - JA sequenceDecs_decodeSync_safe_bmi2_error_match_len_too_big - TESTQ R13, R13 - JNZ sequenceDecs_decodeSync_safe_bmi2_match_len_ofs_ok - TESTQ CX, CX - JNZ sequenceDecs_decodeSync_safe_bmi2_error_match_len_ofs_mismatch - -sequenceDecs_decodeSync_safe_bmi2_match_len_ofs_ok: - MOVQ 24(SP), CX - MOVQ 8(SP), R12 - MOVQ 16(SP), R13 - - // Check if we have enough space in s.out - LEAQ (CX)(R13*1), R14 - ADDQ R9, R14 - CMPQ R14, 32(SP) - JA error_not_enough_space - - // Copy literals - TESTQ CX, CX - JZ check_offset - MOVQ CX, R14 - SUBQ $0x10, R14 - JB copy_1_small - -copy_1_loop: - MOVUPS (R10), X0 - MOVUPS X0, (R9) - ADDQ $0x10, R10 - ADDQ $0x10, R9 - SUBQ $0x10, R14 - JAE copy_1_loop - LEAQ 16(R10)(R14*1), R10 - LEAQ 16(R9)(R14*1), R9 - MOVUPS -16(R10), X0 - MOVUPS X0, -16(R9) - JMP copy_1_end - -copy_1_small: - CMPQ CX, $0x03 - JE copy_1_move_3 - JB copy_1_move_1or2 - CMPQ CX, $0x08 - JB copy_1_move_4through7 - JMP copy_1_move_8through16 - -copy_1_move_1or2: - MOVB (R10), R14 - MOVB -1(R10)(CX*1), R15 - MOVB R14, (R9) - MOVB R15, -1(R9)(CX*1) - ADDQ CX, R10 - ADDQ CX, R9 - JMP copy_1_end - -copy_1_move_3: - MOVW (R10), R14 - MOVB 2(R10), R15 - MOVW R14, (R9) - MOVB R15, 2(R9) - ADDQ CX, R10 - ADDQ CX, R9 - JMP copy_1_end - -copy_1_move_4through7: - MOVL (R10), R14 - MOVL -4(R10)(CX*1), R15 - MOVL R14, (R9) - MOVL R15, -4(R9)(CX*1) - ADDQ CX, R10 - ADDQ CX, R9 - JMP copy_1_end - -copy_1_move_8through16: - MOVQ (R10), R14 - MOVQ -8(R10)(CX*1), R15 - MOVQ R14, (R9) - MOVQ R15, -8(R9)(CX*1) - ADDQ CX, R10 - ADDQ CX, R9 - -copy_1_end: - ADDQ CX, R11 - - // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: - MOVQ R11, CX - ADDQ 40(SP), CX - CMPQ R12, CX - JG error_match_off_too_big - CMPQ R12, 56(SP) - JG error_match_off_too_big - - // Copy match from history - MOVQ R12, CX - SUBQ R11, CX - JLS copy_match - MOVQ 48(SP), R14 - SUBQ CX, R14 - CMPQ R13, CX - JG copy_all_from_history - MOVQ R13, CX - SUBQ $0x10, CX - JB copy_4_small - -copy_4_loop: - MOVUPS (R14), X0 - MOVUPS X0, (R9) - ADDQ $0x10, R14 - ADDQ $0x10, R9 - SUBQ $0x10, CX - JAE copy_4_loop - LEAQ 16(R14)(CX*1), R14 - LEAQ 16(R9)(CX*1), R9 - MOVUPS -16(R14), X0 - MOVUPS X0, -16(R9) - JMP copy_4_end - -copy_4_small: - CMPQ R13, $0x03 - JE copy_4_move_3 - CMPQ R13, $0x08 - JB copy_4_move_4through7 - JMP copy_4_move_8through16 - -copy_4_move_3: - MOVW (R14), CX - MOVB 2(R14), R12 - MOVW CX, (R9) - MOVB R12, 2(R9) - ADDQ R13, R14 - ADDQ R13, R9 - JMP copy_4_end - -copy_4_move_4through7: - MOVL (R14), CX - MOVL -4(R14)(R13*1), R12 - MOVL CX, (R9) - MOVL R12, -4(R9)(R13*1) - ADDQ R13, R14 - ADDQ R13, R9 - JMP copy_4_end - -copy_4_move_8through16: - MOVQ (R14), CX - MOVQ -8(R14)(R13*1), R12 - MOVQ CX, (R9) - MOVQ R12, -8(R9)(R13*1) - ADDQ R13, R14 - ADDQ R13, R9 - -copy_4_end: - ADDQ R13, R11 - JMP handle_loop - JMP loop_finished - -copy_all_from_history: - MOVQ CX, R15 - SUBQ $0x10, R15 - JB copy_5_small - -copy_5_loop: - MOVUPS (R14), X0 - MOVUPS X0, (R9) - ADDQ $0x10, R14 - ADDQ $0x10, R9 - SUBQ $0x10, R15 - JAE copy_5_loop - LEAQ 16(R14)(R15*1), R14 - LEAQ 16(R9)(R15*1), R9 - MOVUPS -16(R14), X0 - MOVUPS X0, -16(R9) - JMP copy_5_end - -copy_5_small: - CMPQ CX, $0x03 - JE copy_5_move_3 - JB copy_5_move_1or2 - CMPQ CX, $0x08 - JB copy_5_move_4through7 - JMP copy_5_move_8through16 - -copy_5_move_1or2: - MOVB (R14), R15 - MOVB -1(R14)(CX*1), BP - MOVB R15, (R9) - MOVB BP, -1(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 - JMP copy_5_end - -copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (R9) - MOVB BP, 2(R9) - ADDQ CX, R14 - ADDQ CX, R9 - JMP copy_5_end - -copy_5_move_4through7: - MOVL (R14), R15 - MOVL -4(R14)(CX*1), BP - MOVL R15, (R9) - MOVL BP, -4(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 - JMP copy_5_end - -copy_5_move_8through16: - MOVQ (R14), R15 - MOVQ -8(R14)(CX*1), BP - MOVQ R15, (R9) - MOVQ BP, -8(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 - -copy_5_end: - ADDQ CX, R11 - SUBQ CX, R13 - - // Copy match from the current buffer -copy_match: - MOVQ R9, CX - SUBQ R12, CX - - // ml <= mo - CMPQ R13, R12 - JA copy_overlapping_match - - // Copy non-overlapping match - ADDQ R13, R11 - MOVQ R13, R12 - SUBQ $0x10, R12 - JB copy_2_small - -copy_2_loop: - MOVUPS (CX), X0 - MOVUPS X0, (R9) - ADDQ $0x10, CX - ADDQ $0x10, R9 - SUBQ $0x10, R12 - JAE copy_2_loop - LEAQ 16(CX)(R12*1), CX - LEAQ 16(R9)(R12*1), R9 - MOVUPS -16(CX), X0 - MOVUPS X0, -16(R9) - JMP copy_2_end - -copy_2_small: - CMPQ R13, $0x03 - JE copy_2_move_3 - JB copy_2_move_1or2 - CMPQ R13, $0x08 - JB copy_2_move_4through7 - JMP copy_2_move_8through16 - -copy_2_move_1or2: - MOVB (CX), R12 - MOVB -1(CX)(R13*1), R14 - MOVB R12, (R9) - MOVB R14, -1(R9)(R13*1) - ADDQ R13, CX - ADDQ R13, R9 - JMP copy_2_end - -copy_2_move_3: - MOVW (CX), R12 - MOVB 2(CX), R14 - MOVW R12, (R9) - MOVB R14, 2(R9) - ADDQ R13, CX - ADDQ R13, R9 - JMP copy_2_end - -copy_2_move_4through7: - MOVL (CX), R12 - MOVL -4(CX)(R13*1), R14 - MOVL R12, (R9) - MOVL R14, -4(R9)(R13*1) - ADDQ R13, CX - ADDQ R13, R9 - JMP copy_2_end - -copy_2_move_8through16: - MOVQ (CX), R12 - MOVQ -8(CX)(R13*1), R14 - MOVQ R12, (R9) - MOVQ R14, -8(R9)(R13*1) - ADDQ R13, CX - ADDQ R13, R9 - -copy_2_end: - JMP handle_loop - - // Copy overlapping match -copy_overlapping_match: - ADDQ R13, R11 - -copy_slow_3: - MOVB (CX), R12 - MOVB R12, (R9) - INCQ CX - INCQ R9 - DECQ R13 - JNZ copy_slow_3 - -handle_loop: - MOVQ ctx+16(FP), CX - DECQ 96(CX) - JNS sequenceDecs_decodeSync_safe_bmi2_main_loop - -loop_finished: - MOVQ br+8(FP), CX - MOVQ AX, 24(CX) - MOVB DL, 32(CX) - MOVQ BX, 8(CX) - - // Update the context - MOVQ ctx+16(FP), AX - MOVQ R11, 136(AX) - MOVQ 144(AX), CX - SUBQ CX, R10 - MOVQ R10, 168(AX) - - // Return success - MOVQ $0x00000000, ret+24(FP) - RET - - // Return with match length error -sequenceDecs_decodeSync_safe_bmi2_error_match_len_ofs_mismatch: - MOVQ 16(SP), AX - MOVQ ctx+16(FP), CX - MOVQ AX, 216(CX) - MOVQ $0x00000001, ret+24(FP) - RET - - // Return with match too long error -sequenceDecs_decodeSync_safe_bmi2_error_match_len_too_big: - MOVQ ctx+16(FP), AX - MOVQ 16(SP), CX - MOVQ CX, 216(AX) - MOVQ $0x00000002, ret+24(FP) - RET - - // Return with match offset too long error -error_match_off_too_big: - MOVQ ctx+16(FP), AX - MOVQ 8(SP), CX - MOVQ CX, 224(AX) - MOVQ R11, 136(AX) - MOVQ $0x00000003, ret+24(FP) - RET - - // Return with not enough literals error -error_not_enough_literals: - MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX - MOVQ CX, 208(AX) - MOVQ $0x00000004, ret+24(FP) - RET - - // Return with overread error -error_overread: - MOVQ $0x00000006, ret+24(FP) - RET - - // Return with not enough output space error -error_not_enough_space: - MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX - MOVQ CX, 208(AX) - MOVQ 16(SP), CX - MOVQ CX, 216(AX) - MOVQ R11, 136(AX) - MOVQ $0x00000005, ret+24(FP) - RET diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_generic.go b/vendor/github.com/klauspost/compress/zstd/seqdec_generic.go deleted file mode 100644 index 2fb35b788..000000000 --- a/vendor/github.com/klauspost/compress/zstd/seqdec_generic.go +++ /dev/null @@ -1,237 +0,0 @@ -//go:build !amd64 || appengine || !gc || noasm -// +build !amd64 appengine !gc noasm - -package zstd - -import ( - "fmt" - "io" -) - -// decode sequences from the stream with the provided history but without dictionary. -func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) { - return false, nil -} - -// decode sequences from the stream without the provided history. -func (s *sequenceDecs) decode(seqs []seqVals) error { - br := s.br - - // Grab full sizes tables, to avoid bounds checks. - llTable, mlTable, ofTable := s.litLengths.fse.dt[:maxTablesize], s.matchLengths.fse.dt[:maxTablesize], s.offsets.fse.dt[:maxTablesize] - llState, mlState, ofState := s.litLengths.state.state, s.matchLengths.state.state, s.offsets.state.state - s.seqSize = 0 - litRemain := len(s.literals) - - maxBlockSize := maxCompressedBlockSize - if s.windowSize < maxBlockSize { - maxBlockSize = s.windowSize - } - for i := range seqs { - var ll, mo, ml int - if len(br.in) > 4+((maxOffsetBits+16+16)>>3) { - // inlined function: - // ll, mo, ml = s.nextFast(br, llState, mlState, ofState) - - // Final will not read from stream. - var llB, mlB, moB uint8 - ll, llB = llState.final() - ml, mlB = mlState.final() - mo, moB = ofState.final() - - // extra bits are stored in reverse order. - br.fillFast() - mo += br.getBits(moB) - if s.maxBits > 32 { - br.fillFast() - } - ml += br.getBits(mlB) - ll += br.getBits(llB) - - if moB > 1 { - s.prevOffset[2] = s.prevOffset[1] - s.prevOffset[1] = s.prevOffset[0] - s.prevOffset[0] = mo - } else { - // mo = s.adjustOffset(mo, ll, moB) - // Inlined for rather big speedup - if ll == 0 { - // There is an exception though, when current sequence's literals_length = 0. - // In this case, repeated offsets are shifted by one, so an offset_value of 1 means Repeated_Offset2, - // an offset_value of 2 means Repeated_Offset3, and an offset_value of 3 means Repeated_Offset1 - 1_byte. - mo++ - } - - if mo == 0 { - mo = s.prevOffset[0] - } else { - var temp int - if mo == 3 { - temp = s.prevOffset[0] - 1 - } else { - temp = s.prevOffset[mo] - } - - if temp == 0 { - // 0 is not valid; input is corrupted; force offset to 1 - println("WARNING: temp was 0") - temp = 1 - } - - if mo != 1 { - s.prevOffset[2] = s.prevOffset[1] - } - s.prevOffset[1] = s.prevOffset[0] - s.prevOffset[0] = temp - mo = temp - } - } - br.fillFast() - } else { - if br.overread() { - if debugDecoder { - printf("reading sequence %d, exceeded available data\n", i) - } - return io.ErrUnexpectedEOF - } - ll, mo, ml = s.next(br, llState, mlState, ofState) - br.fill() - } - - if debugSequences { - println("Seq", i, "Litlen:", ll, "mo:", mo, "(abs) ml:", ml) - } - // Evaluate. - // We might be doing this async, so do it early. - if mo == 0 && ml > 0 { - return fmt.Errorf("zero matchoff and matchlen (%d) > 0", ml) - } - if ml > maxMatchLen { - return fmt.Errorf("match len (%d) bigger than max allowed length", ml) - } - s.seqSize += ll + ml - if s.seqSize > maxBlockSize { - return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) - } - litRemain -= ll - if litRemain < 0 { - return fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", ll, litRemain+ll) - } - seqs[i] = seqVals{ - ll: ll, - ml: ml, - mo: mo, - } - if i == len(seqs)-1 { - // This is the last sequence, so we shouldn't update state. - break - } - - // Manually inlined, ~ 5-20% faster - // Update all 3 states at once. Approx 20% faster. - nBits := llState.nbBits() + mlState.nbBits() + ofState.nbBits() - if nBits == 0 { - llState = llTable[llState.newState()&maxTableMask] - mlState = mlTable[mlState.newState()&maxTableMask] - ofState = ofTable[ofState.newState()&maxTableMask] - } else { - bits := br.get32BitsFast(nBits) - lowBits := uint16(bits >> ((ofState.nbBits() + mlState.nbBits()) & 31)) - llState = llTable[(llState.newState()+lowBits)&maxTableMask] - - lowBits = uint16(bits >> (ofState.nbBits() & 31)) - lowBits &= bitMask[mlState.nbBits()&15] - mlState = mlTable[(mlState.newState()+lowBits)&maxTableMask] - - lowBits = uint16(bits) & bitMask[ofState.nbBits()&15] - ofState = ofTable[(ofState.newState()+lowBits)&maxTableMask] - } - } - s.seqSize += litRemain - if s.seqSize > maxBlockSize { - return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) - } - err := br.close() - if err != nil { - printf("Closing sequences: %v, %+v\n", err, *br) - } - return err -} - -// executeSimple handles cases when a dictionary is not used. -func (s *sequenceDecs) executeSimple(seqs []seqVals, hist []byte) error { - // Ensure we have enough output size... - if len(s.out)+s.seqSize > cap(s.out) { - addBytes := s.seqSize + len(s.out) - s.out = append(s.out, make([]byte, addBytes)...) - s.out = s.out[:len(s.out)-addBytes] - } - - if debugDecoder { - printf("Execute %d seqs with literals: %d into %d bytes\n", len(seqs), len(s.literals), s.seqSize) - } - - var t = len(s.out) - out := s.out[:t+s.seqSize] - - for _, seq := range seqs { - // Add literals - copy(out[t:], s.literals[:seq.ll]) - t += seq.ll - s.literals = s.literals[seq.ll:] - - // Malformed input - if seq.mo > t+len(hist) || seq.mo > s.windowSize { - return fmt.Errorf("match offset (%d) bigger than current history (%d)", seq.mo, t+len(hist)) - } - - // Copy from history. - if v := seq.mo - t; v > 0 { - // v is the start position in history from end. - start := len(hist) - v - if seq.ml > v { - // Some goes into the current block. - // Copy remainder of history - copy(out[t:], hist[start:]) - t += v - seq.ml -= v - } else { - copy(out[t:], hist[start:start+seq.ml]) - t += seq.ml - continue - } - } - - // We must be in the current buffer now - if seq.ml > 0 { - start := t - seq.mo - if seq.ml <= t-start { - // No overlap - copy(out[t:], out[start:start+seq.ml]) - t += seq.ml - } else { - // Overlapping copy - // Extend destination slice and copy one byte at the time. - src := out[start : start+seq.ml] - dst := out[t:] - dst = dst[:len(src)] - t += len(src) - // Destination is the space we just added. - for i := range src { - dst[i] = src[i] - } - } - } - } - // Add final literals - copy(out[t:], s.literals) - if debugDecoder { - t += len(s.literals) - if t != len(out) { - panic(fmt.Errorf("length mismatch, want %d, got %d, ss: %d", len(out), t, s.seqSize)) - } - } - s.out = out - - return nil -} diff --git a/vendor/github.com/klauspost/compress/zstd/seqenc.go b/vendor/github.com/klauspost/compress/zstd/seqenc.go deleted file mode 100644 index 8014174a7..000000000 --- a/vendor/github.com/klauspost/compress/zstd/seqenc.go +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import "math/bits" - -type seqCoders struct { - llEnc, ofEnc, mlEnc *fseEncoder - llPrev, ofPrev, mlPrev *fseEncoder -} - -// swap coders with another (block). -func (s *seqCoders) swap(other *seqCoders) { - *s, *other = *other, *s -} - -// setPrev will update the previous encoders to the actually used ones -// and make sure a fresh one is in the main slot. -func (s *seqCoders) setPrev(ll, ml, of *fseEncoder) { - compareSwap := func(used *fseEncoder, current, prev **fseEncoder) { - // We used the new one, more current to history and reuse the previous history - if *current == used { - *prev, *current = *current, *prev - c := *current - p := *prev - c.reUsed = false - p.reUsed = true - return - } - if used == *prev { - return - } - // Ensure we cannot reuse by accident - prevEnc := *prev - prevEnc.symbolLen = 0 - } - compareSwap(ll, &s.llEnc, &s.llPrev) - compareSwap(ml, &s.mlEnc, &s.mlPrev) - compareSwap(of, &s.ofEnc, &s.ofPrev) -} - -func highBit(val uint32) (n uint32) { - return uint32(bits.Len32(val) - 1) -} - -var llCodeTable = [64]byte{0, 1, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 16, 17, 17, 18, 18, 19, 19, - 20, 20, 20, 20, 21, 21, 21, 21, - 22, 22, 22, 22, 22, 22, 22, 22, - 23, 23, 23, 23, 23, 23, 23, 23, - 24, 24, 24, 24, 24, 24, 24, 24, - 24, 24, 24, 24, 24, 24, 24, 24} - -// Up to 6 bits -const maxLLCode = 35 - -// llBitsTable translates from ll code to number of bits. -var llBitsTable = [maxLLCode + 1]byte{ - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 1, 1, 1, 1, 2, 2, 3, 3, - 4, 6, 7, 8, 9, 10, 11, 12, - 13, 14, 15, 16} - -// llCode returns the code that represents the literal length requested. -func llCode(litLength uint32) uint8 { - const llDeltaCode = 19 - if litLength <= 63 { - // Compiler insists on bounds check (Go 1.12) - return llCodeTable[litLength&63] - } - return uint8(highBit(litLength)) + llDeltaCode -} - -var mlCodeTable = [128]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, - 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 36, 36, 37, 37, 37, 37, - 38, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39, - 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, - 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, - 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, - 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42} - -// Up to 6 bits -const maxMLCode = 52 - -// mlBitsTable translates from ml code to number of bits. -var mlBitsTable = [maxMLCode + 1]byte{ - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 1, 1, 1, 1, 2, 2, 3, 3, - 4, 4, 5, 7, 8, 9, 10, 11, - 12, 13, 14, 15, 16} - -// note : mlBase = matchLength - MINMATCH; -// because it's the format it's stored in seqStore->sequences -func mlCode(mlBase uint32) uint8 { - const mlDeltaCode = 36 - if mlBase <= 127 { - // Compiler insists on bounds check (Go 1.12) - return mlCodeTable[mlBase&127] - } - return uint8(highBit(mlBase)) + mlDeltaCode -} - -func ofCode(offset uint32) uint8 { - // A valid offset will always be > 0. - return uint8(bits.Len32(offset) - 1) -} diff --git a/vendor/github.com/klauspost/compress/zstd/snappy.go b/vendor/github.com/klauspost/compress/zstd/snappy.go deleted file mode 100644 index ec13594e8..000000000 --- a/vendor/github.com/klauspost/compress/zstd/snappy.go +++ /dev/null @@ -1,434 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "encoding/binary" - "errors" - "hash/crc32" - "io" - - "github.com/klauspost/compress/huff0" - snappy "github.com/klauspost/compress/internal/snapref" -) - -const ( - snappyTagLiteral = 0x00 - snappyTagCopy1 = 0x01 - snappyTagCopy2 = 0x02 - snappyTagCopy4 = 0x03 -) - -const ( - snappyChecksumSize = 4 - snappyMagicBody = "sNaPpY" - - // snappyMaxBlockSize is the maximum size of the input to encodeBlock. It is not - // part of the wire format per se, but some parts of the encoder assume - // that an offset fits into a uint16. - // - // Also, for the framing format (Writer type instead of Encode function), - // https://github.com/google/snappy/blob/master/framing_format.txt says - // that "the uncompressed data in a chunk must be no longer than 65536 - // bytes". - snappyMaxBlockSize = 65536 - - // snappyMaxEncodedLenOfMaxBlockSize equals MaxEncodedLen(snappyMaxBlockSize), but is - // hard coded to be a const instead of a variable, so that obufLen can also - // be a const. Their equivalence is confirmed by - // TestMaxEncodedLenOfMaxBlockSize. - snappyMaxEncodedLenOfMaxBlockSize = 76490 -) - -const ( - chunkTypeCompressedData = 0x00 - chunkTypeUncompressedData = 0x01 - chunkTypePadding = 0xfe - chunkTypeStreamIdentifier = 0xff -) - -var ( - // ErrSnappyCorrupt reports that the input is invalid. - ErrSnappyCorrupt = errors.New("snappy: corrupt input") - // ErrSnappyTooLarge reports that the uncompressed length is too large. - ErrSnappyTooLarge = errors.New("snappy: decoded block is too large") - // ErrSnappyUnsupported reports that the input isn't supported. - ErrSnappyUnsupported = errors.New("snappy: unsupported input") - - errUnsupportedLiteralLength = errors.New("snappy: unsupported literal length") -) - -// SnappyConverter can read SnappyConverter-compressed streams and convert them to zstd. -// Conversion is done by converting the stream directly from Snappy without intermediate -// full decoding. -// Therefore the compression ratio is much less than what can be done by a full decompression -// and compression, and a faulty Snappy stream may lead to a faulty Zstandard stream without -// any errors being generated. -// No CRC value is being generated and not all CRC values of the Snappy stream are checked. -// However, it provides really fast recompression of Snappy streams. -// The converter can be reused to avoid allocations, even after errors. -type SnappyConverter struct { - r io.Reader - err error - buf []byte - block *blockEnc -} - -// Convert the Snappy stream supplied in 'in' and write the zStandard stream to 'w'. -// If any error is detected on the Snappy stream it is returned. -// The number of bytes written is returned. -func (r *SnappyConverter) Convert(in io.Reader, w io.Writer) (int64, error) { - initPredefined() - r.err = nil - r.r = in - if r.block == nil { - r.block = &blockEnc{} - r.block.init() - } - r.block.initNewEncode() - if len(r.buf) != snappyMaxEncodedLenOfMaxBlockSize+snappyChecksumSize { - r.buf = make([]byte, snappyMaxEncodedLenOfMaxBlockSize+snappyChecksumSize) - } - r.block.litEnc.Reuse = huff0.ReusePolicyNone - var written int64 - var readHeader bool - { - header := frameHeader{WindowSize: snappyMaxBlockSize}.appendTo(r.buf[:0]) - - var n int - n, r.err = w.Write(header) - if r.err != nil { - return written, r.err - } - written += int64(n) - } - - for { - if !r.readFull(r.buf[:4], true) { - // Add empty last block - r.block.reset(nil) - r.block.last = true - err := r.block.encodeLits(r.block.literals, false) - if err != nil { - return written, err - } - n, err := w.Write(r.block.output) - if err != nil { - return written, err - } - written += int64(n) - - return written, r.err - } - chunkType := r.buf[0] - if !readHeader { - if chunkType != chunkTypeStreamIdentifier { - println("chunkType != chunkTypeStreamIdentifier", chunkType) - r.err = ErrSnappyCorrupt - return written, r.err - } - readHeader = true - } - chunkLen := int(r.buf[1]) | int(r.buf[2])<<8 | int(r.buf[3])<<16 - if chunkLen > len(r.buf) { - println("chunkLen > len(r.buf)", chunkType) - r.err = ErrSnappyUnsupported - return written, r.err - } - - // The chunk types are specified at - // https://github.com/google/snappy/blob/master/framing_format.txt - switch chunkType { - case chunkTypeCompressedData: - // Section 4.2. Compressed data (chunk type 0x00). - if chunkLen < snappyChecksumSize { - println("chunkLen < snappyChecksumSize", chunkLen, snappyChecksumSize) - r.err = ErrSnappyCorrupt - return written, r.err - } - buf := r.buf[:chunkLen] - if !r.readFull(buf, false) { - return written, r.err - } - //checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 - buf = buf[snappyChecksumSize:] - - n, hdr, err := snappyDecodedLen(buf) - if err != nil { - r.err = err - return written, r.err - } - buf = buf[hdr:] - if n > snappyMaxBlockSize { - println("n > snappyMaxBlockSize", n, snappyMaxBlockSize) - r.err = ErrSnappyCorrupt - return written, r.err - } - r.block.reset(nil) - r.block.pushOffsets() - if err := decodeSnappy(r.block, buf); err != nil { - r.err = err - return written, r.err - } - if r.block.size+r.block.extraLits != n { - printf("invalid size, want %d, got %d\n", n, r.block.size+r.block.extraLits) - r.err = ErrSnappyCorrupt - return written, r.err - } - err = r.block.encode(nil, false, false) - switch err { - case errIncompressible: - r.block.popOffsets() - r.block.reset(nil) - r.block.literals, err = snappy.Decode(r.block.literals[:n], r.buf[snappyChecksumSize:chunkLen]) - if err != nil { - return written, err - } - err = r.block.encodeLits(r.block.literals, false) - if err != nil { - return written, err - } - case nil: - default: - return written, err - } - - n, r.err = w.Write(r.block.output) - if r.err != nil { - return written, err - } - written += int64(n) - continue - case chunkTypeUncompressedData: - if debugEncoder { - println("Uncompressed, chunklen", chunkLen) - } - // Section 4.3. Uncompressed data (chunk type 0x01). - if chunkLen < snappyChecksumSize { - println("chunkLen < snappyChecksumSize", chunkLen, snappyChecksumSize) - r.err = ErrSnappyCorrupt - return written, r.err - } - r.block.reset(nil) - buf := r.buf[:snappyChecksumSize] - if !r.readFull(buf, false) { - return written, r.err - } - checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 - // Read directly into r.decoded instead of via r.buf. - n := chunkLen - snappyChecksumSize - if n > snappyMaxBlockSize { - println("n > snappyMaxBlockSize", n, snappyMaxBlockSize) - r.err = ErrSnappyCorrupt - return written, r.err - } - r.block.literals = r.block.literals[:n] - if !r.readFull(r.block.literals, false) { - return written, r.err - } - if snappyCRC(r.block.literals) != checksum { - println("literals crc mismatch") - r.err = ErrSnappyCorrupt - return written, r.err - } - err := r.block.encodeLits(r.block.literals, false) - if err != nil { - return written, err - } - n, r.err = w.Write(r.block.output) - if r.err != nil { - return written, err - } - written += int64(n) - continue - - case chunkTypeStreamIdentifier: - if debugEncoder { - println("stream id", chunkLen, len(snappyMagicBody)) - } - // Section 4.1. Stream identifier (chunk type 0xff). - if chunkLen != len(snappyMagicBody) { - println("chunkLen != len(snappyMagicBody)", chunkLen, len(snappyMagicBody)) - r.err = ErrSnappyCorrupt - return written, r.err - } - if !r.readFull(r.buf[:len(snappyMagicBody)], false) { - return written, r.err - } - for i := 0; i < len(snappyMagicBody); i++ { - if r.buf[i] != snappyMagicBody[i] { - println("r.buf[i] != snappyMagicBody[i]", r.buf[i], snappyMagicBody[i], i) - r.err = ErrSnappyCorrupt - return written, r.err - } - } - continue - } - - if chunkType <= 0x7f { - // Section 4.5. Reserved unskippable chunks (chunk types 0x02-0x7f). - println("chunkType <= 0x7f") - r.err = ErrSnappyUnsupported - return written, r.err - } - // Section 4.4 Padding (chunk type 0xfe). - // Section 4.6. Reserved skippable chunks (chunk types 0x80-0xfd). - if !r.readFull(r.buf[:chunkLen], false) { - return written, r.err - } - } -} - -// decodeSnappy writes the decoding of src to dst. It assumes that the varint-encoded -// length of the decompressed bytes has already been read. -func decodeSnappy(blk *blockEnc, src []byte) error { - //decodeRef(make([]byte, snappyMaxBlockSize), src) - var s, length int - lits := blk.extraLits - var offset uint32 - for s < len(src) { - switch src[s] & 0x03 { - case snappyTagLiteral: - x := uint32(src[s] >> 2) - switch { - case x < 60: - s++ - case x == 60: - s += 2 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - println("uint(s) > uint(len(src)", s, src) - return ErrSnappyCorrupt - } - x = uint32(src[s-1]) - case x == 61: - s += 3 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - println("uint(s) > uint(len(src)", s, src) - return ErrSnappyCorrupt - } - x = uint32(src[s-2]) | uint32(src[s-1])<<8 - case x == 62: - s += 4 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - println("uint(s) > uint(len(src)", s, src) - return ErrSnappyCorrupt - } - x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16 - case x == 63: - s += 5 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - println("uint(s) > uint(len(src)", s, src) - return ErrSnappyCorrupt - } - x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24 - } - if x > snappyMaxBlockSize { - println("x > snappyMaxBlockSize", x, snappyMaxBlockSize) - return ErrSnappyCorrupt - } - length = int(x) + 1 - if length <= 0 { - println("length <= 0 ", length) - - return errUnsupportedLiteralLength - } - //if length > snappyMaxBlockSize-d || uint32(length) > len(src)-s { - // return ErrSnappyCorrupt - //} - - blk.literals = append(blk.literals, src[s:s+length]...) - //println(length, "litLen") - lits += length - s += length - continue - - case snappyTagCopy1: - s += 2 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - println("uint(s) > uint(len(src)", s, len(src)) - return ErrSnappyCorrupt - } - length = 4 + int(src[s-2])>>2&0x7 - offset = uint32(src[s-2])&0xe0<<3 | uint32(src[s-1]) - - case snappyTagCopy2: - s += 3 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - println("uint(s) > uint(len(src)", s, len(src)) - return ErrSnappyCorrupt - } - length = 1 + int(src[s-3])>>2 - offset = uint32(src[s-2]) | uint32(src[s-1])<<8 - - case snappyTagCopy4: - s += 5 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - println("uint(s) > uint(len(src)", s, len(src)) - return ErrSnappyCorrupt - } - length = 1 + int(src[s-5])>>2 - offset = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24 - } - - if offset <= 0 || blk.size+lits < int(offset) /*|| length > len(blk)-d */ { - println("offset <= 0 || blk.size+lits < int(offset)", offset, blk.size+lits, int(offset), blk.size, lits) - - return ErrSnappyCorrupt - } - - // Check if offset is one of the recent offsets. - // Adjusts the output offset accordingly. - // Gives a tiny bit of compression, typically around 1%. - if false { - offset = blk.matchOffset(offset, uint32(lits)) - } else { - offset += 3 - } - - blk.sequences = append(blk.sequences, seq{ - litLen: uint32(lits), - offset: offset, - matchLen: uint32(length) - zstdMinMatch, - }) - blk.size += length + lits - lits = 0 - } - blk.extraLits = lits - return nil -} - -func (r *SnappyConverter) readFull(p []byte, allowEOF bool) (ok bool) { - if _, r.err = io.ReadFull(r.r, p); r.err != nil { - if r.err == io.ErrUnexpectedEOF || (r.err == io.EOF && !allowEOF) { - r.err = ErrSnappyCorrupt - } - return false - } - return true -} - -var crcTable = crc32.MakeTable(crc32.Castagnoli) - -// crc implements the checksum specified in section 3 of -// https://github.com/google/snappy/blob/master/framing_format.txt -func snappyCRC(b []byte) uint32 { - c := crc32.Update(0, crcTable, b) - return c>>15 | c<<17 + 0xa282ead8 -} - -// snappyDecodedLen returns the length of the decoded block and the number of bytes -// that the length header occupied. -func snappyDecodedLen(src []byte) (blockLen, headerLen int, err error) { - v, n := binary.Uvarint(src) - if n <= 0 || v > 0xffffffff { - return 0, 0, ErrSnappyCorrupt - } - - const wordSize = 32 << (^uint(0) >> 32 & 1) - if wordSize == 32 && v > 0x7fffffff { - return 0, 0, ErrSnappyTooLarge - } - return int(v), n, nil -} diff --git a/vendor/github.com/klauspost/compress/zstd/zip.go b/vendor/github.com/klauspost/compress/zstd/zip.go deleted file mode 100644 index 29c15c8c4..000000000 --- a/vendor/github.com/klauspost/compress/zstd/zip.go +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. - -package zstd - -import ( - "errors" - "io" - "sync" -) - -// ZipMethodWinZip is the method for Zstandard compressed data inside Zip files for WinZip. -// See https://www.winzip.com/win/en/comp_info.html -const ZipMethodWinZip = 93 - -// ZipMethodPKWare is the original method number used by PKWARE to indicate Zstandard compression. -// Deprecated: This has been deprecated by PKWARE, use ZipMethodWinZip instead for compression. -// See https://pkware.cachefly.net/webdocs/APPNOTE/APPNOTE-6.3.9.TXT -const ZipMethodPKWare = 20 - -// zipReaderPool is the default reader pool. -var zipReaderPool = sync.Pool{New: func() interface{} { - z, err := NewReader(nil, WithDecoderLowmem(true), WithDecoderMaxWindow(128<<20), WithDecoderConcurrency(1)) - if err != nil { - panic(err) - } - return z -}} - -// newZipReader creates a pooled zip decompressor. -func newZipReader(opts ...DOption) func(r io.Reader) io.ReadCloser { - pool := &zipReaderPool - if len(opts) > 0 { - opts = append([]DOption{WithDecoderLowmem(true), WithDecoderMaxWindow(128 << 20)}, opts...) - // Force concurrency 1 - opts = append(opts, WithDecoderConcurrency(1)) - // Create our own pool - pool = &sync.Pool{} - } - return func(r io.Reader) io.ReadCloser { - dec, ok := pool.Get().(*Decoder) - if ok { - dec.Reset(r) - } else { - d, err := NewReader(r, opts...) - if err != nil { - panic(err) - } - dec = d - } - return &pooledZipReader{dec: dec, pool: pool} - } -} - -type pooledZipReader struct { - mu sync.Mutex // guards Close and Read - pool *sync.Pool - dec *Decoder -} - -func (r *pooledZipReader) Read(p []byte) (n int, err error) { - r.mu.Lock() - defer r.mu.Unlock() - if r.dec == nil { - return 0, errors.New("read after close or EOF") - } - dec, err := r.dec.Read(p) - if err == io.EOF { - r.dec.Reset(nil) - r.pool.Put(r.dec) - r.dec = nil - } - return dec, err -} - -func (r *pooledZipReader) Close() error { - r.mu.Lock() - defer r.mu.Unlock() - var err error - if r.dec != nil { - err = r.dec.Reset(nil) - r.pool.Put(r.dec) - r.dec = nil - } - return err -} - -type pooledZipWriter struct { - mu sync.Mutex // guards Close and Read - enc *Encoder - pool *sync.Pool -} - -func (w *pooledZipWriter) Write(p []byte) (n int, err error) { - w.mu.Lock() - defer w.mu.Unlock() - if w.enc == nil { - return 0, errors.New("Write after Close") - } - return w.enc.Write(p) -} - -func (w *pooledZipWriter) Close() error { - w.mu.Lock() - defer w.mu.Unlock() - var err error - if w.enc != nil { - err = w.enc.Close() - w.pool.Put(w.enc) - w.enc = nil - } - return err -} - -// ZipCompressor returns a compressor that can be registered with zip libraries. -// The provided encoder options will be used on all encodes. -func ZipCompressor(opts ...EOption) func(w io.Writer) (io.WriteCloser, error) { - var pool sync.Pool - return func(w io.Writer) (io.WriteCloser, error) { - enc, ok := pool.Get().(*Encoder) - if ok { - enc.Reset(w) - } else { - var err error - enc, err = NewWriter(w, opts...) - if err != nil { - return nil, err - } - } - return &pooledZipWriter{enc: enc, pool: &pool}, nil - } -} - -// ZipDecompressor returns a decompressor that can be registered with zip libraries. -// See ZipCompressor for example. -// Options can be specified. WithDecoderConcurrency(1) is forced, -// and by default a 128MB maximum decompression window is specified. -// The window size can be overridden if required. -func ZipDecompressor(opts ...DOption) func(r io.Reader) io.ReadCloser { - return newZipReader(opts...) -} diff --git a/vendor/github.com/klauspost/compress/zstd/zstd.go b/vendor/github.com/klauspost/compress/zstd/zstd.go deleted file mode 100644 index 4be7cc736..000000000 --- a/vendor/github.com/klauspost/compress/zstd/zstd.go +++ /dev/null @@ -1,121 +0,0 @@ -// Package zstd provides decompression of zstandard files. -// -// For advanced usage and examples, go to the README: https://github.com/klauspost/compress/tree/master/zstd#zstd -package zstd - -import ( - "bytes" - "encoding/binary" - "errors" - "log" - "math" -) - -// enable debug printing -const debug = false - -// enable encoding debug printing -const debugEncoder = debug - -// enable decoding debug printing -const debugDecoder = debug - -// Enable extra assertions. -const debugAsserts = debug || false - -// print sequence details -const debugSequences = false - -// print detailed matching information -const debugMatches = false - -// force encoder to use predefined tables. -const forcePreDef = false - -// zstdMinMatch is the minimum zstd match length. -const zstdMinMatch = 3 - -// fcsUnknown is used for unknown frame content size. -const fcsUnknown = math.MaxUint64 - -var ( - // ErrReservedBlockType is returned when a reserved block type is found. - // Typically this indicates wrong or corrupted input. - ErrReservedBlockType = errors.New("invalid input: reserved block type encountered") - - // ErrCompressedSizeTooBig is returned when a block is bigger than allowed. - // Typically this indicates wrong or corrupted input. - ErrCompressedSizeTooBig = errors.New("invalid input: compressed size too big") - - // ErrBlockTooSmall is returned when a block is too small to be decoded. - // Typically returned on invalid input. - ErrBlockTooSmall = errors.New("block too small") - - // ErrUnexpectedBlockSize is returned when a block has unexpected size. - // Typically returned on invalid input. - ErrUnexpectedBlockSize = errors.New("unexpected block size") - - // ErrMagicMismatch is returned when a "magic" number isn't what is expected. - // Typically this indicates wrong or corrupted input. - ErrMagicMismatch = errors.New("invalid input: magic number mismatch") - - // ErrWindowSizeExceeded is returned when a reference exceeds the valid window size. - // Typically this indicates wrong or corrupted input. - ErrWindowSizeExceeded = errors.New("window size exceeded") - - // ErrWindowSizeTooSmall is returned when no window size is specified. - // Typically this indicates wrong or corrupted input. - ErrWindowSizeTooSmall = errors.New("invalid input: window size was too small") - - // ErrDecoderSizeExceeded is returned if decompressed size exceeds the configured limit. - ErrDecoderSizeExceeded = errors.New("decompressed size exceeds configured limit") - - // ErrUnknownDictionary is returned if the dictionary ID is unknown. - ErrUnknownDictionary = errors.New("unknown dictionary") - - // ErrFrameSizeExceeded is returned if the stated frame size is exceeded. - // This is only returned if SingleSegment is specified on the frame. - ErrFrameSizeExceeded = errors.New("frame size exceeded") - - // ErrFrameSizeMismatch is returned if the stated frame size does not match the expected size. - // This is only returned if SingleSegment is specified on the frame. - ErrFrameSizeMismatch = errors.New("frame size does not match size on stream") - - // ErrCRCMismatch is returned if CRC mismatches. - ErrCRCMismatch = errors.New("CRC check failed") - - // ErrDecoderClosed will be returned if the Decoder was used after - // Close has been called. - ErrDecoderClosed = errors.New("decoder used after Close") - - // ErrDecoderNilInput is returned when a nil Reader was provided - // and an operation other than Reset/DecodeAll/Close was attempted. - ErrDecoderNilInput = errors.New("nil input provided as reader") -) - -func println(a ...interface{}) { - if debug || debugDecoder || debugEncoder { - log.Println(a...) - } -} - -func printf(format string, a ...interface{}) { - if debug || debugDecoder || debugEncoder { - log.Printf(format, a...) - } -} - -func load3232(b []byte, i int32) uint32 { - return binary.LittleEndian.Uint32(b[:len(b):len(b)][i:]) -} - -func load6432(b []byte, i int32) uint64 { - return binary.LittleEndian.Uint64(b[:len(b):len(b)][i:]) -} - -type byter interface { - Bytes() []byte - Len() int -} - -var _ byter = &bytes.Buffer{} diff --git a/vendor/github.com/mitchellh/go-homedir/LICENSE b/vendor/github.com/mitchellh/go-homedir/LICENSE deleted file mode 100644 index f9c841a51..000000000 --- a/vendor/github.com/mitchellh/go-homedir/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Mitchell Hashimoto - -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. diff --git a/vendor/github.com/mitchellh/go-homedir/README.md b/vendor/github.com/mitchellh/go-homedir/README.md deleted file mode 100644 index d70706d5b..000000000 --- a/vendor/github.com/mitchellh/go-homedir/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# go-homedir - -This is a Go library for detecting the user's home directory without -the use of cgo, so the library can be used in cross-compilation environments. - -Usage is incredibly simple, just call `homedir.Dir()` to get the home directory -for a user, and `homedir.Expand()` to expand the `~` in a path to the home -directory. - -**Why not just use `os/user`?** The built-in `os/user` package requires -cgo on Darwin systems. This means that any Go code that uses that package -cannot cross compile. But 99% of the time the use for `os/user` is just to -retrieve the home directory, which we can do for the current user without -cgo. This library does that, enabling cross-compilation. diff --git a/vendor/github.com/mitchellh/go-homedir/homedir.go b/vendor/github.com/mitchellh/go-homedir/homedir.go deleted file mode 100644 index 25378537e..000000000 --- a/vendor/github.com/mitchellh/go-homedir/homedir.go +++ /dev/null @@ -1,167 +0,0 @@ -package homedir - -import ( - "bytes" - "errors" - "os" - "os/exec" - "path/filepath" - "runtime" - "strconv" - "strings" - "sync" -) - -// DisableCache will disable caching of the home directory. Caching is enabled -// by default. -var DisableCache bool - -var homedirCache string -var cacheLock sync.RWMutex - -// Dir returns the home directory for the executing user. -// -// This uses an OS-specific method for discovering the home directory. -// An error is returned if a home directory cannot be detected. -func Dir() (string, error) { - if !DisableCache { - cacheLock.RLock() - cached := homedirCache - cacheLock.RUnlock() - if cached != "" { - return cached, nil - } - } - - cacheLock.Lock() - defer cacheLock.Unlock() - - var result string - var err error - if runtime.GOOS == "windows" { - result, err = dirWindows() - } else { - // Unix-like system, so just assume Unix - result, err = dirUnix() - } - - if err != nil { - return "", err - } - homedirCache = result - return result, nil -} - -// Expand expands the path to include the home directory if the path -// is prefixed with `~`. If it isn't prefixed with `~`, the path is -// returned as-is. -func Expand(path string) (string, error) { - if len(path) == 0 { - return path, nil - } - - if path[0] != '~' { - return path, nil - } - - if len(path) > 1 && path[1] != '/' && path[1] != '\\' { - return "", errors.New("cannot expand user-specific home dir") - } - - dir, err := Dir() - if err != nil { - return "", err - } - - return filepath.Join(dir, path[1:]), nil -} - -// Reset clears the cache, forcing the next call to Dir to re-detect -// the home directory. This generally never has to be called, but can be -// useful in tests if you're modifying the home directory via the HOME -// env var or something. -func Reset() { - cacheLock.Lock() - defer cacheLock.Unlock() - homedirCache = "" -} - -func dirUnix() (string, error) { - homeEnv := "HOME" - if runtime.GOOS == "plan9" { - // On plan9, env vars are lowercase. - homeEnv = "home" - } - - // First prefer the HOME environmental variable - if home := os.Getenv(homeEnv); home != "" { - return home, nil - } - - var stdout bytes.Buffer - - // If that fails, try OS specific commands - if runtime.GOOS == "darwin" { - cmd := exec.Command("sh", "-c", `dscl -q . -read /Users/"$(whoami)" NFSHomeDirectory | sed 's/^[^ ]*: //'`) - cmd.Stdout = &stdout - if err := cmd.Run(); err == nil { - result := strings.TrimSpace(stdout.String()) - if result != "" { - return result, nil - } - } - } else { - cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid())) - cmd.Stdout = &stdout - if err := cmd.Run(); err != nil { - // If the error is ErrNotFound, we ignore it. Otherwise, return it. - if err != exec.ErrNotFound { - return "", err - } - } else { - if passwd := strings.TrimSpace(stdout.String()); passwd != "" { - // username:password:uid:gid:gecos:home:shell - passwdParts := strings.SplitN(passwd, ":", 7) - if len(passwdParts) > 5 { - return passwdParts[5], nil - } - } - } - } - - // If all else fails, try the shell - stdout.Reset() - cmd := exec.Command("sh", "-c", "cd && pwd") - cmd.Stdout = &stdout - if err := cmd.Run(); err != nil { - return "", err - } - - result := strings.TrimSpace(stdout.String()) - if result == "" { - return "", errors.New("blank output when reading home directory") - } - - return result, nil -} - -func dirWindows() (string, error) { - // First prefer the HOME environmental variable - if home := os.Getenv("HOME"); home != "" { - return home, nil - } - - // Prefer standard environment variable USERPROFILE - if home := os.Getenv("USERPROFILE"); home != "" { - return home, nil - } - - drive := os.Getenv("HOMEDRIVE") - path := os.Getenv("HOMEPATH") - home := drive + path - if drive == "" || path == "" { - return "", errors.New("HOMEDRIVE, HOMEPATH, or USERPROFILE are blank") - } - - return home, nil -} diff --git a/vendor/github.com/nats-io/nats.go/.gitignore b/vendor/github.com/nats-io/nats.go/.gitignore deleted file mode 100644 index ae4871f46..000000000 --- a/vendor/github.com/nats-io/nats.go/.gitignore +++ /dev/null @@ -1,45 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe - -# Emacs -*~ -\#*\# -.\#* - -# vi/vim -.??*.swp - -# Mac -.DS_Store - -# Eclipse -.project -.settings/ - -# bin - -# Goland -.idea - -# VS Code -.vscode \ No newline at end of file diff --git a/vendor/github.com/nats-io/nats.go/.golangci.yaml b/vendor/github.com/nats-io/nats.go/.golangci.yaml deleted file mode 100644 index fb548e50e..000000000 --- a/vendor/github.com/nats-io/nats.go/.golangci.yaml +++ /dev/null @@ -1,16 +0,0 @@ -issues: - max-issues-per-linter: 0 - max-same-issues: 0 - exclude-rules: - - linters: - - errcheck - text: "Unsubscribe" - - linters: - - errcheck - text: "Drain" - - linters: - - errcheck - text: "msg.Ack" - - linters: - - errcheck - text: "watcher.Stop" diff --git a/vendor/github.com/nats-io/nats.go/.travis.yml b/vendor/github.com/nats-io/nats.go/.travis.yml deleted file mode 100644 index 1505f773d..000000000 --- a/vendor/github.com/nats-io/nats.go/.travis.yml +++ /dev/null @@ -1,36 +0,0 @@ -language: go -go: -- "1.21.x" -- "1.20.x" -go_import_path: github.com/nats-io/nats.go -install: -- go get -t ./... -- curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin -- if [[ "$TRAVIS_GO_VERSION" =~ 1.21 ]]; then - go install github.com/mattn/goveralls@latest; - go install github.com/wadey/gocovmerge@latest; - go install honnef.co/go/tools/cmd/staticcheck@latest; - go install github.com/client9/misspell/cmd/misspell@latest; - fi -before_script: -- $(exit $(go fmt ./... | wc -l)) -- go vet -modfile=go_test.mod ./... -- if [[ "$TRAVIS_GO_VERSION" =~ 1.21 ]]; then - find . -type f -name "*.go" | xargs misspell -error -locale US; - GOFLAGS="-mod=mod -modfile=go_test.mod" staticcheck ./...; - fi -- golangci-lint run ./jetstream/... -script: -- go test -modfile=go_test.mod -v -run=TestNoRace -p=1 ./... --failfast -vet=off -- if [[ "$TRAVIS_GO_VERSION" =~ 1.21 ]]; then ./scripts/cov.sh TRAVIS; else go test -modfile=go_test.mod -race -v -p=1 ./... --failfast -vet=off -tags=internal_testing; fi -after_success: -- if [[ "$TRAVIS_GO_VERSION" =~ 1.21 ]]; then $HOME/gopath/bin/goveralls -coverprofile=acc.out -service travis-ci; fi - -jobs: - include: - - name: "Go: 1.21.x (nats-server@main)" - go: "1.21.x" - before_script: - - go get -modfile go_test.mod github.com/nats-io/nats-server/v2@main - allow_failures: - - name: "Go: 1.21.x (nats-server@main)" diff --git a/vendor/github.com/nats-io/nats.go/.words b/vendor/github.com/nats-io/nats.go/.words deleted file mode 100644 index 24be7f625..000000000 --- a/vendor/github.com/nats-io/nats.go/.words +++ /dev/null @@ -1,106 +0,0 @@ -1 - -derek -dlc -ivan - -acknowledgement/SM -arity -deduplication/S -demarshal/SDG -durables -iff -observable/S -redelivery/S -retransmitting -retry/SB - -SlowConsumer - -AppendInt -ReadMIMEHeader - -clientProtoZero -jetstream -v1 -v2 - -ack/SGD -auth -authToken -chans -creds -config/S -cseq -impl -msgh -msgId -mux/S -nack -ptr -puback -scanf -stderr -stdout -structs -tm -todo -unsub/S - -permessage -permessage-deflate -urlA -urlB -websocket -ws -wss - -NKey -pList - -backend/S -backoff/S -decompressor/CGS -inflight -inlined -lookups -reconnection/MS -redeliver/ADGS -responder/S -rewrap/S -rollup/S -unreceive/DRSZGB -variadic -wakeup/S -whitespace -wrap/AS - -omitempty - -apache -html -ietf -www - -sum256 -32bit/S -64bit/S -64k -128k -512k - -hacky -handroll/D - -rfc6455 -rfc7692 -0x00 -0xff -20x -40x -50x - -ErrXXX - -atlanta -eu diff --git a/vendor/github.com/nats-io/nats.go/.words.readme b/vendor/github.com/nats-io/nats.go/.words.readme deleted file mode 100644 index 9d9f5cbbc..000000000 --- a/vendor/github.com/nats-io/nats.go/.words.readme +++ /dev/null @@ -1,25 +0,0 @@ -The .words file is used by gospel (v1.2+), which wraps the Hunspell libraries -but populates the dictionary with identifiers from the Go source. - - - -Alas, no comments are allowed in the .words file and newer versions of gospel -error out on seeing them. This is really a hunspell restriction. - -We assume en_US hunspell dictionaries are installed and used. -The /AFFIXRULES are defined in en_US.aff (eg: /usr/share/hunspell/en_US.aff) -Invoke `hunspell -D` to see the actual locations. - -Words which are in the base dictionary can't have extra affix rules added to -them, so we have to start with the affixed variant we want to add. -Thus `creds` rather than `cred/S` and so on. - -So we can't use receive/DRSZGBU, adding 'U', to allow unreceive and variants, -we have to use unreceive as the stem. - -We can't define our own affix or compound rules, -to capture rfc\d{3,} or 0x[0-9A-Fa-f]{2} - -The spelling tokenizer doesn't take "permessage-deflate" as allowing for ... -"permessage-deflate", which is an RFC7692 registered extension for websockets. -We have to explicitly list "permessage". diff --git a/vendor/github.com/nats-io/nats.go/CODE-OF-CONDUCT.md b/vendor/github.com/nats-io/nats.go/CODE-OF-CONDUCT.md deleted file mode 100644 index b850d49ee..000000000 --- a/vendor/github.com/nats-io/nats.go/CODE-OF-CONDUCT.md +++ /dev/null @@ -1,3 +0,0 @@ -## Community Code of Conduct - -NATS follows the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/master/code-of-conduct.md). diff --git a/vendor/github.com/nats-io/nats.go/CONTRIBUTING.md b/vendor/github.com/nats-io/nats.go/CONTRIBUTING.md deleted file mode 100644 index 9eea61be3..000000000 --- a/vendor/github.com/nats-io/nats.go/CONTRIBUTING.md +++ /dev/null @@ -1,45 +0,0 @@ -# Contributing - -Thanks for your interest in contributing! This document contains `nats-io/nats.go` specific contributing details. If you are a first-time contributor, please refer to the general [NATS Contributor Guide](https://nats.io/contributing/) to get a comprehensive overview of contributing to the NATS project. - -## Getting started - -There are three general ways you can contribute to this repo: - -- Proposing an enhancement or new feature -- Reporting a bug or regression -- Contributing changes to the source code - -For the first two, refer to the [GitHub Issues](https://github.com/nats-io/nats.go/issues/new/choose) which guides you through the available options along with the needed information to collect. - -## Contributing changes - -_Prior to opening a pull request, it is recommended to open an issue first to ensure the maintainers can review intended changes. Exceptions to this rule include fixing non-functional source such as code comments, documentation or other supporting files._ - -Proposing source code changes is done through GitHub's standard pull request workflow. - -If your branch is a work-in-progress then please start by creating your pull requests as draft, by clicking the down-arrow next to the `Create pull request` button and instead selecting `Create draft pull request`. - -This will defer the automatic process of requesting a review from the NATS team and significantly reduces noise until you are ready. Once you are happy, you can click the `Ready for review` button. - -### Guidelines - -A good pull request includes: - -- A high-level description of the changes, including links to any issues that are related by adding comments like `Resolves #NNN` to your description. See [Linking a Pull Request to an Issue](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for more information. -- An up-to-date parent commit. Please make sure you are pulling in the latest `main` branch and rebasing your work on top of it, i.e. `git rebase main`. -- Unit tests where appropriate. Bug fixes will benefit from the addition of regression tests. New features will not be accepted without suitable test coverage! -- No more commits than necessary. Sometimes having multiple commits is useful for telling a story or isolating changes from one another, but please squash down any unnecessary commits that may just be for clean-up, comments or small changes. -- No additional external dependencies that aren't absolutely essential. Please do everything you can to avoid pulling in additional libraries/dependencies into `go.mod` as we will be very critical of these. - -### Sign-off - -In order to accept a contribution, you will first need to certify that the contribution is your original work and that you license the work to the project under the [Apache-2.0 license](https://github.com/nats-io/nats.go/blob/main/LICENSE). - -This is done by using `Signed-off-by` statements, which should appear in **both** your commit messages and your PR description. Please note that we can only accept sign-offs under a legal name. Nicknames and aliases are not permitted. - -To perform a sign-off with `git`, use `git commit -s` (or `--signoff`). - -## Get help - -If you have questions about the contribution process, please start a [GitHub discussion](https://github.com/nats-io/nats.go/discussions), join the [NATS Slack](https://slack.nats.io/), or send your question to the [NATS Google Group](https://groups.google.com/forum/#!forum/natsio). diff --git a/vendor/github.com/nats-io/nats.go/GOVERNANCE.md b/vendor/github.com/nats-io/nats.go/GOVERNANCE.md deleted file mode 100644 index 1d5a7be3e..000000000 --- a/vendor/github.com/nats-io/nats.go/GOVERNANCE.md +++ /dev/null @@ -1,3 +0,0 @@ -# NATS Go Client Governance - -NATS Go Client (go-nats) is part of the NATS project and is subject to the [NATS Governance](https://github.com/nats-io/nats-general/blob/master/GOVERNANCE.md). \ No newline at end of file diff --git a/vendor/github.com/nats-io/nats.go/LICENSE b/vendor/github.com/nats-io/nats.go/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/vendor/github.com/nats-io/nats.go/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - 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 "[]" - 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 - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/nats-io/nats.go/MAINTAINERS.md b/vendor/github.com/nats-io/nats.go/MAINTAINERS.md deleted file mode 100644 index 232146550..000000000 --- a/vendor/github.com/nats-io/nats.go/MAINTAINERS.md +++ /dev/null @@ -1,8 +0,0 @@ -# Maintainers - -Maintainership is on a per project basis. - -### Maintainers - - Derek Collison [@derekcollison](https://github.com/derekcollison) - - Ivan Kozlovic [@kozlovic](https://github.com/kozlovic) - - Waldemar Quevedo [@wallyqs](https://github.com/wallyqs) diff --git a/vendor/github.com/nats-io/nats.go/README.md b/vendor/github.com/nats-io/nats.go/README.md deleted file mode 100644 index bc8cceb3a..000000000 --- a/vendor/github.com/nats-io/nats.go/README.md +++ /dev/null @@ -1,482 +0,0 @@ -# NATS - Go Client -A [Go](http://golang.org) client for the [NATS messaging system](https://nats.io). - -[![License Apache 2][License-Image]][License-Url] [![Go Report Card][ReportCard-Image]][ReportCard-Url] [![Build Status][Build-Status-Image]][Build-Status-Url] [![GoDoc][GoDoc-Image]][GoDoc-Url] [![Coverage Status][Coverage-image]][Coverage-Url] - -[License-Url]: https://www.apache.org/licenses/LICENSE-2.0 -[License-Image]: https://img.shields.io/badge/License-Apache2-blue.svg -[ReportCard-Url]: https://goreportcard.com/report/github.com/nats-io/nats.go -[ReportCard-Image]: https://goreportcard.com/badge/github.com/nats-io/nats.go -[Build-Status-Url]: https://travis-ci.com/github/nats-io/nats.go -[Build-Status-Image]: https://travis-ci.com/nats-io/nats.go.svg?branch=main -[GoDoc-Url]: https://pkg.go.dev/github.com/nats-io/nats.go -[GoDoc-Image]: https://img.shields.io/badge/GoDoc-reference-007d9c -[Coverage-Url]: https://coveralls.io/r/nats-io/nats.go?branch=main -[Coverage-image]: https://coveralls.io/repos/github/nats-io/nats.go/badge.svg?branch=main - -**Check out [NATS by example](https://natsbyexample.com) - An evolving collection of runnable, cross-client reference examples for NATS.** - -## Installation - -```bash -# Go client -go get github.com/nats-io/nats.go/ - -# Server -go get github.com/nats-io/nats-server -``` - -When using or transitioning to Go modules support: - -```bash -# Go client latest or explicit version -go get github.com/nats-io/nats.go/@latest -go get github.com/nats-io/nats.go/@v1.33.1 - -# For latest NATS Server, add /v2 at the end -go get github.com/nats-io/nats-server/v2 - -# NATS Server v1 is installed otherwise -# go get github.com/nats-io/nats-server -``` - -## Basic Usage - -```go -import "github.com/nats-io/nats.go" - -// Connect to a server -nc, _ := nats.Connect(nats.DefaultURL) - -// Simple Publisher -nc.Publish("foo", []byte("Hello World")) - -// Simple Async Subscriber -nc.Subscribe("foo", func(m *nats.Msg) { - fmt.Printf("Received a message: %s\n", string(m.Data)) -}) - -// Responding to a request message -nc.Subscribe("request", func(m *nats.Msg) { - m.Respond([]byte("answer is 42")) -}) - -// Simple Sync Subscriber -sub, err := nc.SubscribeSync("foo") -m, err := sub.NextMsg(timeout) - -// Channel Subscriber -ch := make(chan *nats.Msg, 64) -sub, err := nc.ChanSubscribe("foo", ch) -msg := <- ch - -// Unsubscribe -sub.Unsubscribe() - -// Drain -sub.Drain() - -// Requests -msg, err := nc.Request("help", []byte("help me"), 10*time.Millisecond) - -// Replies -nc.Subscribe("help", func(m *nats.Msg) { - nc.Publish(m.Reply, []byte("I can help!")) -}) - -// Drain connection (Preferred for responders) -// Close() not needed if this is called. -nc.Drain() - -// Close connection -nc.Close() -``` - -## JetStream - -JetStream is the built-in NATS persistence system. `nats.go` provides a built-in -API enabling both managing JetStream assets as well as publishing/consuming -persistent messages. - -### Basic usage - -```go -// connect to nats server -nc, _ := nats.Connect(nats.DefaultURL) - -// create jetstream context from nats connection -js, _ := jetstream.New(nc) - -ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) -defer cancel() - -// get existing stream handle -stream, _ := js.Stream(ctx, "foo") - -// retrieve consumer handle from a stream -cons, _ := stream.Consumer(ctx, "cons") - -// consume messages from the consumer in callback -cc, _ := cons.Consume(func(msg jetstream.Msg) { - fmt.Println("Received jetstream message: ", string(msg.Data())) - msg.Ack() -}) -defer cc.Stop() -``` - -To find more information on `nats.go` JetStream API, visit -[`jetstream/README.md`](jetstream/README.md) - -> The current JetStream API replaces the [legacy JetStream API](legacy_jetstream.md) - -## Service API - -The service API (`micro`) allows you to [easily build NATS services](micro/README.md) The -services API is currently in beta release. - -## Encoded Connections - -```go - -nc, _ := nats.Connect(nats.DefaultURL) -c, _ := nats.NewEncodedConn(nc, nats.JSON_ENCODER) -defer c.Close() - -// Simple Publisher -c.Publish("foo", "Hello World") - -// Simple Async Subscriber -c.Subscribe("foo", func(s string) { - fmt.Printf("Received a message: %s\n", s) -}) - -// EncodedConn can Publish any raw Go type using the registered Encoder -type person struct { - Name string - Address string - Age int -} - -// Go type Subscriber -c.Subscribe("hello", func(p *person) { - fmt.Printf("Received a person: %+v\n", p) -}) - -me := &person{Name: "derek", Age: 22, Address: "140 New Montgomery Street, San Francisco, CA"} - -// Go type Publisher -c.Publish("hello", me) - -// Unsubscribe -sub, err := c.Subscribe("foo", nil) -// ... -sub.Unsubscribe() - -// Requests -var response string -err = c.Request("help", "help me", &response, 10*time.Millisecond) -if err != nil { - fmt.Printf("Request failed: %v\n", err) -} - -// Replying -c.Subscribe("help", func(subj, reply string, msg string) { - c.Publish(reply, "I can help!") -}) - -// Close connection -c.Close(); -``` - -## New Authentication (Nkeys and User Credentials) -This requires server with version >= 2.0.0 - -NATS servers have a new security and authentication mechanism to authenticate with user credentials and Nkeys. -The simplest form is to use the helper method UserCredentials(credsFilepath). -```go -nc, err := nats.Connect(url, nats.UserCredentials("user.creds")) -``` - -The helper methods creates two callback handlers to present the user JWT and sign the nonce challenge from the server. -The core client library never has direct access to your private key and simply performs the callback for signing the server challenge. -The helper will load and wipe and erase memory it uses for each connect or reconnect. - -The helper also can take two entries, one for the JWT and one for the NKey seed file. -```go -nc, err := nats.Connect(url, nats.UserCredentials("user.jwt", "user.nk")) -``` - -You can also set the callback handlers directly and manage challenge signing directly. -```go -nc, err := nats.Connect(url, nats.UserJWT(jwtCB, sigCB)) -``` - -Bare Nkeys are also supported. The nkey seed should be in a read only file, e.g. seed.txt -```bash -> cat seed.txt -# This is my seed nkey! -SUAGMJH5XLGZKQQWAWKRZJIGMOU4HPFUYLXJMXOO5NLFEO2OOQJ5LPRDPM -``` - -This is a helper function which will load and decode and do the proper signing for the server nonce. -It will clear memory in between invocations. -You can choose to use the low level option and provide the public key and a signature callback on your own. - -```go -opt, err := nats.NkeyOptionFromSeed("seed.txt") -nc, err := nats.Connect(serverUrl, opt) - -// Direct -nc, err := nats.Connect(serverUrl, nats.Nkey(pubNkey, sigCB)) -``` - -## TLS - -```go -// tls as a scheme will enable secure connections by default. This will also verify the server name. -nc, err := nats.Connect("tls://nats.demo.io:4443") - -// If you are using a self-signed certificate, you need to have a tls.Config with RootCAs setup. -// We provide a helper method to make this case easier. -nc, err = nats.Connect("tls://localhost:4443", nats.RootCAs("./configs/certs/ca.pem")) - -// If the server requires client certificate, there is an helper function for that too: -cert := nats.ClientCert("./configs/certs/client-cert.pem", "./configs/certs/client-key.pem") -nc, err = nats.Connect("tls://localhost:4443", cert) - -// You can also supply a complete tls.Config - -certFile := "./configs/certs/client-cert.pem" -keyFile := "./configs/certs/client-key.pem" -cert, err := tls.LoadX509KeyPair(certFile, keyFile) -if err != nil { - t.Fatalf("error parsing X509 certificate/key pair: %v", err) -} - -config := &tls.Config{ - ServerName: opts.Host, - Certificates: []tls.Certificate{cert}, - RootCAs: pool, - MinVersion: tls.VersionTLS12, -} - -nc, err = nats.Connect("nats://localhost:4443", nats.Secure(config)) -if err != nil { - t.Fatalf("Got an error on Connect with Secure Options: %+v\n", err) -} - -``` - -## Using Go Channels (netchan) - -```go -nc, _ := nats.Connect(nats.DefaultURL) -ec, _ := nats.NewEncodedConn(nc, nats.JSON_ENCODER) -defer ec.Close() - -type person struct { - Name string - Address string - Age int -} - -recvCh := make(chan *person) -ec.BindRecvChan("hello", recvCh) - -sendCh := make(chan *person) -ec.BindSendChan("hello", sendCh) - -me := &person{Name: "derek", Age: 22, Address: "140 New Montgomery Street"} - -// Send via Go channels -sendCh <- me - -// Receive via Go channels -who := <- recvCh -``` - -## Wildcard Subscriptions - -```go - -// "*" matches any token, at any level of the subject. -nc.Subscribe("foo.*.baz", func(m *Msg) { - fmt.Printf("Msg received on [%s] : %s\n", m.Subject, string(m.Data)); -}) - -nc.Subscribe("foo.bar.*", func(m *Msg) { - fmt.Printf("Msg received on [%s] : %s\n", m.Subject, string(m.Data)); -}) - -// ">" matches any length of the tail of a subject, and can only be the last token -// E.g. 'foo.>' will match 'foo.bar', 'foo.bar.baz', 'foo.foo.bar.bax.22' -nc.Subscribe("foo.>", func(m *Msg) { - fmt.Printf("Msg received on [%s] : %s\n", m.Subject, string(m.Data)); -}) - -// Matches all of the above -nc.Publish("foo.bar.baz", []byte("Hello World")) - -``` - -## Queue Groups - -```go -// All subscriptions with the same queue name will form a queue group. -// Each message will be delivered to only one subscriber per queue group, -// using queuing semantics. You can have as many queue groups as you wish. -// Normal subscribers will continue to work as expected. - -nc.QueueSubscribe("foo", "job_workers", func(_ *Msg) { - received += 1; -}) -``` - -## Advanced Usage - -```go - -// Normally, the library will return an error when trying to connect and -// there is no server running. The RetryOnFailedConnect option will set -// the connection in reconnecting state if it failed to connect right away. -nc, err := nats.Connect(nats.DefaultURL, - nats.RetryOnFailedConnect(true), - nats.MaxReconnects(10), - nats.ReconnectWait(time.Second), - nats.ReconnectHandler(func(_ *nats.Conn) { - // Note that this will be invoked for the first asynchronous connect. - })) -if err != nil { - // Should not return an error even if it can't connect, but you still - // need to check in case there are some configuration errors. -} - -// Flush connection to server, returns when all messages have been processed. -nc.Flush() -fmt.Println("All clear!") - -// FlushTimeout specifies a timeout value as well. -err := nc.FlushTimeout(1*time.Second) -if err != nil { - fmt.Println("All clear!") -} else { - fmt.Println("Flushed timed out!") -} - -// Auto-unsubscribe after MAX_WANTED messages received -const MAX_WANTED = 10 -sub, err := nc.Subscribe("foo") -sub.AutoUnsubscribe(MAX_WANTED) - -// Multiple connections -nc1 := nats.Connect("nats://host1:4222") -nc2 := nats.Connect("nats://host2:4222") - -nc1.Subscribe("foo", func(m *Msg) { - fmt.Printf("Received a message: %s\n", string(m.Data)) -}) - -nc2.Publish("foo", []byte("Hello World!")); - -``` - -## Clustered Usage - -```go - -var servers = "nats://localhost:1222, nats://localhost:1223, nats://localhost:1224" - -nc, err := nats.Connect(servers) - -// Optionally set ReconnectWait and MaxReconnect attempts. -// This example means 10 seconds total per backend. -nc, err = nats.Connect(servers, nats.MaxReconnects(5), nats.ReconnectWait(2 * time.Second)) - -// You can also add some jitter for the reconnection. -// This call will add up to 500 milliseconds for non TLS connections and 2 seconds for TLS connections. -// If not specified, the library defaults to 100 milliseconds and 1 second, respectively. -nc, err = nats.Connect(servers, nats.ReconnectJitter(500*time.Millisecond, 2*time.Second)) - -// You can also specify a custom reconnect delay handler. If set, the library will invoke it when it has tried -// all URLs in its list. The value returned will be used as the total sleep time, so add your own jitter. -// The library will pass the number of times it went through the whole list. -nc, err = nats.Connect(servers, nats.CustomReconnectDelay(func(attempts int) time.Duration { - return someBackoffFunction(attempts) -})) - -// Optionally disable randomization of the server pool -nc, err = nats.Connect(servers, nats.DontRandomize()) - -// Setup callbacks to be notified on disconnects, reconnects and connection closed. -nc, err = nats.Connect(servers, - nats.DisconnectErrHandler(func(nc *nats.Conn, err error) { - fmt.Printf("Got disconnected! Reason: %q\n", err) - }), - nats.ReconnectHandler(func(nc *nats.Conn) { - fmt.Printf("Got reconnected to %v!\n", nc.ConnectedUrl()) - }), - nats.ClosedHandler(func(nc *nats.Conn) { - fmt.Printf("Connection closed. Reason: %q\n", nc.LastError()) - }) -) - -// When connecting to a mesh of servers with auto-discovery capabilities, -// you may need to provide a username/password or token in order to connect -// to any server in that mesh when authentication is required. -// Instead of providing the credentials in the initial URL, you will use -// new option setters: -nc, err = nats.Connect("nats://localhost:4222", nats.UserInfo("foo", "bar")) - -// For token based authentication: -nc, err = nats.Connect("nats://localhost:4222", nats.Token("S3cretT0ken")) - -// You can even pass the two at the same time in case one of the server -// in the mesh requires token instead of user name and password. -nc, err = nats.Connect("nats://localhost:4222", - nats.UserInfo("foo", "bar"), - nats.Token("S3cretT0ken")) - -// Note that if credentials are specified in the initial URLs, they take -// precedence on the credentials specified through the options. -// For instance, in the connect call below, the client library will use -// the user "my" and password "pwd" to connect to localhost:4222, however, -// it will use username "foo" and password "bar" when (re)connecting to -// a different server URL that it got as part of the auto-discovery. -nc, err = nats.Connect("nats://my:pwd@localhost:4222", nats.UserInfo("foo", "bar")) - -``` - -## Context support (+Go 1.7) - -```go -ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) -defer cancel() - -nc, err := nats.Connect(nats.DefaultURL) - -// Request with context -msg, err := nc.RequestWithContext(ctx, "foo", []byte("bar")) - -// Synchronous subscriber with context -sub, err := nc.SubscribeSync("foo") -msg, err := sub.NextMsgWithContext(ctx) - -// Encoded Request with context -c, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER) -type request struct { - Message string `json:"message"` -} -type response struct { - Code int `json:"code"` -} -req := &request{Message: "Hello"} -resp := &response{} -err := c.RequestWithContext(ctx, "foo", req, resp) -``` - -## License - -Unless otherwise noted, the NATS source files are distributed -under the Apache Version 2.0 license found in the LICENSE file. - -[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fnats-io%2Fgo-nats.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fnats-io%2Fgo-nats?ref=badge_large) diff --git a/vendor/github.com/nats-io/nats.go/context.go b/vendor/github.com/nats-io/nats.go/context.go deleted file mode 100644 index 20f1782ac..000000000 --- a/vendor/github.com/nats-io/nats.go/context.go +++ /dev/null @@ -1,244 +0,0 @@ -// Copyright 2016-2023 The NATS 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 nats - -import ( - "context" - "reflect" -) - -// RequestMsgWithContext takes a context, a subject and payload -// in bytes and request expecting a single response. -func (nc *Conn) RequestMsgWithContext(ctx context.Context, msg *Msg) (*Msg, error) { - if msg == nil { - return nil, ErrInvalidMsg - } - hdr, err := msg.headerBytes() - if err != nil { - return nil, err - } - return nc.requestWithContext(ctx, msg.Subject, hdr, msg.Data) -} - -// RequestWithContext takes a context, a subject and payload -// in bytes and request expecting a single response. -func (nc *Conn) RequestWithContext(ctx context.Context, subj string, data []byte) (*Msg, error) { - return nc.requestWithContext(ctx, subj, nil, data) -} - -func (nc *Conn) requestWithContext(ctx context.Context, subj string, hdr, data []byte) (*Msg, error) { - if ctx == nil { - return nil, ErrInvalidContext - } - if nc == nil { - return nil, ErrInvalidConnection - } - // Check whether the context is done already before making - // the request. - if ctx.Err() != nil { - return nil, ctx.Err() - } - - var m *Msg - var err error - - // If user wants the old style. - if nc.useOldRequestStyle() { - m, err = nc.oldRequestWithContext(ctx, subj, hdr, data) - } else { - mch, token, err := nc.createNewRequestAndSend(subj, hdr, data) - if err != nil { - return nil, err - } - - var ok bool - - select { - case m, ok = <-mch: - if !ok { - return nil, ErrConnectionClosed - } - case <-ctx.Done(): - nc.mu.Lock() - delete(nc.respMap, token) - nc.mu.Unlock() - return nil, ctx.Err() - } - } - // Check for no responder status. - if err == nil && len(m.Data) == 0 && m.Header.Get(statusHdr) == noResponders { - m, err = nil, ErrNoResponders - } - return m, err -} - -// oldRequestWithContext utilizes inbox and subscription per request. -func (nc *Conn) oldRequestWithContext(ctx context.Context, subj string, hdr, data []byte) (*Msg, error) { - inbox := nc.NewInbox() - ch := make(chan *Msg, RequestChanLen) - - s, err := nc.subscribe(inbox, _EMPTY_, nil, ch, true, nil) - if err != nil { - return nil, err - } - s.AutoUnsubscribe(1) - defer s.Unsubscribe() - - err = nc.publish(subj, inbox, hdr, data) - if err != nil { - return nil, err - } - - return s.NextMsgWithContext(ctx) -} - -func (s *Subscription) nextMsgWithContext(ctx context.Context, pullSubInternal, waitIfNoMsg bool) (*Msg, error) { - if ctx == nil { - return nil, ErrInvalidContext - } - if s == nil { - return nil, ErrBadSubscription - } - if ctx.Err() != nil { - return nil, ctx.Err() - } - - s.mu.Lock() - err := s.validateNextMsgState(pullSubInternal) - if err != nil { - s.mu.Unlock() - return nil, err - } - - // snapshot - mch := s.mch - s.mu.Unlock() - - var ok bool - var msg *Msg - - // If something is available right away, let's optimize that case. - select { - case msg, ok = <-mch: - if !ok { - return nil, s.getNextMsgErr() - } - if err := s.processNextMsgDelivered(msg); err != nil { - return nil, err - } - return msg, nil - default: - // If internal and we don't want to wait, signal that there is no - // message in the internal queue. - if pullSubInternal && !waitIfNoMsg { - return nil, errNoMessages - } - } - - select { - case msg, ok = <-mch: - if !ok { - return nil, s.getNextMsgErr() - } - if err := s.processNextMsgDelivered(msg); err != nil { - return nil, err - } - case <-ctx.Done(): - return nil, ctx.Err() - } - - return msg, nil -} - -// NextMsgWithContext takes a context and returns the next message -// available to a synchronous subscriber, blocking until it is delivered -// or context gets canceled. -func (s *Subscription) NextMsgWithContext(ctx context.Context) (*Msg, error) { - return s.nextMsgWithContext(ctx, false, true) -} - -// FlushWithContext will allow a context to control the duration -// of a Flush() call. This context should be non-nil and should -// have a deadline set. We will return an error if none is present. -func (nc *Conn) FlushWithContext(ctx context.Context) error { - if nc == nil { - return ErrInvalidConnection - } - if ctx == nil { - return ErrInvalidContext - } - _, ok := ctx.Deadline() - if !ok { - return ErrNoDeadlineContext - } - - nc.mu.Lock() - if nc.isClosed() { - nc.mu.Unlock() - return ErrConnectionClosed - } - // Create a buffered channel to prevent chan send to block - // in processPong() - ch := make(chan struct{}, 1) - nc.sendPing(ch) - nc.mu.Unlock() - - var err error - - select { - case _, ok := <-ch: - if !ok { - err = ErrConnectionClosed - } else { - close(ch) - } - case <-ctx.Done(): - err = ctx.Err() - } - - if err != nil { - nc.removeFlushEntry(ch) - } - - return err -} - -// RequestWithContext will create an Inbox and perform a Request -// using the provided cancellation context with the Inbox reply -// for the data v. A response will be decoded into the vPtr last parameter. -func (c *EncodedConn) RequestWithContext(ctx context.Context, subject string, v any, vPtr any) error { - if ctx == nil { - return ErrInvalidContext - } - - b, err := c.Enc.Encode(subject, v) - if err != nil { - return err - } - m, err := c.Conn.RequestWithContext(ctx, subject, b) - if err != nil { - return err - } - if reflect.TypeOf(vPtr) == emptyMsgType { - mPtr := vPtr.(*Msg) - *mPtr = *m - } else { - err := c.Enc.Decode(m.Subject, m.Data, vPtr) - if err != nil { - return err - } - } - - return nil -} diff --git a/vendor/github.com/nats-io/nats.go/dependencies.md b/vendor/github.com/nats-io/nats.go/dependencies.md deleted file mode 100644 index ec9ab3c6a..000000000 --- a/vendor/github.com/nats-io/nats.go/dependencies.md +++ /dev/null @@ -1,15 +0,0 @@ -# External Dependencies - -This file lists the dependencies used in this repository. - -| Dependency | License | -|-----------------------------------|--------------| -| Go | BSD 3-Clause | -| github.com/golang/protobuf/proto | BSD-3-Clause | -| github.com/klauspost/compress | BSD-3-Clause | -| github.com/nats-io/nats-server/v2 | Apache-2.0 | -| github.com/nats-io/nkeys | Apache-2.0 | -| github.com/nats-io/nuid | Apache-2.0 | -| go.uber.org/goleak | MIT | -| golang.org/x/text | BSD-3-Clause | -| google.golang.org/protobuf | BSD-3-Clause | diff --git a/vendor/github.com/nats-io/nats.go/enc.go b/vendor/github.com/nats-io/nats.go/enc.go deleted file mode 100644 index 4550f618d..000000000 --- a/vendor/github.com/nats-io/nats.go/enc.go +++ /dev/null @@ -1,269 +0,0 @@ -// Copyright 2012-2023 The NATS 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 nats - -import ( - "errors" - "fmt" - "reflect" - "sync" - "time" - - // Default Encoders - "github.com/nats-io/nats.go/encoders/builtin" -) - -// Encoder interface is for all register encoders -type Encoder interface { - Encode(subject string, v any) ([]byte, error) - Decode(subject string, data []byte, vPtr any) error -} - -var encMap map[string]Encoder -var encLock sync.Mutex - -// Indexed names into the Registered Encoders. -const ( - JSON_ENCODER = "json" - GOB_ENCODER = "gob" - DEFAULT_ENCODER = "default" -) - -func init() { - encMap = make(map[string]Encoder) - // Register json, gob and default encoder - RegisterEncoder(JSON_ENCODER, &builtin.JsonEncoder{}) - RegisterEncoder(GOB_ENCODER, &builtin.GobEncoder{}) - RegisterEncoder(DEFAULT_ENCODER, &builtin.DefaultEncoder{}) -} - -// EncodedConn are the preferred way to interface with NATS. They wrap a bare connection to -// a nats server and have an extendable encoder system that will encode and decode messages -// from raw Go types. -type EncodedConn struct { - Conn *Conn - Enc Encoder -} - -// NewEncodedConn will wrap an existing Connection and utilize the appropriate registered -// encoder. -func NewEncodedConn(c *Conn, encType string) (*EncodedConn, error) { - if c == nil { - return nil, errors.New("nats: Nil Connection") - } - if c.IsClosed() { - return nil, ErrConnectionClosed - } - ec := &EncodedConn{Conn: c, Enc: EncoderForType(encType)} - if ec.Enc == nil { - return nil, fmt.Errorf("no encoder registered for '%s'", encType) - } - return ec, nil -} - -// RegisterEncoder will register the encType with the given Encoder. Useful for customization. -func RegisterEncoder(encType string, enc Encoder) { - encLock.Lock() - defer encLock.Unlock() - encMap[encType] = enc -} - -// EncoderForType will return the registered Encoder for the encType. -func EncoderForType(encType string) Encoder { - encLock.Lock() - defer encLock.Unlock() - return encMap[encType] -} - -// Publish publishes the data argument to the given subject. The data argument -// will be encoded using the associated encoder. -func (c *EncodedConn) Publish(subject string, v any) error { - b, err := c.Enc.Encode(subject, v) - if err != nil { - return err - } - return c.Conn.publish(subject, _EMPTY_, nil, b) -} - -// PublishRequest will perform a Publish() expecting a response on the -// reply subject. Use Request() for automatically waiting for a response -// inline. -func (c *EncodedConn) PublishRequest(subject, reply string, v any) error { - b, err := c.Enc.Encode(subject, v) - if err != nil { - return err - } - return c.Conn.publish(subject, reply, nil, b) -} - -// Request will create an Inbox and perform a Request() call -// with the Inbox reply for the data v. A response will be -// decoded into the vPtr Response. -func (c *EncodedConn) Request(subject string, v any, vPtr any, timeout time.Duration) error { - b, err := c.Enc.Encode(subject, v) - if err != nil { - return err - } - m, err := c.Conn.Request(subject, b, timeout) - if err != nil { - return err - } - if reflect.TypeOf(vPtr) == emptyMsgType { - mPtr := vPtr.(*Msg) - *mPtr = *m - } else { - err = c.Enc.Decode(m.Subject, m.Data, vPtr) - } - return err -} - -// Handler is a specific callback used for Subscribe. It is generalized to -// an any, but we will discover its format and arguments at runtime -// and perform the correct callback, including demarshaling encoded data -// back into the appropriate struct based on the signature of the Handler. -// -// Handlers are expected to have one of four signatures. -// -// type person struct { -// Name string `json:"name,omitempty"` -// Age uint `json:"age,omitempty"` -// } -// -// handler := func(m *Msg) -// handler := func(p *person) -// handler := func(subject string, o *obj) -// handler := func(subject, reply string, o *obj) -// -// These forms allow a callback to request a raw Msg ptr, where the processing -// of the message from the wire is untouched. Process a JSON representation -// and demarshal it into the given struct, e.g. person. -// There are also variants where the callback wants either the subject, or the -// subject and the reply subject. -type Handler any - -// Dissect the cb Handler's signature -func argInfo(cb Handler) (reflect.Type, int) { - cbType := reflect.TypeOf(cb) - if cbType.Kind() != reflect.Func { - panic("nats: Handler needs to be a func") - } - numArgs := cbType.NumIn() - if numArgs == 0 { - return nil, numArgs - } - return cbType.In(numArgs - 1), numArgs -} - -var emptyMsgType = reflect.TypeOf(&Msg{}) - -// Subscribe will create a subscription on the given subject and process incoming -// messages using the specified Handler. The Handler should be a func that matches -// a signature from the description of Handler from above. -func (c *EncodedConn) Subscribe(subject string, cb Handler) (*Subscription, error) { - return c.subscribe(subject, _EMPTY_, cb) -} - -// QueueSubscribe will create a queue subscription on the given subject and process -// incoming messages using the specified Handler. The Handler should be a func that -// matches a signature from the description of Handler from above. -func (c *EncodedConn) QueueSubscribe(subject, queue string, cb Handler) (*Subscription, error) { - return c.subscribe(subject, queue, cb) -} - -// Internal implementation that all public functions will use. -func (c *EncodedConn) subscribe(subject, queue string, cb Handler) (*Subscription, error) { - if cb == nil { - return nil, errors.New("nats: Handler required for EncodedConn Subscription") - } - argType, numArgs := argInfo(cb) - if argType == nil { - return nil, errors.New("nats: Handler requires at least one argument") - } - - cbValue := reflect.ValueOf(cb) - wantsRaw := (argType == emptyMsgType) - - natsCB := func(m *Msg) { - var oV []reflect.Value - if wantsRaw { - oV = []reflect.Value{reflect.ValueOf(m)} - } else { - var oPtr reflect.Value - if argType.Kind() != reflect.Ptr { - oPtr = reflect.New(argType) - } else { - oPtr = reflect.New(argType.Elem()) - } - if err := c.Enc.Decode(m.Subject, m.Data, oPtr.Interface()); err != nil { - if c.Conn.Opts.AsyncErrorCB != nil { - c.Conn.ach.push(func() { - c.Conn.Opts.AsyncErrorCB(c.Conn, m.Sub, errors.New("nats: Got an error trying to unmarshal: "+err.Error())) - }) - } - return - } - if argType.Kind() != reflect.Ptr { - oPtr = reflect.Indirect(oPtr) - } - - // Callback Arity - switch numArgs { - case 1: - oV = []reflect.Value{oPtr} - case 2: - subV := reflect.ValueOf(m.Subject) - oV = []reflect.Value{subV, oPtr} - case 3: - subV := reflect.ValueOf(m.Subject) - replyV := reflect.ValueOf(m.Reply) - oV = []reflect.Value{subV, replyV, oPtr} - } - - } - cbValue.Call(oV) - } - - return c.Conn.subscribe(subject, queue, natsCB, nil, false, nil) -} - -// FlushTimeout allows a Flush operation to have an associated timeout. -func (c *EncodedConn) FlushTimeout(timeout time.Duration) (err error) { - return c.Conn.FlushTimeout(timeout) -} - -// Flush will perform a round trip to the server and return when it -// receives the internal reply. -func (c *EncodedConn) Flush() error { - return c.Conn.Flush() -} - -// Close will close the connection to the server. This call will release -// all blocking calls, such as Flush(), etc. -func (c *EncodedConn) Close() { - c.Conn.Close() -} - -// Drain will put a connection into a drain state. All subscriptions will -// immediately be put into a drain state. Upon completion, the publishers -// will be drained and can not publish any additional messages. Upon draining -// of the publishers, the connection will be closed. Use the ClosedCB() -// option to know when the connection has moved from draining to closed. -func (c *EncodedConn) Drain() error { - return c.Conn.Drain() -} - -// LastError reports the last error encountered via the Connection. -func (c *EncodedConn) LastError() error { - return c.Conn.LastError() -} diff --git a/vendor/github.com/nats-io/nats.go/encoders/builtin/default_enc.go b/vendor/github.com/nats-io/nats.go/encoders/builtin/default_enc.go deleted file mode 100644 index c1d0f6f0b..000000000 --- a/vendor/github.com/nats-io/nats.go/encoders/builtin/default_enc.go +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2012-2023 The NATS 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 builtin - -import ( - "bytes" - "fmt" - "reflect" - "strconv" - "unsafe" -) - -// DefaultEncoder implementation for EncodedConn. -// This encoder will leave []byte and string untouched, but will attempt to -// turn numbers into appropriate strings that can be decoded. It will also -// properly encoded and decode bools. If will encode a struct, but if you want -// to properly handle structures you should use JsonEncoder. -type DefaultEncoder struct { - // Empty -} - -var trueB = []byte("true") -var falseB = []byte("false") -var nilB = []byte("") - -// Encode -func (je *DefaultEncoder) Encode(subject string, v any) ([]byte, error) { - switch arg := v.(type) { - case string: - bytes := *(*[]byte)(unsafe.Pointer(&arg)) - return bytes, nil - case []byte: - return arg, nil - case bool: - if arg { - return trueB, nil - } else { - return falseB, nil - } - case nil: - return nilB, nil - default: - var buf bytes.Buffer - fmt.Fprintf(&buf, "%+v", arg) - return buf.Bytes(), nil - } -} - -// Decode -func (je *DefaultEncoder) Decode(subject string, data []byte, vPtr any) error { - // Figure out what it's pointing to... - sData := *(*string)(unsafe.Pointer(&data)) - switch arg := vPtr.(type) { - case *string: - *arg = sData - return nil - case *[]byte: - *arg = data - return nil - case *int: - n, err := strconv.ParseInt(sData, 10, 64) - if err != nil { - return err - } - *arg = int(n) - return nil - case *int32: - n, err := strconv.ParseInt(sData, 10, 64) - if err != nil { - return err - } - *arg = int32(n) - return nil - case *int64: - n, err := strconv.ParseInt(sData, 10, 64) - if err != nil { - return err - } - *arg = int64(n) - return nil - case *float32: - n, err := strconv.ParseFloat(sData, 32) - if err != nil { - return err - } - *arg = float32(n) - return nil - case *float64: - n, err := strconv.ParseFloat(sData, 64) - if err != nil { - return err - } - *arg = float64(n) - return nil - case *bool: - b, err := strconv.ParseBool(sData) - if err != nil { - return err - } - *arg = b - return nil - default: - vt := reflect.TypeOf(arg).Elem() - return fmt.Errorf("nats: Default Encoder can't decode to type %s", vt) - } -} diff --git a/vendor/github.com/nats-io/nats.go/encoders/builtin/gob_enc.go b/vendor/github.com/nats-io/nats.go/encoders/builtin/gob_enc.go deleted file mode 100644 index 7ecf85e4d..000000000 --- a/vendor/github.com/nats-io/nats.go/encoders/builtin/gob_enc.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2013-2023 The NATS 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 builtin - -import ( - "bytes" - "encoding/gob" -) - -// GobEncoder is a Go specific GOB Encoder implementation for EncodedConn. -// This encoder will use the builtin encoding/gob to Marshal -// and Unmarshal most types, including structs. -type GobEncoder struct { - // Empty -} - -// FIXME(dlc) - This could probably be more efficient. - -// Encode -func (ge *GobEncoder) Encode(subject string, v any) ([]byte, error) { - b := new(bytes.Buffer) - enc := gob.NewEncoder(b) - if err := enc.Encode(v); err != nil { - return nil, err - } - return b.Bytes(), nil -} - -// Decode -func (ge *GobEncoder) Decode(subject string, data []byte, vPtr any) (err error) { - dec := gob.NewDecoder(bytes.NewBuffer(data)) - err = dec.Decode(vPtr) - return -} diff --git a/vendor/github.com/nats-io/nats.go/encoders/builtin/json_enc.go b/vendor/github.com/nats-io/nats.go/encoders/builtin/json_enc.go deleted file mode 100644 index 0540d9850..000000000 --- a/vendor/github.com/nats-io/nats.go/encoders/builtin/json_enc.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2012-2023 The NATS 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 builtin - -import ( - "encoding/json" - "strings" -) - -// JsonEncoder is a JSON Encoder implementation for EncodedConn. -// This encoder will use the builtin encoding/json to Marshal -// and Unmarshal most types, including structs. -type JsonEncoder struct { - // Empty -} - -// Encode -func (je *JsonEncoder) Encode(subject string, v any) ([]byte, error) { - b, err := json.Marshal(v) - if err != nil { - return nil, err - } - return b, nil -} - -// Decode -func (je *JsonEncoder) Decode(subject string, data []byte, vPtr any) (err error) { - switch arg := vPtr.(type) { - case *string: - // If they want a string and it is a JSON string, strip quotes - // This allows someone to send a struct but receive as a plain string - // This cast should be efficient for Go 1.3 and beyond. - str := string(data) - if strings.HasPrefix(str, `"`) && strings.HasSuffix(str, `"`) { - *arg = str[1 : len(str)-1] - } else { - *arg = str - } - case *[]byte: - *arg = data - default: - err = json.Unmarshal(data, arg) - } - return -} diff --git a/vendor/github.com/nats-io/nats.go/go_test.mod b/vendor/github.com/nats-io/nats.go/go_test.mod deleted file mode 100644 index 4e747bfeb..000000000 --- a/vendor/github.com/nats-io/nats.go/go_test.mod +++ /dev/null @@ -1,22 +0,0 @@ -module github.com/nats-io/nats.go - -go 1.19 - -require ( - github.com/golang/protobuf v1.4.2 - github.com/klauspost/compress v1.17.4 - github.com/nats-io/nats-server/v2 v2.10.9 - github.com/nats-io/nkeys v0.4.7 - github.com/nats-io/nuid v1.0.1 - go.uber.org/goleak v1.2.1 - golang.org/x/text v0.14.0 - google.golang.org/protobuf v1.23.0 -) - -require ( - github.com/minio/highwayhash v1.0.2 // indirect - github.com/nats-io/jwt/v2 v2.5.3 // indirect - golang.org/x/crypto v0.18.0 // indirect - golang.org/x/sys v0.16.0 // indirect - golang.org/x/time v0.5.0 // indirect -) diff --git a/vendor/github.com/nats-io/nats.go/go_test.sum b/vendor/github.com/nats-io/nats.go/go_test.sum deleted file mode 100644 index e33016d80..000000000 --- a/vendor/github.com/nats-io/nats.go/go_test.sum +++ /dev/null @@ -1,47 +0,0 @@ -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/klauspost/compress v1.17.4 h1:Ej5ixsIri7BrIjBkRZLTo6ghwrEtHFk7ijlczPW4fZ4= -github.com/klauspost/compress v1.17.4/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM= -github.com/minio/highwayhash v1.0.2 h1:Aak5U0nElisjDCfPSG79Tgzkn2gl66NxOMspRrKnA/g= -github.com/minio/highwayhash v1.0.2/go.mod h1:BQskDq+xkJ12lmlUUi7U0M5Swg3EWR+dLTk+kldvVxY= -github.com/nats-io/jwt/v2 v2.5.3 h1:/9SWvzc6hTfamcgXJ3uYRpgj+QuY2aLNqRiqrKcrpEo= -github.com/nats-io/jwt/v2 v2.5.3/go.mod h1:iysuPemFcc7p4IoYots3IuELSI4EDe9Y0bQMe+I3Bf4= -github.com/nats-io/nats-server/v2 v2.10.9 h1:VEW43Zz+p+9lARtiPM9ctd6ckun+92ZT2T17HWtwiFI= -github.com/nats-io/nats-server/v2 v2.10.9/go.mod h1:oorGiV9j3BOLLO3ejQe+U7pfAGyPo+ppD7rpgNF6KTQ= -github.com/nats-io/nkeys v0.4.7 h1:RwNJbbIdYCoClSDNY7QVKZlyb/wfT6ugvFCiKy6vDvI= -github.com/nats-io/nkeys v0.4.7/go.mod h1:kqXRgRDPlGy7nGaEDMuYzmiJCIAAWDK0IMBtDmGD0nc= -github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= -github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= -go.uber.org/goleak v1.2.1 h1:NBol2c7O1ZokfZ0LEU9K6Whx/KnwvepVetCUhtKja4A= -go.uber.org/goleak v1.2.1/go.mod h1:qlT2yGI9QafXHhZZLxlSuNsMw3FFLxBr+tBRlmO1xH4= -golang.org/x/crypto v0.18.0 h1:PGVlW0xEltQnzFZ55hkuX5+KLyrMYhHld1YHO4AKcdc= -golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= -golang.org/x/sys v0.0.0-20190130150945-aca44879d564/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU= -golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= -golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= -golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/vendor/github.com/nats-io/nats.go/internal/parser/parse.go b/vendor/github.com/nats-io/nats.go/internal/parser/parse.go deleted file mode 100644 index 7eab8addd..000000000 --- a/vendor/github.com/nats-io/nats.go/internal/parser/parse.go +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright 2020-2022 The NATS 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 parser - -import ( - "errors" - "fmt" -) - -const ( - AckDomainTokenPos = iota + 2 - AckAccHashTokenPos - AckStreamTokenPos - AckConsumerTokenPos - AckNumDeliveredTokenPos - AckStreamSeqTokenPos - AckConsumerSeqTokenPos - AckTimestampSeqTokenPos - AckNumPendingTokenPos -) - -var ErrInvalidSubjectFormat = errors.New("invalid format of ACK subject") - -// Quick parser for positive numbers in ack reply encoding. -// NOTE: This parser does not detect uint64 overflow -func ParseNum(d string) (n uint64) { - if len(d) == 0 { - return 0 - } - - // ASCII numbers 0-9 - const ( - asciiZero = 48 - asciiNine = 57 - ) - - for _, dec := range d { - if dec < asciiZero || dec > asciiNine { - return 0 - } - n = n*10 + uint64(dec) - asciiZero - } - return -} - -func GetMetadataFields(subject string) ([]string, error) { - v1TokenCounts, v2TokenCounts := 9, 12 - - var start int - tokens := make([]string, 0, v2TokenCounts) - for i := 0; i < len(subject); i++ { - if subject[i] == '.' { - tokens = append(tokens, subject[start:i]) - start = i + 1 - } - } - tokens = append(tokens, subject[start:]) - // - // Newer server will include the domain name and account hash in the subject, - // and a token at the end. - // - // Old subject was: - // $JS.ACK....... - // - // New subject would be: - // $JS.ACK.......... - // - // v1 has 9 tokens, v2 has 12, but we must not be strict on the 12th since - // it may be removed in the future. Also, the library has no use for it. - // The point is that a v2 ACK subject is valid if it has at least 11 tokens. - // - tokensLen := len(tokens) - // If lower than 9 or more than 9 but less than 11, report an error - if tokensLen < v1TokenCounts || (tokensLen > v1TokenCounts && tokensLen < v2TokenCounts-1) { - return nil, ErrInvalidSubjectFormat - } - if tokens[0] != "$JS" || tokens[1] != "ACK" { - return nil, fmt.Errorf("%w: subject should start with $JS.ACK", ErrInvalidSubjectFormat) - } - // For v1 style, we insert 2 empty tokens (domain and hash) so that the - // rest of the library references known fields at a constant location. - if tokensLen == v1TokenCounts { - // Extend the array (we know the backend is big enough) - tokens = append(tokens[:AckDomainTokenPos+2], tokens[AckDomainTokenPos:]...) - // Clear the domain and hash tokens - tokens[AckDomainTokenPos], tokens[AckAccHashTokenPos] = "", "" - - } else if tokens[AckDomainTokenPos] == "_" { - // If domain is "_", replace with empty value. - tokens[AckDomainTokenPos] = "" - } - return tokens, nil -} diff --git a/vendor/github.com/nats-io/nats.go/js.go b/vendor/github.com/nats-io/nats.go/js.go deleted file mode 100644 index 462fea17e..000000000 --- a/vendor/github.com/nats-io/nats.go/js.go +++ /dev/null @@ -1,3848 +0,0 @@ -// Copyright 2020-2023 The NATS 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 nats - -import ( - "bytes" - "context" - "crypto/sha256" - "encoding/json" - "errors" - "fmt" - "math/rand" - "strconv" - "strings" - "sync" - "sync/atomic" - "time" - - "github.com/nats-io/nats.go/internal/parser" - "github.com/nats-io/nuid" -) - -// JetStream allows persistent messaging through JetStream. -// -// NOTE: JetStream is part of legacy API. -// Users are encouraged to switch to the new JetStream API for enhanced capabilities and -// simplified API. Please refer to the `jetstream` package. -// See: https://github.com/nats-io/nats.go/blob/main/jetstream/README.md -type JetStream interface { - // Publish publishes a message to JetStream. - Publish(subj string, data []byte, opts ...PubOpt) (*PubAck, error) - - // PublishMsg publishes a Msg to JetStream. - PublishMsg(m *Msg, opts ...PubOpt) (*PubAck, error) - - // PublishAsync publishes a message to JetStream and returns a PubAckFuture. - // The data should not be changed until the PubAckFuture has been processed. - PublishAsync(subj string, data []byte, opts ...PubOpt) (PubAckFuture, error) - - // PublishMsgAsync publishes a Msg to JetStream and returns a PubAckFuture. - // The message should not be changed until the PubAckFuture has been processed. - PublishMsgAsync(m *Msg, opts ...PubOpt) (PubAckFuture, error) - - // PublishAsyncPending returns the number of async publishes outstanding for this context. - PublishAsyncPending() int - - // PublishAsyncComplete returns a channel that will be closed when all outstanding messages are ack'd. - PublishAsyncComplete() <-chan struct{} - - // Subscribe creates an async Subscription for JetStream. - // The stream and consumer names can be provided with the nats.Bind() option. - // For creating an ephemeral (where the consumer name is picked by the server), - // you can provide the stream name with nats.BindStream(). - // If no stream name is specified, the library will attempt to figure out which - // stream the subscription is for. See important notes below for more details. - // - // IMPORTANT NOTES: - // * If none of the options Bind() nor Durable() are specified, the library will - // send a request to the server to create an ephemeral JetStream consumer, - // which will be deleted after an Unsubscribe() or Drain(), or automatically - // by the server after a short period of time after the NATS subscription is - // gone. - // * If Durable() option is specified, the library will attempt to lookup a JetStream - // consumer with this name, and if found, will bind to it and not attempt to - // delete it. However, if not found, the library will send a request to - // create such durable JetStream consumer. Note that the library will delete - // the JetStream consumer after an Unsubscribe() or Drain() only if it - // created the durable consumer while subscribing. If the durable consumer - // already existed prior to subscribing it won't be deleted. - // * If Bind() option is provided, the library will attempt to lookup the - // consumer with the given name, and if successful, bind to it. If the lookup fails, - // then the Subscribe() call will return an error. - Subscribe(subj string, cb MsgHandler, opts ...SubOpt) (*Subscription, error) - - // SubscribeSync creates a Subscription that can be used to process messages synchronously. - // See important note in Subscribe() - SubscribeSync(subj string, opts ...SubOpt) (*Subscription, error) - - // ChanSubscribe creates channel based Subscription. - // See important note in Subscribe() - ChanSubscribe(subj string, ch chan *Msg, opts ...SubOpt) (*Subscription, error) - - // ChanQueueSubscribe creates channel based Subscription with a queue group. - // See important note in QueueSubscribe() - ChanQueueSubscribe(subj, queue string, ch chan *Msg, opts ...SubOpt) (*Subscription, error) - - // QueueSubscribe creates a Subscription with a queue group. - // If no optional durable name nor binding options are specified, the queue name will be used as a durable name. - // See important note in Subscribe() - QueueSubscribe(subj, queue string, cb MsgHandler, opts ...SubOpt) (*Subscription, error) - - // QueueSubscribeSync creates a Subscription with a queue group that can be used to process messages synchronously. - // See important note in QueueSubscribe() - QueueSubscribeSync(subj, queue string, opts ...SubOpt) (*Subscription, error) - - // PullSubscribe creates a Subscription that can fetch messages. - // See important note in Subscribe(). Additionally, for an ephemeral pull consumer, the "durable" value must be - // set to an empty string. - PullSubscribe(subj, durable string, opts ...SubOpt) (*Subscription, error) -} - -// JetStreamContext allows JetStream messaging and stream management. -// -// NOTE: JetStreamContext is part of legacy API. -// Users are encouraged to switch to the new JetStream API for enhanced capabilities and -// simplified API. Please refer to the `jetstream` package. -// See: https://github.com/nats-io/nats.go/blob/main/jetstream/README.md -type JetStreamContext interface { - JetStream - JetStreamManager - KeyValueManager - ObjectStoreManager -} - -// Request API subjects for JetStream. -const ( - // defaultAPIPrefix is the default prefix for the JetStream API. - defaultAPIPrefix = "$JS.API." - - // jsDomainT is used to create JetStream API prefix by specifying only Domain - jsDomainT = "$JS.%s.API." - - // jsExtDomainT is used to create a StreamSource External APIPrefix - jsExtDomainT = "$JS.%s.API" - - // apiAccountInfo is for obtaining general information about JetStream. - apiAccountInfo = "INFO" - - // apiConsumerCreateT is used to create consumers. - // it accepts stream name and consumer name. - apiConsumerCreateT = "CONSUMER.CREATE.%s.%s" - - // apiConsumerCreateT is used to create consumers. - // it accepts stream name, consumer name and filter subject - apiConsumerCreateWithFilterSubjectT = "CONSUMER.CREATE.%s.%s.%s" - - // apiLegacyConsumerCreateT is used to create consumers. - // this is a legacy endpoint to support creating ephemerals before nats-server v2.9.0. - apiLegacyConsumerCreateT = "CONSUMER.CREATE.%s" - - // apiDurableCreateT is used to create durable consumers. - // this is a legacy endpoint to support creating durable consumers before nats-server v2.9.0. - apiDurableCreateT = "CONSUMER.DURABLE.CREATE.%s.%s" - - // apiConsumerInfoT is used to create consumers. - apiConsumerInfoT = "CONSUMER.INFO.%s.%s" - - // apiRequestNextT is the prefix for the request next message(s) for a consumer in worker/pull mode. - apiRequestNextT = "CONSUMER.MSG.NEXT.%s.%s" - - // apiConsumerDeleteT is used to delete consumers. - apiConsumerDeleteT = "CONSUMER.DELETE.%s.%s" - - // apiConsumerListT is used to return all detailed consumer information - apiConsumerListT = "CONSUMER.LIST.%s" - - // apiConsumerNamesT is used to return a list with all consumer names for the stream. - apiConsumerNamesT = "CONSUMER.NAMES.%s" - - // apiStreams can lookup a stream by subject. - apiStreams = "STREAM.NAMES" - - // apiStreamCreateT is the endpoint to create new streams. - apiStreamCreateT = "STREAM.CREATE.%s" - - // apiStreamInfoT is the endpoint to get information on a stream. - apiStreamInfoT = "STREAM.INFO.%s" - - // apiStreamUpdateT is the endpoint to update existing streams. - apiStreamUpdateT = "STREAM.UPDATE.%s" - - // apiStreamDeleteT is the endpoint to delete streams. - apiStreamDeleteT = "STREAM.DELETE.%s" - - // apiStreamPurgeT is the endpoint to purge streams. - apiStreamPurgeT = "STREAM.PURGE.%s" - - // apiStreamListT is the endpoint that will return all detailed stream information - apiStreamListT = "STREAM.LIST" - - // apiMsgGetT is the endpoint to get a message. - apiMsgGetT = "STREAM.MSG.GET.%s" - - // apiMsgGetT is the endpoint to perform a direct get of a message. - apiDirectMsgGetT = "DIRECT.GET.%s" - - // apiDirectMsgGetLastBySubjectT is the endpoint to perform a direct get of a message by subject. - apiDirectMsgGetLastBySubjectT = "DIRECT.GET.%s.%s" - - // apiMsgDeleteT is the endpoint to remove a message. - apiMsgDeleteT = "STREAM.MSG.DELETE.%s" - - // orderedHeartbeatsInterval is how fast we want HBs from the server during idle. - orderedHeartbeatsInterval = 5 * time.Second - - // Scale for threshold of missed HBs or lack of activity. - hbcThresh = 2 - - // For ChanSubscription, we can't update sub.delivered as we do for other - // type of subscriptions, since the channel is user provided. - // With flow control in play, we will check for flow control on incoming - // messages (as opposed to when they are delivered), but also from a go - // routine. Without this, the subscription would possibly stall until - // a new message or heartbeat/fc are received. - chanSubFCCheckInterval = 250 * time.Millisecond - - // Default time wait between retries on Publish iff err is NoResponders. - DefaultPubRetryWait = 250 * time.Millisecond - - // Default number of retries - DefaultPubRetryAttempts = 2 - - // defaultAsyncPubAckInflight is the number of async pub acks inflight. - defaultAsyncPubAckInflight = 4000 -) - -// Types of control messages, so far heartbeat and flow control -const ( - jsCtrlHB = 1 - jsCtrlFC = 2 -) - -// js is an internal struct from a JetStreamContext. -type js struct { - nc *Conn - opts *jsOpts - - // For async publish context. - mu sync.RWMutex - rpre string - rsub *Subscription - pafs map[string]*pubAckFuture - stc chan struct{} - dch chan struct{} - rr *rand.Rand - connStatusCh chan (Status) - replyPrefix string - replyPrefixLen int -} - -type jsOpts struct { - ctx context.Context - // For importing JetStream from other accounts. - pre string - // Amount of time to wait for API requests. - wait time.Duration - // For async publish error handling. - aecb MsgErrHandler - // Max async pub ack in flight - maxpa int - // the domain that produced the pre - domain string - // enables protocol tracing - ctrace ClientTrace - shouldTrace bool - // purgeOpts contains optional stream purge options - purgeOpts *StreamPurgeRequest - // streamInfoOpts contains optional stream info options - streamInfoOpts *StreamInfoRequest - // streamListSubject is used for subject filtering when listing streams / stream names - streamListSubject string - // For direct get message requests - directGet bool - // For direct get next message - directNextFor string - - // featureFlags are used to enable/disable specific JetStream features - featureFlags featureFlags -} - -const ( - defaultRequestWait = 5 * time.Second - defaultAccountCheck = 20 * time.Second -) - -// JetStream returns a JetStreamContext for messaging and stream management. -// Errors are only returned if inconsistent options are provided. -// -// NOTE: JetStreamContext is part of legacy API. -// Users are encouraged to switch to the new JetStream API for enhanced capabilities and -// simplified API. Please refer to the `jetstream` package. -// See: https://github.com/nats-io/nats.go/blob/main/jetstream/README.md -func (nc *Conn) JetStream(opts ...JSOpt) (JetStreamContext, error) { - js := &js{ - nc: nc, - opts: &jsOpts{ - pre: defaultAPIPrefix, - wait: defaultRequestWait, - maxpa: defaultAsyncPubAckInflight, - }, - } - inboxPrefix := InboxPrefix - if js.nc.Opts.InboxPrefix != _EMPTY_ { - inboxPrefix = js.nc.Opts.InboxPrefix + "." - } - js.replyPrefix = inboxPrefix - js.replyPrefixLen = len(js.replyPrefix) + aReplyTokensize + 1 - - for _, opt := range opts { - if err := opt.configureJSContext(js.opts); err != nil { - return nil, err - } - } - return js, nil -} - -// JSOpt configures a JetStreamContext. -type JSOpt interface { - configureJSContext(opts *jsOpts) error -} - -// jsOptFn configures an option for the JetStreamContext. -type jsOptFn func(opts *jsOpts) error - -func (opt jsOptFn) configureJSContext(opts *jsOpts) error { - return opt(opts) -} - -type featureFlags struct { - useDurableConsumerCreate bool -} - -// UseLegacyDurableConsumers makes JetStream use the legacy (pre nats-server v2.9.0) subjects for consumer creation. -// If this option is used when creating JetStremContext, $JS.API.CONSUMER.DURABLE.CREATE.. will be used -// to create a consumer with Durable provided, rather than $JS.API.CONSUMER.CREATE... -func UseLegacyDurableConsumers() JSOpt { - return jsOptFn(func(opts *jsOpts) error { - opts.featureFlags.useDurableConsumerCreate = true - return nil - }) -} - -// ClientTrace can be used to trace API interactions for the JetStream Context. -type ClientTrace struct { - RequestSent func(subj string, payload []byte) - ResponseReceived func(subj string, payload []byte, hdr Header) -} - -func (ct ClientTrace) configureJSContext(js *jsOpts) error { - js.ctrace = ct - js.shouldTrace = true - return nil -} - -// Domain changes the domain part of JetStream API prefix. -func Domain(domain string) JSOpt { - if domain == _EMPTY_ { - return APIPrefix(_EMPTY_) - } - - return jsOptFn(func(js *jsOpts) error { - js.domain = domain - js.pre = fmt.Sprintf(jsDomainT, domain) - - return nil - }) - -} - -func (s *StreamPurgeRequest) configureJSContext(js *jsOpts) error { - js.purgeOpts = s - return nil -} - -func (s *StreamInfoRequest) configureJSContext(js *jsOpts) error { - js.streamInfoOpts = s - return nil -} - -// APIPrefix changes the default prefix used for the JetStream API. -func APIPrefix(pre string) JSOpt { - return jsOptFn(func(js *jsOpts) error { - if pre == _EMPTY_ { - return nil - } - - js.pre = pre - if !strings.HasSuffix(js.pre, ".") { - js.pre = js.pre + "." - } - - return nil - }) -} - -// DirectGet is an option that can be used to make GetMsg() or GetLastMsg() -// retrieve message directly from a group of servers (leader and replicas) -// if the stream was created with the AllowDirect option. -func DirectGet() JSOpt { - return jsOptFn(func(js *jsOpts) error { - js.directGet = true - return nil - }) -} - -// DirectGetNext is an option that can be used to make GetMsg() retrieve message -// directly from a group of servers (leader and replicas) if the stream was -// created with the AllowDirect option. -// The server will find the next message matching the filter `subject` starting -// at the start sequence (argument in GetMsg()). The filter `subject` can be a -// wildcard. -func DirectGetNext(subject string) JSOpt { - return jsOptFn(func(js *jsOpts) error { - js.directGet = true - js.directNextFor = subject - return nil - }) -} - -// StreamListFilter is an option that can be used to configure `StreamsInfo()` and `StreamNames()` requests. -// It allows filtering the returned streams by subject associated with each stream. -// Wildcards can be used. For example, `StreamListFilter(FOO.*.A) will return -// all streams which have at least one subject matching the provided pattern (e.g. FOO.TEST.A). -func StreamListFilter(subject string) JSOpt { - return jsOptFn(func(opts *jsOpts) error { - opts.streamListSubject = subject - return nil - }) -} - -func (js *js) apiSubj(subj string) string { - if js.opts.pre == _EMPTY_ { - return subj - } - var b strings.Builder - b.WriteString(js.opts.pre) - b.WriteString(subj) - return b.String() -} - -// PubOpt configures options for publishing JetStream messages. -type PubOpt interface { - configurePublish(opts *pubOpts) error -} - -// pubOptFn is a function option used to configure JetStream Publish. -type pubOptFn func(opts *pubOpts) error - -func (opt pubOptFn) configurePublish(opts *pubOpts) error { - return opt(opts) -} - -type pubOpts struct { - ctx context.Context - ttl time.Duration - id string - lid string // Expected last msgId - str string // Expected stream name - seq *uint64 // Expected last sequence - lss *uint64 // Expected last sequence per subject - - // Publish retries for NoResponders err. - rwait time.Duration // Retry wait between attempts - rnum int // Retry attempts - - // stallWait is the max wait of a async pub ack. - stallWait time.Duration -} - -// pubAckResponse is the ack response from the JetStream API when publishing a message. -type pubAckResponse struct { - apiResponse - *PubAck -} - -// PubAck is an ack received after successfully publishing a message. -type PubAck struct { - Stream string `json:"stream"` - Sequence uint64 `json:"seq"` - Duplicate bool `json:"duplicate,omitempty"` - Domain string `json:"domain,omitempty"` -} - -// Headers for published messages. -const ( - MsgIdHdr = "Nats-Msg-Id" - ExpectedStreamHdr = "Nats-Expected-Stream" - ExpectedLastSeqHdr = "Nats-Expected-Last-Sequence" - ExpectedLastSubjSeqHdr = "Nats-Expected-Last-Subject-Sequence" - ExpectedLastMsgIdHdr = "Nats-Expected-Last-Msg-Id" - MsgRollup = "Nats-Rollup" -) - -// Headers for republished messages and direct gets. -const ( - JSStream = "Nats-Stream" - JSSequence = "Nats-Sequence" - JSTimeStamp = "Nats-Time-Stamp" - JSSubject = "Nats-Subject" - JSLastSequence = "Nats-Last-Sequence" -) - -// MsgSize is a header that will be part of a consumer's delivered message if HeadersOnly requested. -const MsgSize = "Nats-Msg-Size" - -// Rollups, can be subject only or all messages. -const ( - MsgRollupSubject = "sub" - MsgRollupAll = "all" -) - -// PublishMsg publishes a Msg to a stream from JetStream. -func (js *js) PublishMsg(m *Msg, opts ...PubOpt) (*PubAck, error) { - var o = pubOpts{rwait: DefaultPubRetryWait, rnum: DefaultPubRetryAttempts} - if len(opts) > 0 { - if m.Header == nil { - m.Header = Header{} - } - for _, opt := range opts { - if err := opt.configurePublish(&o); err != nil { - return nil, err - } - } - } - // Check for option collisions. Right now just timeout and context. - if o.ctx != nil && o.ttl != 0 { - return nil, ErrContextAndTimeout - } - if o.ttl == 0 && o.ctx == nil { - o.ttl = js.opts.wait - } - if o.stallWait > 0 { - return nil, fmt.Errorf("nats: stall wait cannot be set to sync publish") - } - - if o.id != _EMPTY_ { - m.Header.Set(MsgIdHdr, o.id) - } - if o.lid != _EMPTY_ { - m.Header.Set(ExpectedLastMsgIdHdr, o.lid) - } - if o.str != _EMPTY_ { - m.Header.Set(ExpectedStreamHdr, o.str) - } - if o.seq != nil { - m.Header.Set(ExpectedLastSeqHdr, strconv.FormatUint(*o.seq, 10)) - } - if o.lss != nil { - m.Header.Set(ExpectedLastSubjSeqHdr, strconv.FormatUint(*o.lss, 10)) - } - - var resp *Msg - var err error - - if o.ttl > 0 { - resp, err = js.nc.RequestMsg(m, time.Duration(o.ttl)) - } else { - resp, err = js.nc.RequestMsgWithContext(o.ctx, m) - } - - if err != nil { - for r, ttl := 0, o.ttl; errors.Is(err, ErrNoResponders) && (r < o.rnum || o.rnum < 0); r++ { - // To protect against small blips in leadership changes etc, if we get a no responders here retry. - if o.ctx != nil { - select { - case <-o.ctx.Done(): - case <-time.After(o.rwait): - } - } else { - time.Sleep(o.rwait) - } - if o.ttl > 0 { - ttl -= o.rwait - if ttl <= 0 { - err = ErrTimeout - break - } - resp, err = js.nc.RequestMsg(m, time.Duration(ttl)) - } else { - resp, err = js.nc.RequestMsgWithContext(o.ctx, m) - } - } - if err != nil { - if errors.Is(err, ErrNoResponders) { - err = ErrNoStreamResponse - } - return nil, err - } - } - - var pa pubAckResponse - if err := json.Unmarshal(resp.Data, &pa); err != nil { - return nil, ErrInvalidJSAck - } - if pa.Error != nil { - return nil, pa.Error - } - if pa.PubAck == nil || pa.PubAck.Stream == _EMPTY_ { - return nil, ErrInvalidJSAck - } - return pa.PubAck, nil -} - -// Publish publishes a message to a stream from JetStream. -func (js *js) Publish(subj string, data []byte, opts ...PubOpt) (*PubAck, error) { - return js.PublishMsg(&Msg{Subject: subj, Data: data}, opts...) -} - -// PubAckFuture is a future for a PubAck. -type PubAckFuture interface { - // Ok returns a receive only channel that can be used to get a PubAck. - Ok() <-chan *PubAck - - // Err returns a receive only channel that can be used to get the error from an async publish. - Err() <-chan error - - // Msg returns the message that was sent to the server. - Msg() *Msg -} - -type pubAckFuture struct { - js *js - msg *Msg - pa *PubAck - st time.Time - err error - errCh chan error - doneCh chan *PubAck -} - -func (paf *pubAckFuture) Ok() <-chan *PubAck { - paf.js.mu.Lock() - defer paf.js.mu.Unlock() - - if paf.doneCh == nil { - paf.doneCh = make(chan *PubAck, 1) - if paf.pa != nil { - paf.doneCh <- paf.pa - } - } - - return paf.doneCh -} - -func (paf *pubAckFuture) Err() <-chan error { - paf.js.mu.Lock() - defer paf.js.mu.Unlock() - - if paf.errCh == nil { - paf.errCh = make(chan error, 1) - if paf.err != nil { - paf.errCh <- paf.err - } - } - - return paf.errCh -} - -func (paf *pubAckFuture) Msg() *Msg { - paf.js.mu.RLock() - defer paf.js.mu.RUnlock() - return paf.msg -} - -// For quick token lookup etc. -const aReplyTokensize = 6 - -func (js *js) newAsyncReply() string { - js.mu.Lock() - if js.rsub == nil { - // Create our wildcard reply subject. - sha := sha256.New() - sha.Write([]byte(nuid.Next())) - b := sha.Sum(nil) - for i := 0; i < aReplyTokensize; i++ { - b[i] = rdigits[int(b[i]%base)] - } - js.rpre = fmt.Sprintf("%s%s.", js.replyPrefix, b[:aReplyTokensize]) - sub, err := js.nc.Subscribe(fmt.Sprintf("%s*", js.rpre), js.handleAsyncReply) - if err != nil { - js.mu.Unlock() - return _EMPTY_ - } - js.rsub = sub - js.rr = rand.New(rand.NewSource(time.Now().UnixNano())) - } - if js.connStatusCh == nil { - js.connStatusCh = js.nc.StatusChanged(RECONNECTING, CLOSED) - go js.resetPendingAcksOnReconnect() - } - var sb strings.Builder - sb.WriteString(js.rpre) - rn := js.rr.Int63() - var b [aReplyTokensize]byte - for i, l := 0, rn; i < len(b); i++ { - b[i] = rdigits[l%base] - l /= base - } - sb.Write(b[:]) - js.mu.Unlock() - return sb.String() -} - -func (js *js) resetPendingAcksOnReconnect() { - js.mu.Lock() - connStatusCh := js.connStatusCh - js.mu.Unlock() - for { - newStatus, ok := <-connStatusCh - if !ok || newStatus == CLOSED { - return - } - js.mu.Lock() - for _, paf := range js.pafs { - paf.err = ErrDisconnected - } - js.pafs = nil - if js.dch != nil { - close(js.dch) - js.dch = nil - } - js.mu.Unlock() - } -} - -func (js *js) cleanupReplySub() { - js.mu.Lock() - if js.rsub != nil { - js.rsub.Unsubscribe() - js.rsub = nil - } - if js.connStatusCh != nil { - close(js.connStatusCh) - js.connStatusCh = nil - } - js.mu.Unlock() -} - -// registerPAF will register for a PubAckFuture. -func (js *js) registerPAF(id string, paf *pubAckFuture) (int, int) { - js.mu.Lock() - if js.pafs == nil { - js.pafs = make(map[string]*pubAckFuture) - } - paf.js = js - js.pafs[id] = paf - np := len(js.pafs) - maxpa := js.opts.maxpa - js.mu.Unlock() - return np, maxpa -} - -// Lock should be held. -func (js *js) getPAF(id string) *pubAckFuture { - if js.pafs == nil { - return nil - } - return js.pafs[id] -} - -// clearPAF will remove a PubAckFuture that was registered. -func (js *js) clearPAF(id string) { - js.mu.Lock() - delete(js.pafs, id) - js.mu.Unlock() -} - -// PublishAsyncPending returns how many PubAckFutures are pending. -func (js *js) PublishAsyncPending() int { - js.mu.RLock() - defer js.mu.RUnlock() - return len(js.pafs) -} - -func (js *js) asyncStall() <-chan struct{} { - js.mu.Lock() - if js.stc == nil { - js.stc = make(chan struct{}) - } - stc := js.stc - js.mu.Unlock() - return stc -} - -// Handle an async reply from PublishAsync. -func (js *js) handleAsyncReply(m *Msg) { - if len(m.Subject) <= js.replyPrefixLen { - return - } - id := m.Subject[js.replyPrefixLen:] - - js.mu.Lock() - paf := js.getPAF(id) - if paf == nil { - js.mu.Unlock() - return - } - // Remove - delete(js.pafs, id) - - // Check on anyone stalled and waiting. - if js.stc != nil && len(js.pafs) < js.opts.maxpa { - close(js.stc) - js.stc = nil - } - // Check on anyone one waiting on done status. - if js.dch != nil && len(js.pafs) == 0 { - dch := js.dch - js.dch = nil - // Defer here so error is processed and can be checked. - defer close(dch) - } - - doErr := func(err error) { - paf.err = err - if paf.errCh != nil { - paf.errCh <- paf.err - } - cb := js.opts.aecb - js.mu.Unlock() - if cb != nil { - cb(paf.js, paf.msg, err) - } - } - - // Process no responders etc. - if len(m.Data) == 0 && m.Header.Get(statusHdr) == noResponders { - doErr(ErrNoResponders) - return - } - - var pa pubAckResponse - if err := json.Unmarshal(m.Data, &pa); err != nil { - doErr(ErrInvalidJSAck) - return - } - if pa.Error != nil { - doErr(pa.Error) - return - } - if pa.PubAck == nil || pa.PubAck.Stream == _EMPTY_ { - doErr(ErrInvalidJSAck) - return - } - - // So here we have received a proper puback. - paf.pa = pa.PubAck - if paf.doneCh != nil { - paf.doneCh <- paf.pa - } - js.mu.Unlock() -} - -// MsgErrHandler is used to process asynchronous errors from -// JetStream PublishAsync. It will return the original -// message sent to the server for possible retransmitting and the error encountered. -type MsgErrHandler func(JetStream, *Msg, error) - -// PublishAsyncErrHandler sets the error handler for async publishes in JetStream. -func PublishAsyncErrHandler(cb MsgErrHandler) JSOpt { - return jsOptFn(func(js *jsOpts) error { - js.aecb = cb - return nil - }) -} - -// PublishAsyncMaxPending sets the maximum outstanding async publishes that can be inflight at one time. -func PublishAsyncMaxPending(max int) JSOpt { - return jsOptFn(func(js *jsOpts) error { - if max < 1 { - return errors.New("nats: max ack pending should be >= 1") - } - js.maxpa = max - return nil - }) -} - -// PublishAsync publishes a message to JetStream and returns a PubAckFuture -func (js *js) PublishAsync(subj string, data []byte, opts ...PubOpt) (PubAckFuture, error) { - return js.PublishMsgAsync(&Msg{Subject: subj, Data: data}, opts...) -} - -const defaultStallWait = 200 * time.Millisecond - -func (js *js) PublishMsgAsync(m *Msg, opts ...PubOpt) (PubAckFuture, error) { - var o pubOpts - if len(opts) > 0 { - if m.Header == nil { - m.Header = Header{} - } - for _, opt := range opts { - if err := opt.configurePublish(&o); err != nil { - return nil, err - } - } - } - - // Timeouts and contexts do not make sense for these. - if o.ttl != 0 || o.ctx != nil { - return nil, ErrContextAndTimeout - } - stallWait := defaultStallWait - if o.stallWait > 0 { - stallWait = o.stallWait - } - - // FIXME(dlc) - Make common. - if o.id != _EMPTY_ { - m.Header.Set(MsgIdHdr, o.id) - } - if o.lid != _EMPTY_ { - m.Header.Set(ExpectedLastMsgIdHdr, o.lid) - } - if o.str != _EMPTY_ { - m.Header.Set(ExpectedStreamHdr, o.str) - } - if o.seq != nil { - m.Header.Set(ExpectedLastSeqHdr, strconv.FormatUint(*o.seq, 10)) - } - if o.lss != nil { - m.Header.Set(ExpectedLastSubjSeqHdr, strconv.FormatUint(*o.lss, 10)) - } - - // Reply - if m.Reply != _EMPTY_ { - return nil, errors.New("nats: reply subject should be empty") - } - reply := m.Reply - m.Reply = js.newAsyncReply() - defer func() { m.Reply = reply }() - - if m.Reply == _EMPTY_ { - return nil, errors.New("nats: error creating async reply handler") - } - - id := m.Reply[js.replyPrefixLen:] - paf := &pubAckFuture{msg: m, st: time.Now()} - numPending, maxPending := js.registerPAF(id, paf) - - if maxPending > 0 && numPending >= maxPending { - select { - case <-js.asyncStall(): - case <-time.After(stallWait): - js.clearPAF(id) - return nil, errors.New("nats: stalled with too many outstanding async published messages") - } - } - if err := js.nc.PublishMsg(m); err != nil { - js.clearPAF(id) - return nil, err - } - - return paf, nil -} - -// PublishAsyncComplete returns a channel that will be closed when all outstanding messages have been ack'd. -func (js *js) PublishAsyncComplete() <-chan struct{} { - js.mu.Lock() - defer js.mu.Unlock() - if js.dch == nil { - js.dch = make(chan struct{}) - } - dch := js.dch - if len(js.pafs) == 0 { - close(js.dch) - js.dch = nil - } - return dch -} - -// MsgId sets the message ID used for deduplication. -func MsgId(id string) PubOpt { - return pubOptFn(func(opts *pubOpts) error { - opts.id = id - return nil - }) -} - -// ExpectStream sets the expected stream to respond from the publish. -func ExpectStream(stream string) PubOpt { - return pubOptFn(func(opts *pubOpts) error { - opts.str = stream - return nil - }) -} - -// ExpectLastSequence sets the expected sequence in the response from the publish. -func ExpectLastSequence(seq uint64) PubOpt { - return pubOptFn(func(opts *pubOpts) error { - opts.seq = &seq - return nil - }) -} - -// ExpectLastSequencePerSubject sets the expected sequence per subject in the response from the publish. -func ExpectLastSequencePerSubject(seq uint64) PubOpt { - return pubOptFn(func(opts *pubOpts) error { - opts.lss = &seq - return nil - }) -} - -// ExpectLastMsgId sets the expected last msgId in the response from the publish. -func ExpectLastMsgId(id string) PubOpt { - return pubOptFn(func(opts *pubOpts) error { - opts.lid = id - return nil - }) -} - -// RetryWait sets the retry wait time when ErrNoResponders is encountered. -func RetryWait(dur time.Duration) PubOpt { - return pubOptFn(func(opts *pubOpts) error { - opts.rwait = dur - return nil - }) -} - -// RetryAttempts sets the retry number of attempts when ErrNoResponders is encountered. -func RetryAttempts(num int) PubOpt { - return pubOptFn(func(opts *pubOpts) error { - opts.rnum = num - return nil - }) -} - -// StallWait sets the max wait when the producer becomes stall producing messages. -func StallWait(ttl time.Duration) PubOpt { - return pubOptFn(func(opts *pubOpts) error { - if ttl <= 0 { - return fmt.Errorf("nats: stall wait should be more than 0") - } - opts.stallWait = ttl - return nil - }) -} - -type ackOpts struct { - ttl time.Duration - ctx context.Context - nakDelay time.Duration -} - -// AckOpt are the options that can be passed when acknowledge a message. -type AckOpt interface { - configureAck(opts *ackOpts) error -} - -// MaxWait sets the maximum amount of time we will wait for a response. -type MaxWait time.Duration - -func (ttl MaxWait) configureJSContext(js *jsOpts) error { - js.wait = time.Duration(ttl) - return nil -} - -func (ttl MaxWait) configurePull(opts *pullOpts) error { - opts.ttl = time.Duration(ttl) - return nil -} - -// AckWait sets the maximum amount of time we will wait for an ack. -type AckWait time.Duration - -func (ttl AckWait) configurePublish(opts *pubOpts) error { - opts.ttl = time.Duration(ttl) - return nil -} - -func (ttl AckWait) configureSubscribe(opts *subOpts) error { - opts.cfg.AckWait = time.Duration(ttl) - return nil -} - -func (ttl AckWait) configureAck(opts *ackOpts) error { - opts.ttl = time.Duration(ttl) - return nil -} - -// ContextOpt is an option used to set a context.Context. -type ContextOpt struct { - context.Context -} - -func (ctx ContextOpt) configureJSContext(opts *jsOpts) error { - opts.ctx = ctx - return nil -} - -func (ctx ContextOpt) configurePublish(opts *pubOpts) error { - opts.ctx = ctx - return nil -} - -func (ctx ContextOpt) configureSubscribe(opts *subOpts) error { - opts.ctx = ctx - return nil -} - -func (ctx ContextOpt) configurePull(opts *pullOpts) error { - opts.ctx = ctx - return nil -} - -func (ctx ContextOpt) configureAck(opts *ackOpts) error { - opts.ctx = ctx - return nil -} - -// Context returns an option that can be used to configure a context for APIs -// that are context aware such as those part of the JetStream interface. -func Context(ctx context.Context) ContextOpt { - return ContextOpt{ctx} -} - -type nakDelay time.Duration - -func (d nakDelay) configureAck(opts *ackOpts) error { - opts.nakDelay = time.Duration(d) - return nil -} - -// Subscribe - -// ConsumerConfig is the configuration of a JetStream consumer. -type ConsumerConfig struct { - Durable string `json:"durable_name,omitempty"` - Name string `json:"name,omitempty"` - Description string `json:"description,omitempty"` - DeliverPolicy DeliverPolicy `json:"deliver_policy"` - OptStartSeq uint64 `json:"opt_start_seq,omitempty"` - OptStartTime *time.Time `json:"opt_start_time,omitempty"` - AckPolicy AckPolicy `json:"ack_policy"` - AckWait time.Duration `json:"ack_wait,omitempty"` - MaxDeliver int `json:"max_deliver,omitempty"` - BackOff []time.Duration `json:"backoff,omitempty"` - FilterSubject string `json:"filter_subject,omitempty"` - FilterSubjects []string `json:"filter_subjects,omitempty"` - ReplayPolicy ReplayPolicy `json:"replay_policy"` - RateLimit uint64 `json:"rate_limit_bps,omitempty"` // Bits per sec - SampleFrequency string `json:"sample_freq,omitempty"` - MaxWaiting int `json:"max_waiting,omitempty"` - MaxAckPending int `json:"max_ack_pending,omitempty"` - FlowControl bool `json:"flow_control,omitempty"` - Heartbeat time.Duration `json:"idle_heartbeat,omitempty"` - HeadersOnly bool `json:"headers_only,omitempty"` - - // Pull based options. - MaxRequestBatch int `json:"max_batch,omitempty"` - MaxRequestExpires time.Duration `json:"max_expires,omitempty"` - MaxRequestMaxBytes int `json:"max_bytes,omitempty"` - - // Push based consumers. - DeliverSubject string `json:"deliver_subject,omitempty"` - DeliverGroup string `json:"deliver_group,omitempty"` - - // Inactivity threshold. - InactiveThreshold time.Duration `json:"inactive_threshold,omitempty"` - - // Generally inherited by parent stream and other markers, now can be configured directly. - Replicas int `json:"num_replicas"` - // Force memory storage. - MemoryStorage bool `json:"mem_storage,omitempty"` - - // Metadata is additional metadata for the Consumer. - // Keys starting with `_nats` are reserved. - // NOTE: Metadata requires nats-server v2.10.0+ - Metadata map[string]string `json:"metadata,omitempty"` -} - -// ConsumerInfo is the info from a JetStream consumer. -type ConsumerInfo struct { - Stream string `json:"stream_name"` - Name string `json:"name"` - Created time.Time `json:"created"` - Config ConsumerConfig `json:"config"` - Delivered SequenceInfo `json:"delivered"` - AckFloor SequenceInfo `json:"ack_floor"` - NumAckPending int `json:"num_ack_pending"` - NumRedelivered int `json:"num_redelivered"` - NumWaiting int `json:"num_waiting"` - NumPending uint64 `json:"num_pending"` - Cluster *ClusterInfo `json:"cluster,omitempty"` - PushBound bool `json:"push_bound,omitempty"` -} - -// SequenceInfo has both the consumer and the stream sequence and last activity. -type SequenceInfo struct { - Consumer uint64 `json:"consumer_seq"` - Stream uint64 `json:"stream_seq"` - Last *time.Time `json:"last_active,omitempty"` -} - -// SequencePair includes the consumer and stream sequence info from a JetStream consumer. -type SequencePair struct { - Consumer uint64 `json:"consumer_seq"` - Stream uint64 `json:"stream_seq"` -} - -// nextRequest is for getting next messages for pull based consumers from JetStream. -type nextRequest struct { - Expires time.Duration `json:"expires,omitempty"` - Batch int `json:"batch,omitempty"` - NoWait bool `json:"no_wait,omitempty"` - MaxBytes int `json:"max_bytes,omitempty"` - Heartbeat time.Duration `json:"idle_heartbeat,omitempty"` -} - -// jsSub includes JetStream subscription info. -type jsSub struct { - js *js - - // For pull subscribers, this is the next message subject to send requests to. - nms string - - psubj string // the subject that was passed by user to the subscribe calls - consumer string - stream string - deliver string - pull bool - dc bool // Delete JS consumer - ackNone bool - - // This is ConsumerInfo's Pending+Consumer.Delivered that we get from the - // add consumer response. Note that some versions of the server gather the - // consumer info *after* the creation of the consumer, which means that - // some messages may have been already delivered. So the sum of the two - // is a more accurate representation of the number of messages pending or - // in the process of being delivered to the subscription when created. - pending uint64 - - // Ordered consumers - ordered bool - dseq uint64 - sseq uint64 - ccreq *createConsumerRequest - - // Heartbeats and Flow Control handling from push consumers. - hbc *time.Timer - hbi time.Duration - active bool - cmeta string - fcr string - fcd uint64 - fciseq uint64 - csfct *time.Timer - - // Cancellation function to cancel context on drain/unsubscribe. - cancel func() -} - -// Deletes the JS Consumer. -// No connection nor subscription lock must be held on entry. -func (sub *Subscription) deleteConsumer() error { - sub.mu.Lock() - jsi := sub.jsi - if jsi == nil { - sub.mu.Unlock() - return nil - } - if jsi.stream == _EMPTY_ || jsi.consumer == _EMPTY_ { - sub.mu.Unlock() - return nil - } - stream, consumer := jsi.stream, jsi.consumer - js := jsi.js - sub.mu.Unlock() - - return js.DeleteConsumer(stream, consumer) -} - -// SubOpt configures options for subscribing to JetStream consumers. -type SubOpt interface { - configureSubscribe(opts *subOpts) error -} - -// subOptFn is a function option used to configure a JetStream Subscribe. -type subOptFn func(opts *subOpts) error - -func (opt subOptFn) configureSubscribe(opts *subOpts) error { - return opt(opts) -} - -// Subscribe creates an async Subscription for JetStream. -// The stream and consumer names can be provided with the nats.Bind() option. -// For creating an ephemeral (where the consumer name is picked by the server), -// you can provide the stream name with nats.BindStream(). -// If no stream name is specified, the library will attempt to figure out which -// stream the subscription is for. See important notes below for more details. -// -// IMPORTANT NOTES: -// * If none of the options Bind() nor Durable() are specified, the library will -// send a request to the server to create an ephemeral JetStream consumer, -// which will be deleted after an Unsubscribe() or Drain(), or automatically -// by the server after a short period of time after the NATS subscription is -// gone. -// * If Durable() option is specified, the library will attempt to lookup a JetStream -// consumer with this name, and if found, will bind to it and not attempt to -// delete it. However, if not found, the library will send a request to create -// such durable JetStream consumer. The library will delete the JetStream consumer -// after an Unsubscribe() or Drain(). -// * If Bind() option is provided, the library will attempt to lookup the -// consumer with the given name, and if successful, bind to it. If the lookup fails, -// then the Subscribe() call will return an error. -func (js *js) Subscribe(subj string, cb MsgHandler, opts ...SubOpt) (*Subscription, error) { - if cb == nil { - return nil, ErrBadSubscription - } - return js.subscribe(subj, _EMPTY_, cb, nil, false, false, opts) -} - -// SubscribeSync creates a Subscription that can be used to process messages synchronously. -// See important note in Subscribe() -func (js *js) SubscribeSync(subj string, opts ...SubOpt) (*Subscription, error) { - mch := make(chan *Msg, js.nc.Opts.SubChanLen) - return js.subscribe(subj, _EMPTY_, nil, mch, true, false, opts) -} - -// QueueSubscribe creates a Subscription with a queue group. -// If no optional durable name nor binding options are specified, the queue name will be used as a durable name. -// See important note in Subscribe() -func (js *js) QueueSubscribe(subj, queue string, cb MsgHandler, opts ...SubOpt) (*Subscription, error) { - if cb == nil { - return nil, ErrBadSubscription - } - return js.subscribe(subj, queue, cb, nil, false, false, opts) -} - -// QueueSubscribeSync creates a Subscription with a queue group that can be used to process messages synchronously. -// See important note in QueueSubscribe() -func (js *js) QueueSubscribeSync(subj, queue string, opts ...SubOpt) (*Subscription, error) { - mch := make(chan *Msg, js.nc.Opts.SubChanLen) - return js.subscribe(subj, queue, nil, mch, true, false, opts) -} - -// ChanSubscribe creates channel based Subscription. -// Using ChanSubscribe without buffered capacity is not recommended since -// it will be prone to dropping messages with a slow consumer error. Make sure to give the channel enough -// capacity to handle bursts in traffic, for example other Subscribe APIs use a default of 512k capacity in comparison. -// See important note in Subscribe() -func (js *js) ChanSubscribe(subj string, ch chan *Msg, opts ...SubOpt) (*Subscription, error) { - return js.subscribe(subj, _EMPTY_, nil, ch, false, false, opts) -} - -// ChanQueueSubscribe creates channel based Subscription with a queue group. -// See important note in QueueSubscribe() -func (js *js) ChanQueueSubscribe(subj, queue string, ch chan *Msg, opts ...SubOpt) (*Subscription, error) { - return js.subscribe(subj, queue, nil, ch, false, false, opts) -} - -// PullSubscribe creates a Subscription that can fetch messages. -// See important note in Subscribe() -func (js *js) PullSubscribe(subj, durable string, opts ...SubOpt) (*Subscription, error) { - mch := make(chan *Msg, js.nc.Opts.SubChanLen) - if durable != "" { - opts = append(opts, Durable(durable)) - } - return js.subscribe(subj, _EMPTY_, nil, mch, true, true, opts) -} - -func processConsInfo(info *ConsumerInfo, userCfg *ConsumerConfig, isPullMode bool, subj, queue string) (string, error) { - ccfg := &info.Config - - // Make sure this new subject matches or is a subset. - if ccfg.FilterSubject != _EMPTY_ && subj != ccfg.FilterSubject { - return _EMPTY_, ErrSubjectMismatch - } - - // Prevent binding a subscription against incompatible consumer types. - if isPullMode && ccfg.DeliverSubject != _EMPTY_ { - return _EMPTY_, ErrPullSubscribeToPushConsumer - } else if !isPullMode && ccfg.DeliverSubject == _EMPTY_ { - return _EMPTY_, ErrPullSubscribeRequired - } - - // If pull mode, nothing else to check here. - if isPullMode { - return _EMPTY_, checkConfig(ccfg, userCfg) - } - - // At this point, we know the user wants push mode, and the JS consumer is - // really push mode. - - dg := info.Config.DeliverGroup - if dg == _EMPTY_ { - // Prevent an user from attempting to create a queue subscription on - // a JS consumer that was not created with a deliver group. - if queue != _EMPTY_ { - return _EMPTY_, fmt.Errorf("cannot create a queue subscription for a consumer without a deliver group") - } else if info.PushBound { - // Need to reject a non queue subscription to a non queue consumer - // if the consumer is already bound. - return _EMPTY_, fmt.Errorf("consumer is already bound to a subscription") - } - } else { - // If the JS consumer has a deliver group, we need to fail a non queue - // subscription attempt: - if queue == _EMPTY_ { - return _EMPTY_, fmt.Errorf("cannot create a subscription for a consumer with a deliver group %q", dg) - } else if queue != dg { - // Here the user's queue group name does not match the one associated - // with the JS consumer. - return _EMPTY_, fmt.Errorf("cannot create a queue subscription %q for a consumer with a deliver group %q", - queue, dg) - } - } - if err := checkConfig(ccfg, userCfg); err != nil { - return _EMPTY_, err - } - return ccfg.DeliverSubject, nil -} - -func checkConfig(s, u *ConsumerConfig) error { - makeErr := func(fieldName string, usrVal, srvVal any) error { - return fmt.Errorf("configuration requests %s to be %v, but consumer's value is %v", fieldName, usrVal, srvVal) - } - - if u.Durable != _EMPTY_ && u.Durable != s.Durable { - return makeErr("durable", u.Durable, s.Durable) - } - if u.Description != _EMPTY_ && u.Description != s.Description { - return makeErr("description", u.Description, s.Description) - } - if u.DeliverPolicy != deliverPolicyNotSet && u.DeliverPolicy != s.DeliverPolicy { - return makeErr("deliver policy", u.DeliverPolicy, s.DeliverPolicy) - } - if u.OptStartSeq > 0 && u.OptStartSeq != s.OptStartSeq { - return makeErr("optional start sequence", u.OptStartSeq, s.OptStartSeq) - } - if u.OptStartTime != nil && !u.OptStartTime.IsZero() && !(*u.OptStartTime).Equal(*s.OptStartTime) { - return makeErr("optional start time", u.OptStartTime, s.OptStartTime) - } - if u.AckPolicy != ackPolicyNotSet && u.AckPolicy != s.AckPolicy { - return makeErr("ack policy", u.AckPolicy, s.AckPolicy) - } - if u.AckWait > 0 && u.AckWait != s.AckWait { - return makeErr("ack wait", u.AckWait, s.AckWait) - } - if u.MaxDeliver > 0 && u.MaxDeliver != s.MaxDeliver { - return makeErr("max deliver", u.MaxDeliver, s.MaxDeliver) - } - if u.ReplayPolicy != replayPolicyNotSet && u.ReplayPolicy != s.ReplayPolicy { - return makeErr("replay policy", u.ReplayPolicy, s.ReplayPolicy) - } - if u.RateLimit > 0 && u.RateLimit != s.RateLimit { - return makeErr("rate limit", u.RateLimit, s.RateLimit) - } - if u.SampleFrequency != _EMPTY_ && u.SampleFrequency != s.SampleFrequency { - return makeErr("sample frequency", u.SampleFrequency, s.SampleFrequency) - } - if u.MaxWaiting > 0 && u.MaxWaiting != s.MaxWaiting { - return makeErr("max waiting", u.MaxWaiting, s.MaxWaiting) - } - if u.MaxAckPending > 0 && u.MaxAckPending != s.MaxAckPending { - return makeErr("max ack pending", u.MaxAckPending, s.MaxAckPending) - } - // For flow control, we want to fail if the user explicit wanted it, but - // it is not set in the existing consumer. If it is not asked by the user, - // the library still handles it and so no reason to fail. - if u.FlowControl && !s.FlowControl { - return makeErr("flow control", u.FlowControl, s.FlowControl) - } - if u.Heartbeat > 0 && u.Heartbeat != s.Heartbeat { - return makeErr("heartbeat", u.Heartbeat, s.Heartbeat) - } - if u.Replicas > 0 && u.Replicas != s.Replicas { - return makeErr("replicas", u.Replicas, s.Replicas) - } - if u.MemoryStorage && !s.MemoryStorage { - return makeErr("memory storage", u.MemoryStorage, s.MemoryStorage) - } - return nil -} - -func (js *js) subscribe(subj, queue string, cb MsgHandler, ch chan *Msg, isSync, isPullMode bool, opts []SubOpt) (*Subscription, error) { - cfg := ConsumerConfig{ - DeliverPolicy: deliverPolicyNotSet, - AckPolicy: ackPolicyNotSet, - ReplayPolicy: replayPolicyNotSet, - } - o := subOpts{cfg: &cfg} - if len(opts) > 0 { - for _, opt := range opts { - if opt == nil { - continue - } - if err := opt.configureSubscribe(&o); err != nil { - return nil, err - } - } - } - - // If no stream name is specified, the subject cannot be empty. - if subj == _EMPTY_ && o.stream == _EMPTY_ { - return nil, fmt.Errorf("nats: subject required") - } - - // Note that these may change based on the consumer info response we may get. - hasHeartbeats := o.cfg.Heartbeat > 0 - hasFC := o.cfg.FlowControl - - // Some checks for pull subscribers - if isPullMode { - // No deliver subject should be provided - if o.cfg.DeliverSubject != _EMPTY_ { - return nil, ErrPullSubscribeToPushConsumer - } - } - - // Some check/setting specific to queue subs - if queue != _EMPTY_ { - // Queue subscriber cannot have HB or FC (since messages will be randomly dispatched - // to members). We may in the future have a separate NATS subscription that all members - // would subscribe to and server would send on. - if o.cfg.Heartbeat > 0 || o.cfg.FlowControl { - // Not making this a public ErrXXX in case we allow in the future. - return nil, fmt.Errorf("nats: queue subscription doesn't support idle heartbeat nor flow control") - } - - // If this is a queue subscription and no consumer nor durable name was specified, - // then we will use the queue name as a durable name. - if o.consumer == _EMPTY_ && o.cfg.Durable == _EMPTY_ { - if err := checkConsumerName(queue); err != nil { - return nil, err - } - o.cfg.Durable = queue - } - } - - var ( - err error - shouldCreate bool - info *ConsumerInfo - deliver string - stream = o.stream - consumer = o.consumer - isDurable = o.cfg.Durable != _EMPTY_ - consumerBound = o.bound - ctx = o.ctx - skipCInfo = o.skipCInfo - notFoundErr bool - lookupErr bool - nc = js.nc - nms string - hbi time.Duration - ccreq *createConsumerRequest // In case we need to hold onto it for ordered consumers. - maxap int - ) - - // Do some quick checks here for ordered consumers. We do these here instead of spread out - // in the individual SubOpts. - if o.ordered { - // Make sure we are not durable. - if isDurable { - return nil, fmt.Errorf("nats: durable can not be set for an ordered consumer") - } - // Check ack policy. - if o.cfg.AckPolicy != ackPolicyNotSet { - return nil, fmt.Errorf("nats: ack policy can not be set for an ordered consumer") - } - // Check max deliver. - if o.cfg.MaxDeliver != 1 && o.cfg.MaxDeliver != 0 { - return nil, fmt.Errorf("nats: max deliver can not be set for an ordered consumer") - } - // No deliver subject, we pick our own. - if o.cfg.DeliverSubject != _EMPTY_ { - return nil, fmt.Errorf("nats: deliver subject can not be set for an ordered consumer") - } - // Queue groups not allowed. - if queue != _EMPTY_ { - return nil, fmt.Errorf("nats: queues not be set for an ordered consumer") - } - // Check for bound consumers. - if consumer != _EMPTY_ { - return nil, fmt.Errorf("nats: can not bind existing consumer for an ordered consumer") - } - // Check for pull mode. - if isPullMode { - return nil, fmt.Errorf("nats: can not use pull mode for an ordered consumer") - } - // Setup how we need it to be here. - o.cfg.FlowControl = true - o.cfg.AckPolicy = AckNonePolicy - o.cfg.MaxDeliver = 1 - o.cfg.AckWait = 22 * time.Hour // Just set to something known, not utilized. - // Force R1 and MemoryStorage for these. - o.cfg.Replicas = 1 - o.cfg.MemoryStorage = true - - if !hasHeartbeats { - o.cfg.Heartbeat = orderedHeartbeatsInterval - } - hasFC, hasHeartbeats = true, true - o.mack = true // To avoid auto-ack wrapping call below. - hbi = o.cfg.Heartbeat - } - - // In case a consumer has not been set explicitly, then the - // durable name will be used as the consumer name. - if consumer == _EMPTY_ { - consumer = o.cfg.Durable - } - - // Find the stream mapped to the subject if not bound to a stream already. - if stream == _EMPTY_ { - stream, err = js.StreamNameBySubject(subj) - if err != nil { - return nil, err - } - } - - // With an explicit durable name, we can lookup the consumer first - // to which it should be attaching to. - // If SkipConsumerLookup was used, do not call consumer info. - if consumer != _EMPTY_ && !o.skipCInfo { - info, err = js.ConsumerInfo(stream, consumer) - notFoundErr = errors.Is(err, ErrConsumerNotFound) - lookupErr = err == ErrJetStreamNotEnabled || errors.Is(err, ErrTimeout) || errors.Is(err, context.DeadlineExceeded) - } - - switch { - case info != nil: - deliver, err = processConsInfo(info, o.cfg, isPullMode, subj, queue) - if err != nil { - return nil, err - } - icfg := &info.Config - hasFC, hbi = icfg.FlowControl, icfg.Heartbeat - hasHeartbeats = hbi > 0 - maxap = icfg.MaxAckPending - case (err != nil && !notFoundErr) || (notFoundErr && consumerBound): - // If the consumer is being bound and we got an error on pull subscribe then allow the error. - if !(isPullMode && lookupErr && consumerBound) { - return nil, err - } - case skipCInfo: - // When skipping consumer info, need to rely on the manually passed sub options - // to match the expected behavior from the subscription. - hasFC, hbi = o.cfg.FlowControl, o.cfg.Heartbeat - hasHeartbeats = hbi > 0 - maxap = o.cfg.MaxAckPending - deliver = o.cfg.DeliverSubject - if consumerBound { - break - } - - // When not bound to a consumer already, proceed to create. - fallthrough - default: - // Attempt to create consumer if not found nor using Bind. - shouldCreate = true - if o.cfg.DeliverSubject != _EMPTY_ { - deliver = o.cfg.DeliverSubject - } else if !isPullMode { - deliver = nc.NewInbox() - cfg.DeliverSubject = deliver - } - // Do filtering always, server will clear as needed. - cfg.FilterSubject = subj - - // Pass the queue to the consumer config - if queue != _EMPTY_ { - cfg.DeliverGroup = queue - } - - // If not set, default to deliver all - if cfg.DeliverPolicy == deliverPolicyNotSet { - cfg.DeliverPolicy = DeliverAllPolicy - } - // If not set, default to ack explicit. - if cfg.AckPolicy == ackPolicyNotSet { - cfg.AckPolicy = AckExplicitPolicy - } - // If not set, default to instant - if cfg.ReplayPolicy == replayPolicyNotSet { - cfg.ReplayPolicy = ReplayInstantPolicy - } - - // If we have acks at all and the MaxAckPending is not set go ahead - // and set to the internal max for channel based consumers - if cfg.MaxAckPending == 0 && ch != nil && cfg.AckPolicy != AckNonePolicy { - cfg.MaxAckPending = cap(ch) - } - // Create request here. - ccreq = &createConsumerRequest{ - Stream: stream, - Config: &cfg, - } - hbi = cfg.Heartbeat - } - - if isPullMode { - nms = fmt.Sprintf(js.apiSubj(apiRequestNextT), stream, consumer) - deliver = nc.NewInbox() - // for pull consumers, create a wildcard subscription to differentiate pull requests - deliver += ".*" - } - - // In case this has a context, then create a child context that - // is possible to cancel via unsubscribe / drain. - var cancel func() - if ctx != nil { - ctx, cancel = context.WithCancel(ctx) - } - - jsi := &jsSub{ - js: js, - stream: stream, - consumer: consumer, - deliver: deliver, - hbi: hbi, - ordered: o.ordered, - ccreq: ccreq, - dseq: 1, - pull: isPullMode, - nms: nms, - psubj: subj, - cancel: cancel, - ackNone: o.cfg.AckPolicy == AckNonePolicy, - } - - // Auto acknowledge unless manual ack is set or policy is set to AckNonePolicy - if cb != nil && !o.mack && o.cfg.AckPolicy != AckNonePolicy { - ocb := cb - cb = func(m *Msg) { ocb(m); m.Ack() } - } - sub, err := nc.subscribe(deliver, queue, cb, ch, isSync, jsi) - if err != nil { - return nil, err - } - - // If we fail and we had the sub we need to cleanup, but can't just do a straight Unsubscribe or Drain. - // We need to clear the jsi so we do not remove any durables etc. - cleanUpSub := func() { - if sub != nil { - sub.mu.Lock() - sub.jsi = nil - sub.mu.Unlock() - sub.Unsubscribe() - } - } - - // If we are creating or updating let's process that request. - consName := o.cfg.Name - if shouldCreate { - if cfg.Durable != "" { - consName = cfg.Durable - } else if consName == "" { - consName = getHash(nuid.Next()) - } - info, err := js.upsertConsumer(stream, consName, ccreq.Config) - if err != nil { - var apiErr *APIError - if ok := errors.As(err, &apiErr); !ok { - cleanUpSub() - return nil, err - } - if consumer == _EMPTY_ || - (apiErr.ErrorCode != JSErrCodeConsumerAlreadyExists && apiErr.ErrorCode != JSErrCodeConsumerNameExists) { - cleanUpSub() - if errors.Is(apiErr, ErrStreamNotFound) { - return nil, ErrStreamNotFound - } - return nil, err - } - // We will not be using this sub here if we were push based. - if !isPullMode { - cleanUpSub() - } - - info, err = js.ConsumerInfo(stream, consumer) - if err != nil { - return nil, err - } - deliver, err = processConsInfo(info, o.cfg, isPullMode, subj, queue) - if err != nil { - return nil, err - } - - if !isPullMode { - // We can't reuse the channel, so if one was passed, we need to create a new one. - if isSync { - ch = make(chan *Msg, cap(ch)) - } else if ch != nil { - // User provided (ChanSubscription), simply try to drain it. - for done := false; !done; { - select { - case <-ch: - default: - done = true - } - } - } - jsi.deliver = deliver - jsi.hbi = info.Config.Heartbeat - - // Recreate the subscription here. - sub, err = nc.subscribe(jsi.deliver, queue, cb, ch, isSync, jsi) - if err != nil { - return nil, err - } - hasFC = info.Config.FlowControl - hasHeartbeats = info.Config.Heartbeat > 0 - } - } else { - // Since the library created the JS consumer, it will delete it on Unsubscribe()/Drain() - sub.mu.Lock() - sub.jsi.dc = true - sub.jsi.pending = info.NumPending + info.Delivered.Consumer - // If this is an ephemeral, we did not have a consumer name, we get it from the info - // after the AddConsumer returns. - if consumer == _EMPTY_ { - sub.jsi.consumer = info.Name - if isPullMode { - sub.jsi.nms = fmt.Sprintf(js.apiSubj(apiRequestNextT), stream, info.Name) - } - } - sub.mu.Unlock() - } - // Capture max ack pending from the info response here which covers both - // success and failure followed by consumer lookup. - maxap = info.Config.MaxAckPending - } - - // If maxap is greater than the default sub's pending limit, use that. - if maxap > DefaultSubPendingMsgsLimit { - // For bytes limit, use the min of maxp*1MB or DefaultSubPendingBytesLimit - bl := maxap * 1024 * 1024 - if bl < DefaultSubPendingBytesLimit { - bl = DefaultSubPendingBytesLimit - } - if err := sub.SetPendingLimits(maxap, bl); err != nil { - return nil, err - } - } - - // Do heartbeats last if needed. - if hasHeartbeats { - sub.scheduleHeartbeatCheck() - } - // For ChanSubscriptions, if we know that there is flow control, we will - // start a go routine that evaluates the number of delivered messages - // and process flow control. - if sub.Type() == ChanSubscription && hasFC { - sub.chanSubcheckForFlowControlResponse() - } - - // Wait for context to get canceled if there is one. - if ctx != nil { - go func() { - <-ctx.Done() - sub.Unsubscribe() - }() - } - - return sub, nil -} - -// InitialConsumerPending returns the number of messages pending to be -// delivered to the consumer when the subscription was created. -func (sub *Subscription) InitialConsumerPending() (uint64, error) { - sub.mu.Lock() - defer sub.mu.Unlock() - if sub.jsi == nil || sub.jsi.consumer == _EMPTY_ { - return 0, fmt.Errorf("%w: not a JetStream subscription", ErrTypeSubscription) - } - return sub.jsi.pending, nil -} - -// This long-lived routine is used per ChanSubscription to check -// on the number of delivered messages and check for flow control response. -func (sub *Subscription) chanSubcheckForFlowControlResponse() { - sub.mu.Lock() - // We don't use defer since if we need to send an RC reply, we need - // to do it outside the sub's lock. So doing explicit unlock... - if sub.closed { - sub.mu.Unlock() - return - } - var fcReply string - var nc *Conn - - jsi := sub.jsi - if jsi.csfct == nil { - jsi.csfct = time.AfterFunc(chanSubFCCheckInterval, sub.chanSubcheckForFlowControlResponse) - } else { - fcReply = sub.checkForFlowControlResponse() - nc = sub.conn - // Do the reset here under the lock, it's ok... - jsi.csfct.Reset(chanSubFCCheckInterval) - } - sub.mu.Unlock() - // This call will return an error (which we don't care here) - // if nc is nil or fcReply is empty. - nc.Publish(fcReply, nil) -} - -// ErrConsumerSequenceMismatch represents an error from a consumer -// that received a Heartbeat including sequence different to the -// one expected from the view of the client. -type ErrConsumerSequenceMismatch struct { - // StreamResumeSequence is the stream sequence from where the consumer - // should resume consuming from the stream. - StreamResumeSequence uint64 - - // ConsumerSequence is the sequence of the consumer that is behind. - ConsumerSequence uint64 - - // LastConsumerSequence is the sequence of the consumer when the heartbeat - // was received. - LastConsumerSequence uint64 -} - -func (ecs *ErrConsumerSequenceMismatch) Error() string { - return fmt.Sprintf("nats: sequence mismatch for consumer at sequence %d (%d sequences behind), should restart consumer from stream sequence %d", - ecs.ConsumerSequence, - ecs.LastConsumerSequence-ecs.ConsumerSequence, - ecs.StreamResumeSequence, - ) -} - -// isJSControlMessage will return true if this is an empty control status message -// and indicate what type of control message it is, say jsCtrlHB or jsCtrlFC -func isJSControlMessage(msg *Msg) (bool, int) { - if len(msg.Data) > 0 || msg.Header.Get(statusHdr) != controlMsg { - return false, 0 - } - val := msg.Header.Get(descrHdr) - if strings.HasPrefix(val, "Idle") { - return true, jsCtrlHB - } - if strings.HasPrefix(val, "Flow") { - return true, jsCtrlFC - } - return true, 0 -} - -// Keeps track of the incoming message's reply subject so that the consumer's -// state (deliver sequence, etc..) can be checked against heartbeats. -// We will also bump the incoming data message sequence that is used in FC cases. -// Runs under the subscription lock -func (sub *Subscription) trackSequences(reply string) { - // For flow control, keep track of incoming message sequence. - sub.jsi.fciseq++ - sub.jsi.cmeta = reply -} - -// Check to make sure messages are arriving in order. -// Returns true if the sub had to be replaced. Will cause upper layers to return. -// The caller has verified that sub.jsi != nil and that this is not a control message. -// Lock should be held. -func (sub *Subscription) checkOrderedMsgs(m *Msg) bool { - // Ignore msgs with no reply like HBs and flow control, they are handled elsewhere. - if m.Reply == _EMPTY_ { - return false - } - - // Normal message here. - tokens, err := parser.GetMetadataFields(m.Reply) - if err != nil { - return false - } - sseq, dseq := parser.ParseNum(tokens[parser.AckStreamSeqTokenPos]), parser.ParseNum(tokens[parser.AckConsumerSeqTokenPos]) - - jsi := sub.jsi - if dseq != jsi.dseq { - sub.resetOrderedConsumer(jsi.sseq + 1) - return true - } - // Update our tracking here. - jsi.dseq, jsi.sseq = dseq+1, sseq - return false -} - -// Update and replace sid. -// Lock should be held on entry but will be unlocked to prevent lock inversion. -func (sub *Subscription) applyNewSID() (osid int64) { - nc := sub.conn - sub.mu.Unlock() - - nc.subsMu.Lock() - osid = sub.sid - delete(nc.subs, osid) - // Place new one. - nc.ssid++ - nsid := nc.ssid - nc.subs[nsid] = sub - nc.subsMu.Unlock() - - sub.mu.Lock() - sub.sid = nsid - return osid -} - -// We are here if we have detected a gap with an ordered consumer. -// We will create a new consumer and rewire the low level subscription. -// Lock should be held. -func (sub *Subscription) resetOrderedConsumer(sseq uint64) { - nc := sub.conn - if sub.jsi == nil || nc == nil || sub.closed { - return - } - - var maxStr string - // If there was an AUTO_UNSUB done, we need to adjust the new value - // to send after the SUB for the new sid. - if sub.max > 0 { - if sub.jsi.fciseq < sub.max { - adjustedMax := sub.max - sub.jsi.fciseq - maxStr = strconv.Itoa(int(adjustedMax)) - } else { - // We are already at the max, so we should just unsub the - // existing sub and be done - go func(sid int64) { - nc.mu.Lock() - nc.bw.appendString(fmt.Sprintf(unsubProto, sid, _EMPTY_)) - nc.kickFlusher() - nc.mu.Unlock() - }(sub.sid) - return - } - } - - // Quick unsubscribe. Since we know this is a simple push subscriber we do in place. - osid := sub.applyNewSID() - - // Grab new inbox. - newDeliver := nc.NewInbox() - sub.Subject = newDeliver - - // Snapshot the new sid under sub lock. - nsid := sub.sid - - // We are still in the low level readLoop for the connection so we need - // to spin a go routine to try to create the new consumer. - go func() { - // Unsubscribe and subscribe with new inbox and sid. - // Remap a new low level sub into this sub since its client accessible. - // This is done here in this go routine to prevent lock inversion. - nc.mu.Lock() - nc.bw.appendString(fmt.Sprintf(unsubProto, osid, _EMPTY_)) - nc.bw.appendString(fmt.Sprintf(subProto, newDeliver, _EMPTY_, nsid)) - if maxStr != _EMPTY_ { - nc.bw.appendString(fmt.Sprintf(unsubProto, nsid, maxStr)) - } - nc.kickFlusher() - nc.mu.Unlock() - - pushErr := func(err error) { - nc.handleConsumerSequenceMismatch(sub, fmt.Errorf("%w: recreating ordered consumer", err)) - nc.unsubscribe(sub, 0, true) - } - - sub.mu.Lock() - jsi := sub.jsi - // Reset some items in jsi. - jsi.dseq = 1 - jsi.cmeta = _EMPTY_ - jsi.fcr, jsi.fcd = _EMPTY_, 0 - jsi.deliver = newDeliver - // Reset consumer request for starting policy. - cfg := jsi.ccreq.Config - cfg.DeliverSubject = newDeliver - cfg.DeliverPolicy = DeliverByStartSequencePolicy - cfg.OptStartSeq = sseq - // In case the consumer was created with a start time, we need to clear it - // since we are now using a start sequence. - cfg.OptStartTime = nil - - js := jsi.js - sub.mu.Unlock() - - sub.mu.Lock() - // Attempt to delete the existing consumer. - // We don't wait for the response since even if it's unsuccessful, - // inactivity threshold will kick in and delete it. - if jsi.consumer != _EMPTY_ { - go js.DeleteConsumer(jsi.stream, jsi.consumer) - } - jsi.consumer = "" - sub.mu.Unlock() - consName := getHash(nuid.Next()) - cinfo, err := js.upsertConsumer(jsi.stream, consName, cfg) - if err != nil { - var apiErr *APIError - if errors.Is(err, ErrJetStreamNotEnabled) || errors.Is(err, ErrTimeout) || errors.Is(err, context.DeadlineExceeded) { - // if creating consumer failed, retry - return - } else if errors.As(err, &apiErr) && apiErr.ErrorCode == JSErrCodeInsufficientResourcesErr { - // retry for insufficient resources, as it may mean that client is connected to a running - // server in cluster while the server hosting R1 JetStream resources is restarting - return - } - pushErr(err) - return - } - - sub.mu.Lock() - jsi.consumer = cinfo.Name - sub.mu.Unlock() - }() -} - -// For jetstream subscriptions, returns the number of delivered messages. -// For ChanSubscription, this value is computed based on the known number -// of messages added to the channel minus the current size of that channel. -// Lock held on entry -func (sub *Subscription) getJSDelivered() uint64 { - if sub.typ == ChanSubscription { - return sub.jsi.fciseq - uint64(len(sub.mch)) - } - return sub.delivered -} - -// checkForFlowControlResponse will check to see if we should send a flow control response -// based on the subscription current delivered index and the target. -// Runs under subscription lock -func (sub *Subscription) checkForFlowControlResponse() string { - // Caller has verified that there is a sub.jsi and fc - jsi := sub.jsi - jsi.active = true - if sub.getJSDelivered() >= jsi.fcd { - fcr := jsi.fcr - jsi.fcr, jsi.fcd = _EMPTY_, 0 - return fcr - } - return _EMPTY_ -} - -// Record an inbound flow control message. -// Runs under subscription lock -func (sub *Subscription) scheduleFlowControlResponse(reply string) { - sub.jsi.fcr, sub.jsi.fcd = reply, sub.jsi.fciseq -} - -// Checks for activity from our consumer. -// If we do not think we are active send an async error. -func (sub *Subscription) activityCheck() { - sub.mu.Lock() - jsi := sub.jsi - if jsi == nil || sub.closed { - sub.mu.Unlock() - return - } - - active := jsi.active - jsi.hbc.Reset(jsi.hbi * hbcThresh) - jsi.active = false - nc := sub.conn - sub.mu.Unlock() - - if !active { - if !jsi.ordered || nc.Status() != CONNECTED { - nc.mu.Lock() - if errCB := nc.Opts.AsyncErrorCB; errCB != nil { - nc.ach.push(func() { errCB(nc, sub, ErrConsumerNotActive) }) - } - nc.mu.Unlock() - return - } - sub.mu.Lock() - sub.resetOrderedConsumer(jsi.sseq + 1) - sub.mu.Unlock() - } -} - -// scheduleHeartbeatCheck sets up the timer check to make sure we are active -// or receiving idle heartbeats.. -func (sub *Subscription) scheduleHeartbeatCheck() { - sub.mu.Lock() - defer sub.mu.Unlock() - - jsi := sub.jsi - if jsi == nil { - return - } - - if jsi.hbc == nil { - jsi.hbc = time.AfterFunc(jsi.hbi*hbcThresh, sub.activityCheck) - } else { - jsi.hbc.Reset(jsi.hbi * hbcThresh) - } -} - -// handleConsumerSequenceMismatch will send an async error that can be used to restart a push based consumer. -func (nc *Conn) handleConsumerSequenceMismatch(sub *Subscription, err error) { - nc.mu.Lock() - errCB := nc.Opts.AsyncErrorCB - if errCB != nil { - nc.ach.push(func() { errCB(nc, sub, err) }) - } - nc.mu.Unlock() -} - -// checkForSequenceMismatch will make sure we have not missed any messages since last seen. -func (nc *Conn) checkForSequenceMismatch(msg *Msg, s *Subscription, jsi *jsSub) { - // Process heartbeat received, get latest control metadata if present. - s.mu.Lock() - ctrl, ordered := jsi.cmeta, jsi.ordered - jsi.active = true - s.mu.Unlock() - - if ctrl == _EMPTY_ { - return - } - - tokens, err := parser.GetMetadataFields(ctrl) - if err != nil { - return - } - - // Consumer sequence. - var ldseq string - dseq := tokens[parser.AckConsumerSeqTokenPos] - hdr := msg.Header[lastConsumerSeqHdr] - if len(hdr) == 1 { - ldseq = hdr[0] - } - - // Detect consumer sequence mismatch and whether - // should restart the consumer. - if ldseq != dseq { - // Dispatch async error including details such as - // from where the consumer could be restarted. - sseq := parser.ParseNum(tokens[parser.AckStreamSeqTokenPos]) - if ordered { - s.mu.Lock() - s.resetOrderedConsumer(jsi.sseq + 1) - s.mu.Unlock() - } else { - ecs := &ErrConsumerSequenceMismatch{ - StreamResumeSequence: uint64(sseq), - ConsumerSequence: parser.ParseNum(dseq), - LastConsumerSequence: parser.ParseNum(ldseq), - } - nc.handleConsumerSequenceMismatch(s, ecs) - } - } -} - -type streamRequest struct { - Subject string `json:"subject,omitempty"` -} - -type streamNamesResponse struct { - apiResponse - apiPaged - Streams []string `json:"streams"` -} - -type subOpts struct { - // For attaching. - stream, consumer string - // For creating or updating. - cfg *ConsumerConfig - // For binding a subscription to a consumer without creating it. - bound bool - // For manual ack - mack bool - // For an ordered consumer. - ordered bool - ctx context.Context - - // To disable calling ConsumerInfo - skipCInfo bool -} - -// SkipConsumerLookup will omit looking up consumer when [Bind], [Durable] -// or [ConsumerName] are provided. -// -// NOTE: This setting may cause an existing consumer to be overwritten. Also, -// because consumer lookup is skipped, all consumer options like AckPolicy, -// DeliverSubject etc. need to be provided even if consumer already exists. -func SkipConsumerLookup() SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.skipCInfo = true - return nil - }) -} - -// OrderedConsumer will create a FIFO direct/ephemeral consumer for in order delivery of messages. -// There are no redeliveries and no acks, and flow control and heartbeats will be added but -// will be taken care of without additional client code. -func OrderedConsumer() SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.ordered = true - return nil - }) -} - -// ManualAck disables auto ack functionality for async subscriptions. -func ManualAck() SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.mack = true - return nil - }) -} - -// Description will set the description for the created consumer. -func Description(description string) SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.Description = description - return nil - }) -} - -// Durable defines the consumer name for JetStream durable subscribers. -// This function will return ErrInvalidConsumerName if the name contains -// any dot ".". -func Durable(consumer string) SubOpt { - return subOptFn(func(opts *subOpts) error { - if opts.cfg.Durable != _EMPTY_ { - return fmt.Errorf("nats: option Durable set more than once") - } - if opts.consumer != _EMPTY_ && opts.consumer != consumer { - return fmt.Errorf("nats: duplicate consumer names (%s and %s)", opts.consumer, consumer) - } - if err := checkConsumerName(consumer); err != nil { - return err - } - - opts.cfg.Durable = consumer - return nil - }) -} - -// DeliverAll will configure a Consumer to receive all the -// messages from a Stream. -func DeliverAll() SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.DeliverPolicy = DeliverAllPolicy - return nil - }) -} - -// DeliverLast configures a Consumer to receive messages -// starting with the latest one. -func DeliverLast() SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.DeliverPolicy = DeliverLastPolicy - return nil - }) -} - -// DeliverLastPerSubject configures a Consumer to receive messages -// starting with the latest one for each filtered subject. -func DeliverLastPerSubject() SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.DeliverPolicy = DeliverLastPerSubjectPolicy - return nil - }) -} - -// DeliverNew configures a Consumer to receive messages -// published after the subscription. -func DeliverNew() SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.DeliverPolicy = DeliverNewPolicy - return nil - }) -} - -// StartSequence configures a Consumer to receive -// messages from a start sequence. -func StartSequence(seq uint64) SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.DeliverPolicy = DeliverByStartSequencePolicy - opts.cfg.OptStartSeq = seq - return nil - }) -} - -// StartTime configures a Consumer to receive -// messages from a start time. -func StartTime(startTime time.Time) SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.DeliverPolicy = DeliverByStartTimePolicy - opts.cfg.OptStartTime = &startTime - return nil - }) -} - -// AckNone requires no acks for delivered messages. -func AckNone() SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.AckPolicy = AckNonePolicy - return nil - }) -} - -// AckAll when acking a sequence number, this implicitly acks all sequences -// below this one as well. -func AckAll() SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.AckPolicy = AckAllPolicy - return nil - }) -} - -// AckExplicit requires ack or nack for all messages. -func AckExplicit() SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.AckPolicy = AckExplicitPolicy - return nil - }) -} - -// MaxDeliver sets the number of redeliveries for a message. -func MaxDeliver(n int) SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.MaxDeliver = n - return nil - }) -} - -// MaxAckPending sets the number of outstanding acks that are allowed before -// message delivery is halted. -func MaxAckPending(n int) SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.MaxAckPending = n - return nil - }) -} - -// ReplayOriginal replays the messages at the original speed. -func ReplayOriginal() SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.ReplayPolicy = ReplayOriginalPolicy - return nil - }) -} - -// ReplayInstant replays the messages as fast as possible. -func ReplayInstant() SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.ReplayPolicy = ReplayInstantPolicy - return nil - }) -} - -// RateLimit is the Bits per sec rate limit applied to a push consumer. -func RateLimit(n uint64) SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.RateLimit = n - return nil - }) -} - -// BackOff is an array of time durations that represent the time to delay based on delivery count. -func BackOff(backOff []time.Duration) SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.BackOff = backOff - return nil - }) -} - -// BindStream binds a consumer to a stream explicitly based on a name. -// When a stream name is not specified, the library uses the subscribe -// subject as a way to find the stream name. It is done by making a request -// to the server to get list of stream names that have a filter for this -// subject. If the returned list contains a single stream, then this -// stream name will be used, otherwise the `ErrNoMatchingStream` is returned. -// To avoid the stream lookup, provide the stream name with this function. -// See also `Bind()`. -func BindStream(stream string) SubOpt { - return subOptFn(func(opts *subOpts) error { - if opts.stream != _EMPTY_ && opts.stream != stream { - return fmt.Errorf("nats: duplicate stream name (%s and %s)", opts.stream, stream) - } - - opts.stream = stream - return nil - }) -} - -// Bind binds a subscription to an existing consumer from a stream without attempting to create. -// The first argument is the stream name and the second argument will be the consumer name. -func Bind(stream, consumer string) SubOpt { - return subOptFn(func(opts *subOpts) error { - if stream == _EMPTY_ { - return ErrStreamNameRequired - } - if consumer == _EMPTY_ { - return ErrConsumerNameRequired - } - - // In case of pull subscribers, the durable name is a required parameter - // so check that they are not different. - if opts.cfg.Durable != _EMPTY_ && opts.cfg.Durable != consumer { - return fmt.Errorf("nats: duplicate consumer names (%s and %s)", opts.cfg.Durable, consumer) - } - if opts.stream != _EMPTY_ && opts.stream != stream { - return fmt.Errorf("nats: duplicate stream name (%s and %s)", opts.stream, stream) - } - opts.stream = stream - opts.consumer = consumer - opts.bound = true - return nil - }) -} - -// EnableFlowControl enables flow control for a push based consumer. -func EnableFlowControl() SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.FlowControl = true - return nil - }) -} - -// IdleHeartbeat enables push based consumers to have idle heartbeats delivered. -// For pull consumers, idle heartbeat has to be set on each [Fetch] call. -func IdleHeartbeat(duration time.Duration) SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.Heartbeat = duration - return nil - }) -} - -// DeliverSubject specifies the JetStream consumer deliver subject. -// -// This option is used only in situations where the consumer does not exist -// and a creation request is sent to the server. If not provided, an inbox -// will be selected. -// If a consumer exists, then the NATS subscription will be created on -// the JetStream consumer's DeliverSubject, not necessarily this subject. -func DeliverSubject(subject string) SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.DeliverSubject = subject - return nil - }) -} - -// HeadersOnly() will instruct the consumer to only deliver headers and no payloads. -func HeadersOnly() SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.HeadersOnly = true - return nil - }) -} - -// MaxRequestBatch sets the maximum pull consumer batch size that a Fetch() -// can request. -func MaxRequestBatch(max int) SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.MaxRequestBatch = max - return nil - }) -} - -// MaxRequestExpires sets the maximum pull consumer request expiration that a -// Fetch() can request (using the Fetch's timeout value). -func MaxRequestExpires(max time.Duration) SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.MaxRequestExpires = max - return nil - }) -} - -// MaxRequesMaxBytes sets the maximum pull consumer request bytes that a -// Fetch() can receive. -func MaxRequestMaxBytes(bytes int) SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.MaxRequestMaxBytes = bytes - return nil - }) -} - -// InactiveThreshold indicates how long the server should keep a consumer -// after detecting a lack of activity. In NATS Server 2.8.4 and earlier, this -// option only applies to ephemeral consumers. In NATS Server 2.9.0 and later, -// this option applies to both ephemeral and durable consumers, allowing durable -// consumers to also be deleted automatically after the inactivity threshold has -// passed. -func InactiveThreshold(threshold time.Duration) SubOpt { - return subOptFn(func(opts *subOpts) error { - if threshold < 0 { - return fmt.Errorf("invalid InactiveThreshold value (%v), needs to be greater or equal to 0", threshold) - } - opts.cfg.InactiveThreshold = threshold - return nil - }) -} - -// ConsumerReplicas sets the number of replica count for a consumer. -func ConsumerReplicas(replicas int) SubOpt { - return subOptFn(func(opts *subOpts) error { - if replicas < 1 { - return fmt.Errorf("invalid ConsumerReplicas value (%v), needs to be greater than 0", replicas) - } - opts.cfg.Replicas = replicas - return nil - }) -} - -// ConsumerMemoryStorage sets the memory storage to true for a consumer. -func ConsumerMemoryStorage() SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.MemoryStorage = true - return nil - }) -} - -// ConsumerName sets the name for a consumer. -func ConsumerName(name string) SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.Name = name - return nil - }) -} - -// ConsumerFilterSubjects can be used to set multiple subject filters on the consumer. -// It has to be used in conjunction with [nats.BindStream] and -// with empty 'subject' parameter. -func ConsumerFilterSubjects(subjects ...string) SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.FilterSubjects = subjects - return nil - }) -} - -func (sub *Subscription) ConsumerInfo() (*ConsumerInfo, error) { - sub.mu.Lock() - // TODO(dlc) - Better way to mark especially if we attach. - if sub.jsi == nil || sub.jsi.consumer == _EMPTY_ { - sub.mu.Unlock() - return nil, ErrTypeSubscription - } - - // Consumer info lookup should fail if in direct mode. - js := sub.jsi.js - stream, consumer := sub.jsi.stream, sub.jsi.consumer - sub.mu.Unlock() - - return js.getConsumerInfo(stream, consumer) -} - -type pullOpts struct { - maxBytes int - ttl time.Duration - ctx context.Context - hb time.Duration -} - -// PullOpt are the options that can be passed when pulling a batch of messages. -type PullOpt interface { - configurePull(opts *pullOpts) error -} - -// PullMaxWaiting defines the max inflight pull requests. -func PullMaxWaiting(n int) SubOpt { - return subOptFn(func(opts *subOpts) error { - opts.cfg.MaxWaiting = n - return nil - }) -} - -type PullHeartbeat time.Duration - -func (h PullHeartbeat) configurePull(opts *pullOpts) error { - if h <= 0 { - return fmt.Errorf("%w: idle heartbeat has to be greater than 0", ErrInvalidArg) - } - opts.hb = time.Duration(h) - return nil -} - -// PullMaxBytes defines the max bytes allowed for a fetch request. -type PullMaxBytes int - -func (n PullMaxBytes) configurePull(opts *pullOpts) error { - opts.maxBytes = int(n) - return nil -} - -var ( - // errNoMessages is an error that a Fetch request using no_wait can receive to signal - // that there are no more messages available. - errNoMessages = errors.New("nats: no messages") - - // errRequestsPending is an error that represents a sub.Fetch requests that was using - // no_wait and expires time got discarded by the server. - errRequestsPending = errors.New("nats: requests pending") -) - -// Returns if the given message is a user message or not, and if -// `checkSts` is true, returns appropriate error based on the -// content of the status (404, etc..) -func checkMsg(msg *Msg, checkSts, isNoWait bool) (usrMsg bool, err error) { - // Assume user message - usrMsg = true - - // If payload or no header, consider this a user message - if len(msg.Data) > 0 || len(msg.Header) == 0 { - return - } - // Look for status header - val := msg.Header.Get(statusHdr) - // If not present, then this is considered a user message - if val == _EMPTY_ { - return - } - // At this point, this is not a user message since there is - // no payload and a "Status" header. - usrMsg = false - - // If we don't care about status, we are done. - if !checkSts { - return - } - - // if it's a heartbeat message, report as not user msg - if isHb, _ := isJSControlMessage(msg); isHb { - return - } - switch val { - case noResponders: - err = ErrNoResponders - case noMessagesSts: - // 404 indicates that there are no messages. - err = errNoMessages - case reqTimeoutSts: - // In case of a fetch request with no wait request and expires time, - // need to skip 408 errors and retry. - if isNoWait { - err = errRequestsPending - } else { - // Older servers may send a 408 when a request in the server was expired - // and interest is still found, which will be the case for our - // implementation. Regardless, ignore 408 errors until receiving at least - // one message when making requests without no_wait. - err = ErrTimeout - } - case jetStream409Sts: - if strings.Contains(strings.ToLower(msg.Header.Get(descrHdr)), "consumer deleted") { - err = ErrConsumerDeleted - break - } - - if strings.Contains(strings.ToLower(msg.Header.Get(descrHdr)), "leadership change") { - err = ErrConsumerLeadershipChanged - break - } - fallthrough - default: - err = fmt.Errorf("nats: %s", msg.Header.Get(descrHdr)) - } - return -} - -// Fetch pulls a batch of messages from a stream for a pull consumer. -func (sub *Subscription) Fetch(batch int, opts ...PullOpt) ([]*Msg, error) { - if sub == nil { - return nil, ErrBadSubscription - } - if batch < 1 { - return nil, ErrInvalidArg - } - - var o pullOpts - for _, opt := range opts { - if err := opt.configurePull(&o); err != nil { - return nil, err - } - } - if o.ctx != nil && o.ttl != 0 { - return nil, ErrContextAndTimeout - } - - sub.mu.Lock() - jsi := sub.jsi - // Reject if this is not a pull subscription. Note that sub.typ is SyncSubscription, - // so check for jsi.pull boolean instead. - if jsi == nil || !jsi.pull { - sub.mu.Unlock() - return nil, ErrTypeSubscription - } - - nc := sub.conn - nms := sub.jsi.nms - rply, _ := newFetchInbox(jsi.deliver) - js := sub.jsi.js - pmc := len(sub.mch) > 0 - - // All fetch requests have an expiration, in case of no explicit expiration - // then the default timeout of the JetStream context is used. - ttl := o.ttl - if ttl == 0 { - ttl = js.opts.wait - } - sub.mu.Unlock() - - // Use the given context or setup a default one for the span - // of the pull batch request. - var ( - ctx = o.ctx - err error - cancel context.CancelFunc - ) - if ctx == nil { - ctx, cancel = context.WithTimeout(context.Background(), ttl) - } else if _, hasDeadline := ctx.Deadline(); !hasDeadline { - // Prevent from passing the background context which will just block - // and cannot be canceled either. - if octx, ok := ctx.(ContextOpt); ok && octx.Context == context.Background() { - return nil, ErrNoDeadlineContext - } - - // If the context did not have a deadline, then create a new child context - // that will use the default timeout from the JS context. - ctx, cancel = context.WithTimeout(ctx, ttl) - } else { - ctx, cancel = context.WithCancel(ctx) - } - defer cancel() - - // if heartbeat is set, validate it against the context timeout - if o.hb > 0 { - deadline, _ := ctx.Deadline() - if 2*o.hb >= time.Until(deadline) { - return nil, fmt.Errorf("%w: idle heartbeat value too large", ErrInvalidArg) - } - } - - // Check if context not done already before making the request. - select { - case <-ctx.Done(): - if o.ctx != nil { // Timeout or Cancel triggered by context object option - err = ctx.Err() - } else { // Timeout triggered by timeout option - err = ErrTimeout - } - default: - } - if err != nil { - return nil, err - } - - var ( - msgs = make([]*Msg, 0, batch) - msg *Msg - ) - for pmc && len(msgs) < batch { - // Check next msg with booleans that say that this is an internal call - // for a pull subscribe (so don't reject it) and don't wait if there - // are no messages. - msg, err = sub.nextMsgWithContext(ctx, true, false) - if err != nil { - if errors.Is(err, errNoMessages) { - err = nil - } - break - } - // Check msg but just to determine if this is a user message - // or status message, however, we don't care about values of status - // messages at this point in the Fetch() call, so checkMsg can't - // return an error. - if usrMsg, _ := checkMsg(msg, false, false); usrMsg { - msgs = append(msgs, msg) - } - } - var hbTimer *time.Timer - var hbErr error - if err == nil && len(msgs) < batch { - // For batch real size of 1, it does not make sense to set no_wait in - // the request. - noWait := batch-len(msgs) > 1 - - var nr nextRequest - - sendReq := func() error { - // The current deadline for the context will be used - // to set the expires TTL for a fetch request. - deadline, _ := ctx.Deadline() - ttl = time.Until(deadline) - - // Check if context has already been canceled or expired. - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - - // Make our request expiration a bit shorter than the current timeout. - expires := ttl - if ttl >= 20*time.Millisecond { - expires = ttl - 10*time.Millisecond - } - - nr.Batch = batch - len(msgs) - nr.Expires = expires - nr.NoWait = noWait - nr.MaxBytes = o.maxBytes - if 2*o.hb < expires { - nr.Heartbeat = o.hb - } else { - nr.Heartbeat = 0 - } - req, _ := json.Marshal(nr) - if err := nc.PublishRequest(nms, rply, req); err != nil { - return err - } - if o.hb > 0 { - if hbTimer == nil { - hbTimer = time.AfterFunc(2*o.hb, func() { - hbErr = ErrNoHeartbeat - cancel() - }) - } else { - hbTimer.Reset(2 * o.hb) - } - } - return nil - } - - err = sendReq() - for err == nil && len(msgs) < batch { - // Ask for next message and wait if there are no messages - msg, err = sub.nextMsgWithContext(ctx, true, true) - if err == nil { - if hbTimer != nil { - hbTimer.Reset(2 * o.hb) - } - var usrMsg bool - - usrMsg, err = checkMsg(msg, true, noWait) - if err == nil && usrMsg { - msgs = append(msgs, msg) - } else if noWait && (errors.Is(err, errNoMessages) || errors.Is(err, errRequestsPending)) && len(msgs) == 0 { - // If we have a 404/408 for our "no_wait" request and have - // not collected any message, then resend request to - // wait this time. - noWait = false - err = sendReq() - } else if errors.Is(err, ErrTimeout) && len(msgs) == 0 { - // If we get a 408, we will bail if we already collected some - // messages, otherwise ignore and go back calling nextMsg. - err = nil - } - } - } - if hbTimer != nil { - hbTimer.Stop() - } - } - // If there is at least a message added to msgs, then need to return OK and no error - if err != nil && len(msgs) == 0 { - if hbErr != nil { - return nil, hbErr - } - return nil, o.checkCtxErr(err) - } - return msgs, nil -} - -// newFetchInbox returns subject used as reply subject when sending pull requests -// as well as request ID. For non-wildcard subject, request ID is empty and -// passed subject is not transformed -func newFetchInbox(subj string) (string, string) { - if !strings.HasSuffix(subj, ".*") { - return subj, "" - } - reqID := nuid.Next() - var sb strings.Builder - sb.WriteString(subj[:len(subj)-1]) - sb.WriteString(reqID) - return sb.String(), reqID -} - -func subjectMatchesReqID(subject, reqID string) bool { - subjectParts := strings.Split(subject, ".") - if len(subjectParts) < 2 { - return false - } - return subjectParts[len(subjectParts)-1] == reqID -} - -// MessageBatch provides methods to retrieve messages consumed using [Subscribe.FetchBatch]. -type MessageBatch interface { - // Messages returns a channel on which messages will be published. - Messages() <-chan *Msg - - // Error returns an error encountered when fetching messages. - Error() error - - // Done signals end of execution. - Done() <-chan struct{} -} - -type messageBatch struct { - msgs chan *Msg - err error - done chan struct{} -} - -func (mb *messageBatch) Messages() <-chan *Msg { - return mb.msgs -} - -func (mb *messageBatch) Error() error { - return mb.err -} - -func (mb *messageBatch) Done() <-chan struct{} { - return mb.done -} - -// FetchBatch pulls a batch of messages from a stream for a pull consumer. -// Unlike [Subscription.Fetch], it is non blocking and returns [MessageBatch], -// allowing to retrieve incoming messages from a channel. -// The returned channel is always closed after all messages for a batch have been -// delivered by the server - it is safe to iterate over it using range. -// -// To avoid using default JetStream timeout as fetch expiry time, use [nats.MaxWait] -// or [nats.Context] (with deadline set). -// -// This method will not return error in case of pull request expiry (even if there are no messages). -// Any other error encountered when receiving messages will cause FetchBatch to stop receiving new messages. -func (sub *Subscription) FetchBatch(batch int, opts ...PullOpt) (MessageBatch, error) { - if sub == nil { - return nil, ErrBadSubscription - } - if batch < 1 { - return nil, ErrInvalidArg - } - - var o pullOpts - for _, opt := range opts { - if err := opt.configurePull(&o); err != nil { - return nil, err - } - } - if o.ctx != nil && o.ttl != 0 { - return nil, ErrContextAndTimeout - } - sub.mu.Lock() - jsi := sub.jsi - // Reject if this is not a pull subscription. Note that sub.typ is SyncSubscription, - // so check for jsi.pull boolean instead. - if jsi == nil || !jsi.pull { - sub.mu.Unlock() - return nil, ErrTypeSubscription - } - - nc := sub.conn - nms := sub.jsi.nms - rply, reqID := newFetchInbox(sub.jsi.deliver) - js := sub.jsi.js - pmc := len(sub.mch) > 0 - - // All fetch requests have an expiration, in case of no explicit expiration - // then the default timeout of the JetStream context is used. - ttl := o.ttl - if ttl == 0 { - ttl = js.opts.wait - } - sub.mu.Unlock() - - // Use the given context or setup a default one for the span - // of the pull batch request. - var ( - ctx = o.ctx - cancel context.CancelFunc - cancelContext = true - ) - if ctx == nil { - ctx, cancel = context.WithTimeout(context.Background(), ttl) - } else if _, hasDeadline := ctx.Deadline(); !hasDeadline { - // Prevent from passing the background context which will just block - // and cannot be canceled either. - if octx, ok := ctx.(ContextOpt); ok && octx.Context == context.Background() { - return nil, ErrNoDeadlineContext - } - - // If the context did not have a deadline, then create a new child context - // that will use the default timeout from the JS context. - ctx, cancel = context.WithTimeout(ctx, ttl) - } else { - ctx, cancel = context.WithCancel(ctx) - } - defer func() { - // only cancel the context here if we are sure the fetching goroutine has not been started yet - if cancelContext { - cancel() - } - }() - - // if heartbeat is set, validate it against the context timeout - if o.hb > 0 { - deadline, _ := ctx.Deadline() - if 2*o.hb >= time.Until(deadline) { - return nil, fmt.Errorf("%w: idle heartbeat value too large", ErrInvalidArg) - } - } - - // Check if context not done already before making the request. - select { - case <-ctx.Done(): - if o.ctx != nil { // Timeout or Cancel triggered by context object option - return nil, ctx.Err() - } else { // Timeout triggered by timeout option - return nil, ErrTimeout - } - default: - } - - result := &messageBatch{ - msgs: make(chan *Msg, batch), - done: make(chan struct{}, 1), - } - var msg *Msg - for pmc && len(result.msgs) < batch { - // Check next msg with booleans that say that this is an internal call - // for a pull subscribe (so don't reject it) and don't wait if there - // are no messages. - msg, err := sub.nextMsgWithContext(ctx, true, false) - if err != nil { - if errors.Is(err, errNoMessages) { - err = nil - } - result.err = err - break - } - // Check msg but just to determine if this is a user message - // or status message, however, we don't care about values of status - // messages at this point in the Fetch() call, so checkMsg can't - // return an error. - if usrMsg, _ := checkMsg(msg, false, false); usrMsg { - result.msgs <- msg - } - } - if len(result.msgs) == batch || result.err != nil { - close(result.msgs) - result.done <- struct{}{} - return result, nil - } - - deadline, _ := ctx.Deadline() - ttl = time.Until(deadline) - - // Make our request expiration a bit shorter than the current timeout. - expires := ttl - if ttl >= 20*time.Millisecond { - expires = ttl - 10*time.Millisecond - } - - requestBatch := batch - len(result.msgs) - req := nextRequest{ - Expires: expires, - Batch: requestBatch, - MaxBytes: o.maxBytes, - Heartbeat: o.hb, - } - reqJSON, err := json.Marshal(req) - if err != nil { - close(result.msgs) - result.done <- struct{}{} - result.err = err - return result, nil - } - if err := nc.PublishRequest(nms, rply, reqJSON); err != nil { - if len(result.msgs) == 0 { - return nil, err - } - close(result.msgs) - result.done <- struct{}{} - result.err = err - return result, nil - } - var hbTimer *time.Timer - var hbErr error - if o.hb > 0 { - hbTimer = time.AfterFunc(2*o.hb, func() { - hbErr = ErrNoHeartbeat - cancel() - }) - } - cancelContext = false - go func() { - defer cancel() - var requestMsgs int - for requestMsgs < requestBatch { - // Ask for next message and wait if there are no messages - msg, err = sub.nextMsgWithContext(ctx, true, true) - if err != nil { - break - } - if hbTimer != nil { - hbTimer.Reset(2 * o.hb) - } - var usrMsg bool - - usrMsg, err = checkMsg(msg, true, false) - if err != nil { - if errors.Is(err, ErrTimeout) { - if reqID != "" && !subjectMatchesReqID(msg.Subject, reqID) { - // ignore timeout message from server if it comes from a different pull request - continue - } - err = nil - } - break - } - if usrMsg { - result.msgs <- msg - requestMsgs++ - } - } - if err != nil { - if hbErr != nil { - result.err = hbErr - } else { - result.err = o.checkCtxErr(err) - } - } - close(result.msgs) - result.done <- struct{}{} - }() - return result, nil -} - -// checkCtxErr is used to determine whether ErrTimeout should be returned in case of context timeout -func (o *pullOpts) checkCtxErr(err error) error { - if o.ctx == nil && errors.Is(err, context.DeadlineExceeded) { - return ErrTimeout - } - return err -} - -func (js *js) getConsumerInfo(stream, consumer string) (*ConsumerInfo, error) { - ctx, cancel := context.WithTimeout(context.Background(), js.opts.wait) - defer cancel() - return js.getConsumerInfoContext(ctx, stream, consumer) -} - -func (js *js) getConsumerInfoContext(ctx context.Context, stream, consumer string) (*ConsumerInfo, error) { - ccInfoSubj := fmt.Sprintf(apiConsumerInfoT, stream, consumer) - resp, err := js.apiRequestWithContext(ctx, js.apiSubj(ccInfoSubj), nil) - if err != nil { - if errors.Is(err, ErrNoResponders) { - err = ErrJetStreamNotEnabled - } - return nil, err - } - - var info consumerResponse - if err := json.Unmarshal(resp.Data, &info); err != nil { - return nil, err - } - if info.Error != nil { - if errors.Is(info.Error, ErrConsumerNotFound) { - return nil, ErrConsumerNotFound - } - if errors.Is(info.Error, ErrStreamNotFound) { - return nil, ErrStreamNotFound - } - return nil, info.Error - } - if info.Error == nil && info.ConsumerInfo == nil { - return nil, ErrConsumerNotFound - } - return info.ConsumerInfo, nil -} - -// a RequestWithContext with tracing via TraceCB -func (js *js) apiRequestWithContext(ctx context.Context, subj string, data []byte) (*Msg, error) { - if js.opts.shouldTrace { - ctrace := js.opts.ctrace - if ctrace.RequestSent != nil { - ctrace.RequestSent(subj, data) - } - } - resp, err := js.nc.RequestWithContext(ctx, subj, data) - if err != nil { - return nil, err - } - if js.opts.shouldTrace { - ctrace := js.opts.ctrace - if ctrace.RequestSent != nil { - ctrace.ResponseReceived(subj, resp.Data, resp.Header) - } - } - - return resp, nil -} - -func (m *Msg) checkReply() error { - if m == nil || m.Sub == nil { - return ErrMsgNotBound - } - if m.Reply == _EMPTY_ { - return ErrMsgNoReply - } - return nil -} - -// ackReply handles all acks. Will do the right thing for pull and sync mode. -// It ensures that an ack is only sent a single time, regardless of -// how many times it is being called to avoid duplicated acks. -func (m *Msg) ackReply(ackType []byte, sync bool, opts ...AckOpt) error { - var o ackOpts - for _, opt := range opts { - if err := opt.configureAck(&o); err != nil { - return err - } - } - - if err := m.checkReply(); err != nil { - return err - } - - var ackNone bool - var js *js - - sub := m.Sub - sub.mu.Lock() - nc := sub.conn - if jsi := sub.jsi; jsi != nil { - js = jsi.js - ackNone = jsi.ackNone - } - sub.mu.Unlock() - - // Skip if already acked. - if atomic.LoadUint32(&m.ackd) == 1 { - return ErrMsgAlreadyAckd - } - if ackNone { - return ErrCantAckIfConsumerAckNone - } - - usesCtx := o.ctx != nil - usesWait := o.ttl > 0 - - // Only allow either AckWait or Context option to set the timeout. - if usesWait && usesCtx { - return ErrContextAndTimeout - } - - sync = sync || usesCtx || usesWait - ctx := o.ctx - wait := defaultRequestWait - if usesWait { - wait = o.ttl - } else if js != nil { - wait = js.opts.wait - } - - var body []byte - var err error - // This will be > 0 only when called from NakWithDelay() - if o.nakDelay > 0 { - body = []byte(fmt.Sprintf("%s {\"delay\": %d}", ackType, o.nakDelay.Nanoseconds())) - } else { - body = ackType - } - - if sync { - if usesCtx { - _, err = nc.RequestWithContext(ctx, m.Reply, body) - } else { - _, err = nc.Request(m.Reply, body, wait) - } - } else { - err = nc.Publish(m.Reply, body) - } - - // Mark that the message has been acked unless it is ackProgress - // which can be sent many times. - if err == nil && !bytes.Equal(ackType, ackProgress) { - atomic.StoreUint32(&m.ackd, 1) - } - - return err -} - -// Ack acknowledges a message. This tells the server that the message was -// successfully processed and it can move on to the next message. -func (m *Msg) Ack(opts ...AckOpt) error { - return m.ackReply(ackAck, false, opts...) -} - -// AckSync is the synchronous version of Ack. This indicates successful message -// processing. -func (m *Msg) AckSync(opts ...AckOpt) error { - return m.ackReply(ackAck, true, opts...) -} - -// Nak negatively acknowledges a message. This tells the server to redeliver -// the message. You can configure the number of redeliveries by passing -// nats.MaxDeliver when you Subscribe. The default is infinite redeliveries. -func (m *Msg) Nak(opts ...AckOpt) error { - return m.ackReply(ackNak, false, opts...) -} - -// Nak negatively acknowledges a message. This tells the server to redeliver -// the message after the give `delay` duration. You can configure the number -// of redeliveries by passing nats.MaxDeliver when you Subscribe. -// The default is infinite redeliveries. -func (m *Msg) NakWithDelay(delay time.Duration, opts ...AckOpt) error { - if delay > 0 { - opts = append(opts, nakDelay(delay)) - } - return m.ackReply(ackNak, false, opts...) -} - -// Term tells the server to not redeliver this message, regardless of the value -// of nats.MaxDeliver. -func (m *Msg) Term(opts ...AckOpt) error { - return m.ackReply(ackTerm, false, opts...) -} - -// InProgress tells the server that this message is being worked on. It resets -// the redelivery timer on the server. -func (m *Msg) InProgress(opts ...AckOpt) error { - return m.ackReply(ackProgress, false, opts...) -} - -// MsgMetadata is the JetStream metadata associated with received messages. -type MsgMetadata struct { - Sequence SequencePair - NumDelivered uint64 - NumPending uint64 - Timestamp time.Time - Stream string - Consumer string - Domain string -} - -// Metadata retrieves the metadata from a JetStream message. This method will -// return an error for non-JetStream Msgs. -func (m *Msg) Metadata() (*MsgMetadata, error) { - if err := m.checkReply(); err != nil { - return nil, err - } - - tokens, err := parser.GetMetadataFields(m.Reply) - if err != nil { - return nil, err - } - - meta := &MsgMetadata{ - Domain: tokens[parser.AckDomainTokenPos], - NumDelivered: parser.ParseNum(tokens[parser.AckNumDeliveredTokenPos]), - NumPending: parser.ParseNum(tokens[parser.AckNumPendingTokenPos]), - Timestamp: time.Unix(0, int64(parser.ParseNum(tokens[parser.AckTimestampSeqTokenPos]))), - Stream: tokens[parser.AckStreamTokenPos], - Consumer: tokens[parser.AckConsumerTokenPos], - } - meta.Sequence.Stream = parser.ParseNum(tokens[parser.AckStreamSeqTokenPos]) - meta.Sequence.Consumer = parser.ParseNum(tokens[parser.AckConsumerSeqTokenPos]) - return meta, nil -} - -// AckPolicy determines how the consumer should acknowledge delivered messages. -type AckPolicy int - -const ( - // AckNonePolicy requires no acks for delivered messages. - AckNonePolicy AckPolicy = iota - - // AckAllPolicy when acking a sequence number, this implicitly acks all - // sequences below this one as well. - AckAllPolicy - - // AckExplicitPolicy requires ack or nack for all messages. - AckExplicitPolicy - - // For configuration mismatch check - ackPolicyNotSet = 99 -) - -func jsonString(s string) string { - return "\"" + s + "\"" -} - -func (p *AckPolicy) UnmarshalJSON(data []byte) error { - switch string(data) { - case jsonString("none"): - *p = AckNonePolicy - case jsonString("all"): - *p = AckAllPolicy - case jsonString("explicit"): - *p = AckExplicitPolicy - default: - return fmt.Errorf("nats: can not unmarshal %q", data) - } - - return nil -} - -func (p AckPolicy) MarshalJSON() ([]byte, error) { - switch p { - case AckNonePolicy: - return json.Marshal("none") - case AckAllPolicy: - return json.Marshal("all") - case AckExplicitPolicy: - return json.Marshal("explicit") - default: - return nil, fmt.Errorf("nats: unknown acknowledgement policy %v", p) - } -} - -func (p AckPolicy) String() string { - switch p { - case AckNonePolicy: - return "AckNone" - case AckAllPolicy: - return "AckAll" - case AckExplicitPolicy: - return "AckExplicit" - case ackPolicyNotSet: - return "Not Initialized" - default: - return "Unknown AckPolicy" - } -} - -// ReplayPolicy determines how the consumer should replay messages it already has queued in the stream. -type ReplayPolicy int - -const ( - // ReplayInstantPolicy will replay messages as fast as possible. - ReplayInstantPolicy ReplayPolicy = iota - - // ReplayOriginalPolicy will maintain the same timing as the messages were received. - ReplayOriginalPolicy - - // For configuration mismatch check - replayPolicyNotSet = 99 -) - -func (p *ReplayPolicy) UnmarshalJSON(data []byte) error { - switch string(data) { - case jsonString("instant"): - *p = ReplayInstantPolicy - case jsonString("original"): - *p = ReplayOriginalPolicy - default: - return fmt.Errorf("nats: can not unmarshal %q", data) - } - - return nil -} - -func (p ReplayPolicy) MarshalJSON() ([]byte, error) { - switch p { - case ReplayOriginalPolicy: - return json.Marshal("original") - case ReplayInstantPolicy: - return json.Marshal("instant") - default: - return nil, fmt.Errorf("nats: unknown replay policy %v", p) - } -} - -var ( - ackAck = []byte("+ACK") - ackNak = []byte("-NAK") - ackProgress = []byte("+WPI") - ackTerm = []byte("+TERM") -) - -// DeliverPolicy determines how the consumer should select the first message to deliver. -type DeliverPolicy int - -const ( - // DeliverAllPolicy starts delivering messages from the very beginning of a - // stream. This is the default. - DeliverAllPolicy DeliverPolicy = iota - - // DeliverLastPolicy will start the consumer with the last sequence - // received. - DeliverLastPolicy - - // DeliverNewPolicy will only deliver new messages that are sent after the - // consumer is created. - DeliverNewPolicy - - // DeliverByStartSequencePolicy will deliver messages starting from a given - // sequence. - DeliverByStartSequencePolicy - - // DeliverByStartTimePolicy will deliver messages starting from a given - // time. - DeliverByStartTimePolicy - - // DeliverLastPerSubjectPolicy will start the consumer with the last message - // for all subjects received. - DeliverLastPerSubjectPolicy - - // For configuration mismatch check - deliverPolicyNotSet = 99 -) - -func (p *DeliverPolicy) UnmarshalJSON(data []byte) error { - switch string(data) { - case jsonString("all"), jsonString("undefined"): - *p = DeliverAllPolicy - case jsonString("last"): - *p = DeliverLastPolicy - case jsonString("new"): - *p = DeliverNewPolicy - case jsonString("by_start_sequence"): - *p = DeliverByStartSequencePolicy - case jsonString("by_start_time"): - *p = DeliverByStartTimePolicy - case jsonString("last_per_subject"): - *p = DeliverLastPerSubjectPolicy - } - - return nil -} - -func (p DeliverPolicy) MarshalJSON() ([]byte, error) { - switch p { - case DeliverAllPolicy: - return json.Marshal("all") - case DeliverLastPolicy: - return json.Marshal("last") - case DeliverNewPolicy: - return json.Marshal("new") - case DeliverByStartSequencePolicy: - return json.Marshal("by_start_sequence") - case DeliverByStartTimePolicy: - return json.Marshal("by_start_time") - case DeliverLastPerSubjectPolicy: - return json.Marshal("last_per_subject") - default: - return nil, fmt.Errorf("nats: unknown deliver policy %v", p) - } -} - -// RetentionPolicy determines how messages in a set are retained. -type RetentionPolicy int - -const ( - // LimitsPolicy (default) means that messages are retained until any given limit is reached. - // This could be one of MaxMsgs, MaxBytes, or MaxAge. - LimitsPolicy RetentionPolicy = iota - // InterestPolicy specifies that when all known observables have acknowledged a message it can be removed. - InterestPolicy - // WorkQueuePolicy specifies that when the first worker or subscriber acknowledges the message it can be removed. - WorkQueuePolicy -) - -// DiscardPolicy determines how to proceed when limits of messages or bytes are -// reached. -type DiscardPolicy int - -const ( - // DiscardOld will remove older messages to return to the limits. This is - // the default. - DiscardOld DiscardPolicy = iota - //DiscardNew will fail to store new messages. - DiscardNew -) - -const ( - limitsPolicyString = "limits" - interestPolicyString = "interest" - workQueuePolicyString = "workqueue" -) - -func (rp RetentionPolicy) String() string { - switch rp { - case LimitsPolicy: - return "Limits" - case InterestPolicy: - return "Interest" - case WorkQueuePolicy: - return "WorkQueue" - default: - return "Unknown Retention Policy" - } -} - -func (rp RetentionPolicy) MarshalJSON() ([]byte, error) { - switch rp { - case LimitsPolicy: - return json.Marshal(limitsPolicyString) - case InterestPolicy: - return json.Marshal(interestPolicyString) - case WorkQueuePolicy: - return json.Marshal(workQueuePolicyString) - default: - return nil, fmt.Errorf("nats: can not marshal %v", rp) - } -} - -func (rp *RetentionPolicy) UnmarshalJSON(data []byte) error { - switch string(data) { - case jsonString(limitsPolicyString): - *rp = LimitsPolicy - case jsonString(interestPolicyString): - *rp = InterestPolicy - case jsonString(workQueuePolicyString): - *rp = WorkQueuePolicy - default: - return fmt.Errorf("nats: can not unmarshal %q", data) - } - return nil -} - -func (dp DiscardPolicy) String() string { - switch dp { - case DiscardOld: - return "DiscardOld" - case DiscardNew: - return "DiscardNew" - default: - return "Unknown Discard Policy" - } -} - -func (dp DiscardPolicy) MarshalJSON() ([]byte, error) { - switch dp { - case DiscardOld: - return json.Marshal("old") - case DiscardNew: - return json.Marshal("new") - default: - return nil, fmt.Errorf("nats: can not marshal %v", dp) - } -} - -func (dp *DiscardPolicy) UnmarshalJSON(data []byte) error { - switch strings.ToLower(string(data)) { - case jsonString("old"): - *dp = DiscardOld - case jsonString("new"): - *dp = DiscardNew - default: - return fmt.Errorf("nats: can not unmarshal %q", data) - } - return nil -} - -// StorageType determines how messages are stored for retention. -type StorageType int - -const ( - // FileStorage specifies on disk storage. It's the default. - FileStorage StorageType = iota - // MemoryStorage specifies in memory only. - MemoryStorage -) - -const ( - memoryStorageString = "memory" - fileStorageString = "file" -) - -func (st StorageType) String() string { - switch st { - case MemoryStorage: - return "Memory" - case FileStorage: - return "File" - default: - return "Unknown Storage Type" - } -} - -func (st StorageType) MarshalJSON() ([]byte, error) { - switch st { - case MemoryStorage: - return json.Marshal(memoryStorageString) - case FileStorage: - return json.Marshal(fileStorageString) - default: - return nil, fmt.Errorf("nats: can not marshal %v", st) - } -} - -func (st *StorageType) UnmarshalJSON(data []byte) error { - switch string(data) { - case jsonString(memoryStorageString): - *st = MemoryStorage - case jsonString(fileStorageString): - *st = FileStorage - default: - return fmt.Errorf("nats: can not unmarshal %q", data) - } - return nil -} - -type StoreCompression uint8 - -const ( - NoCompression StoreCompression = iota - S2Compression -) - -func (alg StoreCompression) String() string { - switch alg { - case NoCompression: - return "None" - case S2Compression: - return "S2" - default: - return "Unknown StoreCompression" - } -} - -func (alg StoreCompression) MarshalJSON() ([]byte, error) { - var str string - switch alg { - case S2Compression: - str = "s2" - case NoCompression: - str = "none" - default: - return nil, fmt.Errorf("unknown compression algorithm") - } - return json.Marshal(str) -} - -func (alg *StoreCompression) UnmarshalJSON(b []byte) error { - var str string - if err := json.Unmarshal(b, &str); err != nil { - return err - } - switch str { - case "s2": - *alg = S2Compression - case "none": - *alg = NoCompression - default: - return fmt.Errorf("unknown compression algorithm") - } - return nil -} - -// Length of our hash used for named consumers. -const nameHashLen = 8 - -// Computes a hash for the given `name`. -func getHash(name string) string { - sha := sha256.New() - sha.Write([]byte(name)) - b := sha.Sum(nil) - for i := 0; i < nameHashLen; i++ { - b[i] = rdigits[int(b[i]%base)] - } - return string(b[:nameHashLen]) -} diff --git a/vendor/github.com/nats-io/nats.go/jserrors.go b/vendor/github.com/nats-io/nats.go/jserrors.go deleted file mode 100644 index ef5d4af94..000000000 --- a/vendor/github.com/nats-io/nats.go/jserrors.go +++ /dev/null @@ -1,235 +0,0 @@ -// Copyright 2020-2023 The NATS 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 nats - -import ( - "errors" - "fmt" -) - -var ( - // API errors - - // ErrJetStreamNotEnabled is an error returned when JetStream is not enabled for an account. - ErrJetStreamNotEnabled JetStreamError = &jsError{apiErr: &APIError{ErrorCode: JSErrCodeJetStreamNotEnabled, Description: "jetstream not enabled", Code: 503}} - - // ErrJetStreamNotEnabledForAccount is an error returned when JetStream is not enabled for an account. - ErrJetStreamNotEnabledForAccount JetStreamError = &jsError{apiErr: &APIError{ErrorCode: JSErrCodeJetStreamNotEnabledForAccount, Description: "jetstream not enabled for account", Code: 503}} - - // ErrStreamNotFound is an error returned when stream with given name does not exist. - ErrStreamNotFound JetStreamError = &jsError{apiErr: &APIError{ErrorCode: JSErrCodeStreamNotFound, Description: "stream not found", Code: 404}} - - // ErrStreamNameAlreadyInUse is returned when a stream with given name already exists and has a different configuration. - ErrStreamNameAlreadyInUse JetStreamError = &jsError{apiErr: &APIError{ErrorCode: JSErrCodeStreamNameInUse, Description: "stream name already in use", Code: 400}} - - // ErrStreamSubjectTransformNotSupported is returned when the connected nats-server version does not support setting - // the stream subject transform. If this error is returned when executing AddStream(), the stream with invalid - // configuration was already created in the server. - ErrStreamSubjectTransformNotSupported JetStreamError = &jsError{message: "stream subject transformation not supported by nats-server"} - - // ErrStreamSourceSubjectTransformNotSupported is returned when the connected nats-server version does not support setting - // the stream source subject transform. If this error is returned when executing AddStream(), the stream with invalid - // configuration was already created in the server. - ErrStreamSourceSubjectTransformNotSupported JetStreamError = &jsError{message: "stream subject transformation not supported by nats-server"} - - // ErrStreamSourceNotSupported is returned when the connected nats-server version does not support setting - // the stream sources. If this error is returned when executing AddStream(), the stream with invalid - // configuration was already created in the server. - ErrStreamSourceNotSupported JetStreamError = &jsError{message: "stream sourcing is not supported by nats-server"} - - // ErrStreamSourceMultipleSubjectTransformsNotSupported is returned when the connected nats-server version does not support setting - // the stream sources. If this error is returned when executing AddStream(), the stream with invalid - // configuration was already created in the server. - ErrStreamSourceMultipleSubjectTransformsNotSupported JetStreamError = &jsError{message: "stream sourceing with multiple subject transforms not supported by nats-server"} - - // ErrConsumerNotFound is an error returned when consumer with given name does not exist. - ErrConsumerNotFound JetStreamError = &jsError{apiErr: &APIError{ErrorCode: JSErrCodeConsumerNotFound, Description: "consumer not found", Code: 404}} - - // ErrMsgNotFound is returned when message with provided sequence number does npt exist. - ErrMsgNotFound JetStreamError = &jsError{apiErr: &APIError{ErrorCode: JSErrCodeMessageNotFound, Description: "message not found", Code: 404}} - - // ErrBadRequest is returned when invalid request is sent to JetStream API. - ErrBadRequest JetStreamError = &jsError{apiErr: &APIError{ErrorCode: JSErrCodeBadRequest, Description: "bad request", Code: 400}} - - // ErrDuplicateFilterSubjects is returned when both FilterSubject and FilterSubjects are specified when creating consumer. - ErrDuplicateFilterSubjects JetStreamError = &jsError{apiErr: &APIError{ErrorCode: JSErrCodeDuplicateFilterSubjects, Description: "consumer cannot have both FilterSubject and FilterSubjects specified", Code: 500}} - - // ErrDuplicateFilterSubjects is returned when filter subjects overlap when creating consumer. - ErrOverlappingFilterSubjects JetStreamError = &jsError{apiErr: &APIError{ErrorCode: JSErrCodeOverlappingFilterSubjects, Description: "consumer subject filters cannot overlap", Code: 500}} - - // ErrEmptyFilter is returned when a filter in FilterSubjects is empty. - ErrEmptyFilter JetStreamError = &jsError{apiErr: &APIError{ErrorCode: JSErrCodeConsumerEmptyFilter, Description: "consumer filter in FilterSubjects cannot be empty", Code: 500}} - - // Client errors - - // ErrConsumerNameAlreadyInUse is an error returned when consumer with given name already exists. - ErrConsumerNameAlreadyInUse JetStreamError = &jsError{message: "consumer name already in use"} - - // ErrConsumerNotActive is an error returned when consumer is not active. - ErrConsumerNotActive JetStreamError = &jsError{message: "consumer not active"} - - // ErrInvalidJSAck is returned when JetStream ack from message publish is invalid. - ErrInvalidJSAck JetStreamError = &jsError{message: "invalid jetstream publish response"} - - // ErrStreamConfigRequired is returned when empty stream configuration is supplied to add/update stream. - ErrStreamConfigRequired JetStreamError = &jsError{message: "stream configuration is required"} - - // ErrStreamNameRequired is returned when the provided stream name is empty. - ErrStreamNameRequired JetStreamError = &jsError{message: "stream name is required"} - - // ErrConsumerNameRequired is returned when the provided consumer durable name is empty. - ErrConsumerNameRequired JetStreamError = &jsError{message: "consumer name is required"} - - // ErrConsumerMultipleFilterSubjectsNotSupported is returned when the connected nats-server version does not support setting - // multiple filter subjects with filter_subjects field. If this error is returned when executing AddConsumer(), the consumer with invalid - // configuration was already created in the server. - ErrConsumerMultipleFilterSubjectsNotSupported JetStreamError = &jsError{message: "multiple consumer filter subjects not supported by nats-server"} - - // ErrConsumerConfigRequired is returned when empty consumer consuguration is supplied to add/update consumer. - ErrConsumerConfigRequired JetStreamError = &jsError{message: "consumer configuration is required"} - - // ErrPullSubscribeToPushConsumer is returned when attempting to use PullSubscribe on push consumer. - ErrPullSubscribeToPushConsumer JetStreamError = &jsError{message: "cannot pull subscribe to push based consumer"} - - // ErrPullSubscribeRequired is returned when attempting to use subscribe methods not suitable for pull consumers for pull consumers. - ErrPullSubscribeRequired JetStreamError = &jsError{message: "must use pull subscribe to bind to pull based consumer"} - - // ErrMsgAlreadyAckd is returned when attempting to acknowledge message more than once. - ErrMsgAlreadyAckd JetStreamError = &jsError{message: "message was already acknowledged"} - - // ErrNoStreamResponse is returned when there is no response from stream (e.g. no responders error). - ErrNoStreamResponse JetStreamError = &jsError{message: "no response from stream"} - - // ErrNotJSMessage is returned when attempting to get metadata from non JetStream message . - ErrNotJSMessage JetStreamError = &jsError{message: "not a jetstream message"} - - // ErrInvalidStreamName is returned when the provided stream name is invalid (contains '.' or ' '). - ErrInvalidStreamName JetStreamError = &jsError{message: "invalid stream name"} - - // ErrInvalidConsumerName is returned when the provided consumer name is invalid (contains '.' or ' '). - ErrInvalidConsumerName JetStreamError = &jsError{message: "invalid consumer name"} - - // ErrNoMatchingStream is returned when stream lookup by subject is unsuccessful. - ErrNoMatchingStream JetStreamError = &jsError{message: "no stream matches subject"} - - // ErrSubjectMismatch is returned when the provided subject does not match consumer's filter subject. - ErrSubjectMismatch JetStreamError = &jsError{message: "subject does not match consumer"} - - // ErrContextAndTimeout is returned when attempting to use both context and timeout. - ErrContextAndTimeout JetStreamError = &jsError{message: "context and timeout can not both be set"} - - // ErrCantAckIfConsumerAckNone is returned when attempting to ack a message for consumer with AckNone policy set. - ErrCantAckIfConsumerAckNone JetStreamError = &jsError{message: "cannot acknowledge a message for a consumer with AckNone policy"} - - // ErrConsumerDeleted is returned when attempting to send pull request to a consumer which does not exist - ErrConsumerDeleted JetStreamError = &jsError{message: "consumer deleted"} - - // ErrConsumerLeadershipChanged is returned when pending requests are no longer valid after leadership has changed - ErrConsumerLeadershipChanged JetStreamError = &jsError{message: "Leadership Changed"} - - // ErrNoHeartbeat is returned when no heartbeat is received from server when sending requests with pull consumer. - ErrNoHeartbeat JetStreamError = &jsError{message: "no heartbeat received"} - - // DEPRECATED: ErrInvalidDurableName is no longer returned and will be removed in future releases. - // Use ErrInvalidConsumerName instead. - ErrInvalidDurableName = errors.New("nats: invalid durable name") -) - -// Error code represents JetStream error codes returned by the API -type ErrorCode uint16 - -const ( - JSErrCodeJetStreamNotEnabledForAccount ErrorCode = 10039 - JSErrCodeJetStreamNotEnabled ErrorCode = 10076 - JSErrCodeInsufficientResourcesErr ErrorCode = 10023 - - JSErrCodeStreamNotFound ErrorCode = 10059 - JSErrCodeStreamNameInUse ErrorCode = 10058 - - JSErrCodeConsumerNotFound ErrorCode = 10014 - JSErrCodeConsumerNameExists ErrorCode = 10013 - JSErrCodeConsumerAlreadyExists ErrorCode = 10105 - JSErrCodeDuplicateFilterSubjects ErrorCode = 10136 - JSErrCodeOverlappingFilterSubjects ErrorCode = 10138 - JSErrCodeConsumerEmptyFilter ErrorCode = 10139 - - JSErrCodeMessageNotFound ErrorCode = 10037 - - JSErrCodeBadRequest ErrorCode = 10003 - JSStreamInvalidConfig ErrorCode = 10052 - - JSErrCodeStreamWrongLastSequence ErrorCode = 10071 -) - -// APIError is included in all API responses if there was an error. -type APIError struct { - Code int `json:"code"` - ErrorCode ErrorCode `json:"err_code"` - Description string `json:"description,omitempty"` -} - -// Error prints the JetStream API error code and description -func (e *APIError) Error() string { - return fmt.Sprintf("nats: %s", e.Description) -} - -// APIError implements the JetStreamError interface. -func (e *APIError) APIError() *APIError { - return e -} - -// Is matches against an APIError. -func (e *APIError) Is(err error) bool { - if e == nil { - return false - } - // Extract internal APIError to match against. - var aerr *APIError - ok := errors.As(err, &aerr) - if !ok { - return ok - } - return e.ErrorCode == aerr.ErrorCode -} - -// JetStreamError is an error result that happens when using JetStream. -// In case of client-side error, `APIError()` returns nil -type JetStreamError interface { - APIError() *APIError - error -} - -type jsError struct { - apiErr *APIError - message string -} - -func (err *jsError) APIError() *APIError { - return err.apiErr -} - -func (err *jsError) Error() string { - if err.apiErr != nil && err.apiErr.Description != "" { - return err.apiErr.Error() - } - return fmt.Sprintf("nats: %s", err.message) -} - -func (err *jsError) Unwrap() error { - // Allow matching to embedded APIError in case there is one. - if err.apiErr == nil { - return nil - } - return err.apiErr -} diff --git a/vendor/github.com/nats-io/nats.go/jsm.go b/vendor/github.com/nats-io/nats.go/jsm.go deleted file mode 100644 index 94fa86c32..000000000 --- a/vendor/github.com/nats-io/nats.go/jsm.go +++ /dev/null @@ -1,1675 +0,0 @@ -// Copyright 2021-2023 The NATS 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 nats - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "strconv" - "strings" - "time" -) - -// JetStreamManager manages JetStream Streams and Consumers. -type JetStreamManager interface { - // AddStream creates a stream. - AddStream(cfg *StreamConfig, opts ...JSOpt) (*StreamInfo, error) - - // UpdateStream updates a stream. - UpdateStream(cfg *StreamConfig, opts ...JSOpt) (*StreamInfo, error) - - // DeleteStream deletes a stream. - DeleteStream(name string, opts ...JSOpt) error - - // StreamInfo retrieves information from a stream. - StreamInfo(stream string, opts ...JSOpt) (*StreamInfo, error) - - // PurgeStream purges a stream messages. - PurgeStream(name string, opts ...JSOpt) error - - // StreamsInfo can be used to retrieve a list of StreamInfo objects. - // DEPRECATED: Use Streams() instead. - StreamsInfo(opts ...JSOpt) <-chan *StreamInfo - - // Streams can be used to retrieve a list of StreamInfo objects. - Streams(opts ...JSOpt) <-chan *StreamInfo - - // StreamNames is used to retrieve a list of Stream names. - StreamNames(opts ...JSOpt) <-chan string - - // GetMsg retrieves a raw stream message stored in JetStream by sequence number. - // Use options nats.DirectGet() or nats.DirectGetNext() to trigger retrieval - // directly from a distributed group of servers (leader and replicas). - // The stream must have been created/updated with the AllowDirect boolean. - GetMsg(name string, seq uint64, opts ...JSOpt) (*RawStreamMsg, error) - - // GetLastMsg retrieves the last raw stream message stored in JetStream by subject. - // Use option nats.DirectGet() to trigger retrieval - // directly from a distributed group of servers (leader and replicas). - // The stream must have been created/updated with the AllowDirect boolean. - GetLastMsg(name, subject string, opts ...JSOpt) (*RawStreamMsg, error) - - // DeleteMsg deletes a message from a stream. The message is marked as erased, but its value is not overwritten. - DeleteMsg(name string, seq uint64, opts ...JSOpt) error - - // SecureDeleteMsg deletes a message from a stream. The deleted message is overwritten with random data - // As a result, this operation is slower than DeleteMsg() - SecureDeleteMsg(name string, seq uint64, opts ...JSOpt) error - - // AddConsumer adds a consumer to a stream. - // If the consumer already exists, and the configuration is the same, it - // will return the existing consumer. - // If the consumer already exists, and the configuration is different, it - // will return ErrConsumerNameAlreadyInUse. - AddConsumer(stream string, cfg *ConsumerConfig, opts ...JSOpt) (*ConsumerInfo, error) - - // UpdateConsumer updates an existing consumer. - UpdateConsumer(stream string, cfg *ConsumerConfig, opts ...JSOpt) (*ConsumerInfo, error) - - // DeleteConsumer deletes a consumer. - DeleteConsumer(stream, consumer string, opts ...JSOpt) error - - // ConsumerInfo retrieves information of a consumer from a stream. - ConsumerInfo(stream, name string, opts ...JSOpt) (*ConsumerInfo, error) - - // ConsumersInfo is used to retrieve a list of ConsumerInfo objects. - // DEPRECATED: Use Consumers() instead. - ConsumersInfo(stream string, opts ...JSOpt) <-chan *ConsumerInfo - - // Consumers is used to retrieve a list of ConsumerInfo objects. - Consumers(stream string, opts ...JSOpt) <-chan *ConsumerInfo - - // ConsumerNames is used to retrieve a list of Consumer names. - ConsumerNames(stream string, opts ...JSOpt) <-chan string - - // AccountInfo retrieves info about the JetStream usage from an account. - AccountInfo(opts ...JSOpt) (*AccountInfo, error) - - // StreamNameBySubject returns a stream matching given subject. - StreamNameBySubject(string, ...JSOpt) (string, error) -} - -// StreamConfig will determine the properties for a stream. -// There are sensible defaults for most. If no subjects are -// given the name will be used as the only subject. -type StreamConfig struct { - Name string `json:"name"` - Description string `json:"description,omitempty"` - Subjects []string `json:"subjects,omitempty"` - Retention RetentionPolicy `json:"retention"` - MaxConsumers int `json:"max_consumers"` - MaxMsgs int64 `json:"max_msgs"` - MaxBytes int64 `json:"max_bytes"` - Discard DiscardPolicy `json:"discard"` - DiscardNewPerSubject bool `json:"discard_new_per_subject,omitempty"` - MaxAge time.Duration `json:"max_age"` - MaxMsgsPerSubject int64 `json:"max_msgs_per_subject"` - MaxMsgSize int32 `json:"max_msg_size,omitempty"` - Storage StorageType `json:"storage"` - Replicas int `json:"num_replicas"` - NoAck bool `json:"no_ack,omitempty"` - Template string `json:"template_owner,omitempty"` - Duplicates time.Duration `json:"duplicate_window,omitempty"` - Placement *Placement `json:"placement,omitempty"` - Mirror *StreamSource `json:"mirror,omitempty"` - Sources []*StreamSource `json:"sources,omitempty"` - Sealed bool `json:"sealed,omitempty"` - DenyDelete bool `json:"deny_delete,omitempty"` - DenyPurge bool `json:"deny_purge,omitempty"` - AllowRollup bool `json:"allow_rollup_hdrs,omitempty"` - Compression StoreCompression `json:"compression"` - FirstSeq uint64 `json:"first_seq,omitempty"` - - // Allow applying a subject transform to incoming messages before doing anything else. - SubjectTransform *SubjectTransformConfig `json:"subject_transform,omitempty"` - - // Allow republish of the message after being sequenced and stored. - RePublish *RePublish `json:"republish,omitempty"` - - // Allow higher performance, direct access to get individual messages. E.g. KeyValue - AllowDirect bool `json:"allow_direct"` - // Allow higher performance and unified direct access for mirrors as well. - MirrorDirect bool `json:"mirror_direct"` - - // Limits for consumers on this stream. - ConsumerLimits StreamConsumerLimits `json:"consumer_limits,omitempty"` - - // Metadata is additional metadata for the Stream. - // Keys starting with `_nats` are reserved. - // NOTE: Metadata requires nats-server v2.10.0+ - Metadata map[string]string `json:"metadata,omitempty"` -} - -// SubjectTransformConfig is for applying a subject transform (to matching messages) before doing anything else when a new message is received. -type SubjectTransformConfig struct { - Source string `json:"src,omitempty"` - Destination string `json:"dest"` -} - -// RePublish is for republishing messages once committed to a stream. The original -// subject cis remapped from the subject pattern to the destination pattern. -type RePublish struct { - Source string `json:"src,omitempty"` - Destination string `json:"dest"` - HeadersOnly bool `json:"headers_only,omitempty"` -} - -// Placement is used to guide placement of streams in clustered JetStream. -type Placement struct { - Cluster string `json:"cluster"` - Tags []string `json:"tags,omitempty"` -} - -// StreamSource dictates how streams can source from other streams. -type StreamSource struct { - Name string `json:"name"` - OptStartSeq uint64 `json:"opt_start_seq,omitempty"` - OptStartTime *time.Time `json:"opt_start_time,omitempty"` - FilterSubject string `json:"filter_subject,omitempty"` - SubjectTransforms []SubjectTransformConfig `json:"subject_transforms,omitempty"` - External *ExternalStream `json:"external,omitempty"` - Domain string `json:"-"` -} - -// ExternalStream allows you to qualify access to a stream source in another -// account. -type ExternalStream struct { - APIPrefix string `json:"api"` - DeliverPrefix string `json:"deliver,omitempty"` -} - -// StreamConsumerLimits are the limits for a consumer on a stream. -// These can be overridden on a per consumer basis. -type StreamConsumerLimits struct { - InactiveThreshold time.Duration `json:"inactive_threshold,omitempty"` - MaxAckPending int `json:"max_ack_pending,omitempty"` -} - -// Helper for copying when we do not want to change user's version. -func (ss *StreamSource) copy() *StreamSource { - nss := *ss - // Check pointers - if ss.OptStartTime != nil { - t := *ss.OptStartTime - nss.OptStartTime = &t - } - if ss.External != nil { - ext := *ss.External - nss.External = &ext - } - return &nss -} - -// If we have a Domain, convert to the appropriate ext.APIPrefix. -// This will change the stream source, so should be a copy passed in. -func (ss *StreamSource) convertDomain() error { - if ss.Domain == _EMPTY_ { - return nil - } - if ss.External != nil { - // These should be mutually exclusive. - // TODO(dlc) - Make generic? - return errors.New("nats: domain and external are both set") - } - ss.External = &ExternalStream{APIPrefix: fmt.Sprintf(jsExtDomainT, ss.Domain)} - return nil -} - -// apiResponse is a standard response from the JetStream JSON API -type apiResponse struct { - Type string `json:"type"` - Error *APIError `json:"error,omitempty"` -} - -// apiPaged includes variables used to create paged responses from the JSON API -type apiPaged struct { - Total int `json:"total"` - Offset int `json:"offset"` - Limit int `json:"limit"` -} - -// apiPagedRequest includes parameters allowing specific pages to be requested -// from APIs responding with apiPaged. -type apiPagedRequest struct { - Offset int `json:"offset,omitempty"` -} - -// AccountInfo contains info about the JetStream usage from the current account. -type AccountInfo struct { - Tier - Domain string `json:"domain"` - API APIStats `json:"api"` - Tiers map[string]Tier `json:"tiers"` -} - -type Tier struct { - Memory uint64 `json:"memory"` - Store uint64 `json:"storage"` - ReservedMemory uint64 `json:"reserved_memory"` - ReservedStore uint64 `json:"reserved_storage"` - Streams int `json:"streams"` - Consumers int `json:"consumers"` - Limits AccountLimits `json:"limits"` -} - -// APIStats reports on API calls to JetStream for this account. -type APIStats struct { - Total uint64 `json:"total"` - Errors uint64 `json:"errors"` -} - -// AccountLimits includes the JetStream limits of the current account. -type AccountLimits struct { - MaxMemory int64 `json:"max_memory"` - MaxStore int64 `json:"max_storage"` - MaxStreams int `json:"max_streams"` - MaxConsumers int `json:"max_consumers"` - MaxAckPending int `json:"max_ack_pending"` - MemoryMaxStreamBytes int64 `json:"memory_max_stream_bytes"` - StoreMaxStreamBytes int64 `json:"storage_max_stream_bytes"` - MaxBytesRequired bool `json:"max_bytes_required"` -} - -type accountInfoResponse struct { - apiResponse - AccountInfo -} - -// AccountInfo retrieves info about the JetStream usage from the current account. -// If JetStream is not enabled, this will return ErrJetStreamNotEnabled -// Other errors can happen but are generally considered retryable -func (js *js) AccountInfo(opts ...JSOpt) (*AccountInfo, error) { - o, cancel, err := getJSContextOpts(js.opts, opts...) - if err != nil { - return nil, err - } - if cancel != nil { - defer cancel() - } - - resp, err := js.apiRequestWithContext(o.ctx, js.apiSubj(apiAccountInfo), nil) - if err != nil { - // todo maybe nats server should never have no responder on this subject and always respond if they know there is no js to be had - if errors.Is(err, ErrNoResponders) { - err = ErrJetStreamNotEnabled - } - return nil, err - } - var info accountInfoResponse - if err := json.Unmarshal(resp.Data, &info); err != nil { - return nil, err - } - if info.Error != nil { - // Internally checks based on error code instead of description match. - if errors.Is(info.Error, ErrJetStreamNotEnabledForAccount) { - return nil, ErrJetStreamNotEnabledForAccount - } - return nil, info.Error - } - - return &info.AccountInfo, nil -} - -type createConsumerRequest struct { - Stream string `json:"stream_name"` - Config *ConsumerConfig `json:"config"` -} - -type consumerResponse struct { - apiResponse - *ConsumerInfo -} - -// AddConsumer adds a consumer to a stream. -// If the consumer already exists, and the configuration is the same, it -// will return the existing consumer. -// If the consumer already exists, and the configuration is different, it -// will return ErrConsumerNameAlreadyInUse. -func (js *js) AddConsumer(stream string, cfg *ConsumerConfig, opts ...JSOpt) (*ConsumerInfo, error) { - if cfg == nil { - cfg = &ConsumerConfig{} - } - consumerName := cfg.Name - if consumerName == _EMPTY_ { - consumerName = cfg.Durable - } - if consumerName != _EMPTY_ { - consInfo, err := js.ConsumerInfo(stream, consumerName, opts...) - if err != nil && !errors.Is(err, ErrConsumerNotFound) && !errors.Is(err, ErrStreamNotFound) { - return nil, err - } - - if consInfo != nil { - sameConfig := checkConfig(&consInfo.Config, cfg) - if sameConfig != nil { - return nil, fmt.Errorf("%w: creating consumer %q on stream %q", ErrConsumerNameAlreadyInUse, consumerName, stream) - } else { - return consInfo, nil - } - } - } - - return js.upsertConsumer(stream, consumerName, cfg, opts...) -} - -func (js *js) UpdateConsumer(stream string, cfg *ConsumerConfig, opts ...JSOpt) (*ConsumerInfo, error) { - if cfg == nil { - return nil, ErrConsumerConfigRequired - } - consumerName := cfg.Name - if consumerName == _EMPTY_ { - consumerName = cfg.Durable - } - if consumerName == _EMPTY_ { - return nil, ErrConsumerNameRequired - } - return js.upsertConsumer(stream, consumerName, cfg, opts...) -} - -func (js *js) upsertConsumer(stream, consumerName string, cfg *ConsumerConfig, opts ...JSOpt) (*ConsumerInfo, error) { - if err := checkStreamName(stream); err != nil { - return nil, err - } - o, cancel, err := getJSContextOpts(js.opts, opts...) - if err != nil { - return nil, err - } - if cancel != nil { - defer cancel() - } - - req, err := json.Marshal(&createConsumerRequest{Stream: stream, Config: cfg}) - if err != nil { - return nil, err - } - - var ccSubj string - if consumerName == _EMPTY_ { - // if consumer name is empty (neither Durable nor Name is set), use the legacy ephemeral endpoint - ccSubj = fmt.Sprintf(apiLegacyConsumerCreateT, stream) - } else if err := checkConsumerName(consumerName); err != nil { - return nil, err - } else if js.nc.serverMinVersion(2, 9, 0) { - if cfg.Durable != "" && js.opts.featureFlags.useDurableConsumerCreate { - // if user set the useDurableConsumerCreate flag, use the legacy DURABLE.CREATE endpoint - ccSubj = fmt.Sprintf(apiDurableCreateT, stream, consumerName) - } else if cfg.FilterSubject == _EMPTY_ || cfg.FilterSubject == ">" { - // if filter subject is empty or ">", use the endpoint without filter subject - ccSubj = fmt.Sprintf(apiConsumerCreateT, stream, consumerName) - } else { - // if filter subject is not empty, use the endpoint with filter subject - ccSubj = fmt.Sprintf(apiConsumerCreateWithFilterSubjectT, stream, consumerName, cfg.FilterSubject) - } - } else { - if cfg.Durable != "" { - // if Durable is set, use the DURABLE.CREATE endpoint - ccSubj = fmt.Sprintf(apiDurableCreateT, stream, consumerName) - } else { - // if Durable is not set, use the legacy ephemeral endpoint - ccSubj = fmt.Sprintf(apiLegacyConsumerCreateT, stream) - } - } - - resp, err := js.apiRequestWithContext(o.ctx, js.apiSubj(ccSubj), req) - if err != nil { - if errors.Is(err, ErrNoResponders) { - err = ErrJetStreamNotEnabled - } - return nil, err - } - var info consumerResponse - err = json.Unmarshal(resp.Data, &info) - if err != nil { - return nil, err - } - if info.Error != nil { - if errors.Is(info.Error, ErrStreamNotFound) { - return nil, ErrStreamNotFound - } - if errors.Is(info.Error, ErrConsumerNotFound) { - return nil, ErrConsumerNotFound - } - return nil, info.Error - } - - // check whether multiple filter subjects (if used) are reflected in the returned ConsumerInfo - if len(cfg.FilterSubjects) != 0 && len(info.Config.FilterSubjects) == 0 { - return nil, ErrConsumerMultipleFilterSubjectsNotSupported - } - return info.ConsumerInfo, nil -} - -// consumerDeleteResponse is the response for a Consumer delete request. -type consumerDeleteResponse struct { - apiResponse - Success bool `json:"success,omitempty"` -} - -func checkStreamName(stream string) error { - if stream == _EMPTY_ { - return ErrStreamNameRequired - } - if strings.ContainsAny(stream, ". ") { - return ErrInvalidStreamName - } - return nil -} - -// Check that the consumer name is not empty and is valid (does not contain "." and " "). -// Additional consumer name validation is done in nats-server. -// Returns ErrConsumerNameRequired if consumer name is empty, ErrInvalidConsumerName is invalid, otherwise nil -func checkConsumerName(consumer string) error { - if consumer == _EMPTY_ { - return ErrConsumerNameRequired - } - if strings.ContainsAny(consumer, ". ") { - return ErrInvalidConsumerName - } - return nil -} - -// DeleteConsumer deletes a Consumer. -func (js *js) DeleteConsumer(stream, consumer string, opts ...JSOpt) error { - if err := checkStreamName(stream); err != nil { - return err - } - if err := checkConsumerName(consumer); err != nil { - return err - } - o, cancel, err := getJSContextOpts(js.opts, opts...) - if err != nil { - return err - } - if cancel != nil { - defer cancel() - } - - dcSubj := js.apiSubj(fmt.Sprintf(apiConsumerDeleteT, stream, consumer)) - r, err := js.apiRequestWithContext(o.ctx, dcSubj, nil) - if err != nil { - return err - } - var resp consumerDeleteResponse - if err := json.Unmarshal(r.Data, &resp); err != nil { - return err - } - - if resp.Error != nil { - if errors.Is(resp.Error, ErrConsumerNotFound) { - return ErrConsumerNotFound - } - return resp.Error - } - return nil -} - -// ConsumerInfo returns information about a Consumer. -func (js *js) ConsumerInfo(stream, consumer string, opts ...JSOpt) (*ConsumerInfo, error) { - if err := checkStreamName(stream); err != nil { - return nil, err - } - if err := checkConsumerName(consumer); err != nil { - return nil, err - } - o, cancel, err := getJSContextOpts(js.opts, opts...) - if err != nil { - return nil, err - } - if cancel != nil { - defer cancel() - } - return js.getConsumerInfoContext(o.ctx, stream, consumer) -} - -// consumerLister fetches pages of ConsumerInfo objects. This object is not -// safe to use for multiple threads. -type consumerLister struct { - stream string - js *js - - err error - offset int - page []*ConsumerInfo - pageInfo *apiPaged -} - -// consumersRequest is the type used for Consumers requests. -type consumersRequest struct { - apiPagedRequest -} - -// consumerListResponse is the response for a Consumers List request. -type consumerListResponse struct { - apiResponse - apiPaged - Consumers []*ConsumerInfo `json:"consumers"` -} - -// Next fetches the next ConsumerInfo page. -func (c *consumerLister) Next() bool { - if c.err != nil { - return false - } - if err := checkStreamName(c.stream); err != nil { - c.err = err - return false - } - if c.pageInfo != nil && c.offset >= c.pageInfo.Total { - return false - } - - req, err := json.Marshal(consumersRequest{ - apiPagedRequest: apiPagedRequest{Offset: c.offset}, - }) - if err != nil { - c.err = err - return false - } - - var cancel context.CancelFunc - ctx := c.js.opts.ctx - if ctx == nil { - ctx, cancel = context.WithTimeout(context.Background(), c.js.opts.wait) - defer cancel() - } - - clSubj := c.js.apiSubj(fmt.Sprintf(apiConsumerListT, c.stream)) - r, err := c.js.apiRequestWithContext(ctx, clSubj, req) - if err != nil { - c.err = err - return false - } - var resp consumerListResponse - if err := json.Unmarshal(r.Data, &resp); err != nil { - c.err = err - return false - } - if resp.Error != nil { - c.err = resp.Error - return false - } - - c.pageInfo = &resp.apiPaged - c.page = resp.Consumers - c.offset += len(c.page) - return true -} - -// Page returns the current ConsumerInfo page. -func (c *consumerLister) Page() []*ConsumerInfo { - return c.page -} - -// Err returns any errors found while fetching pages. -func (c *consumerLister) Err() error { - return c.err -} - -// Consumers is used to retrieve a list of ConsumerInfo objects. -func (jsc *js) Consumers(stream string, opts ...JSOpt) <-chan *ConsumerInfo { - o, cancel, err := getJSContextOpts(jsc.opts, opts...) - if err != nil { - return nil - } - - ch := make(chan *ConsumerInfo) - l := &consumerLister{js: &js{nc: jsc.nc, opts: o}, stream: stream} - go func() { - if cancel != nil { - defer cancel() - } - defer close(ch) - for l.Next() { - for _, info := range l.Page() { - select { - case ch <- info: - case <-o.ctx.Done(): - return - } - } - } - }() - - return ch -} - -// ConsumersInfo is used to retrieve a list of ConsumerInfo objects. -// DEPRECATED: Use Consumers() instead. -func (jsc *js) ConsumersInfo(stream string, opts ...JSOpt) <-chan *ConsumerInfo { - return jsc.Consumers(stream, opts...) -} - -type consumerNamesLister struct { - stream string - js *js - - err error - offset int - page []string - pageInfo *apiPaged -} - -// consumerNamesListResponse is the response for a Consumers Names List request. -type consumerNamesListResponse struct { - apiResponse - apiPaged - Consumers []string `json:"consumers"` -} - -// Next fetches the next consumer names page. -func (c *consumerNamesLister) Next() bool { - if c.err != nil { - return false - } - if err := checkStreamName(c.stream); err != nil { - c.err = err - return false - } - if c.pageInfo != nil && c.offset >= c.pageInfo.Total { - return false - } - - var cancel context.CancelFunc - ctx := c.js.opts.ctx - if ctx == nil { - ctx, cancel = context.WithTimeout(context.Background(), c.js.opts.wait) - defer cancel() - } - - req, err := json.Marshal(consumersRequest{ - apiPagedRequest: apiPagedRequest{Offset: c.offset}, - }) - if err != nil { - c.err = err - return false - } - clSubj := c.js.apiSubj(fmt.Sprintf(apiConsumerNamesT, c.stream)) - r, err := c.js.apiRequestWithContext(ctx, clSubj, req) - if err != nil { - c.err = err - return false - } - var resp consumerNamesListResponse - if err := json.Unmarshal(r.Data, &resp); err != nil { - c.err = err - return false - } - if resp.Error != nil { - c.err = resp.Error - return false - } - - c.pageInfo = &resp.apiPaged - c.page = resp.Consumers - c.offset += len(c.page) - return true -} - -// Page returns the current ConsumerInfo page. -func (c *consumerNamesLister) Page() []string { - return c.page -} - -// Err returns any errors found while fetching pages. -func (c *consumerNamesLister) Err() error { - return c.err -} - -// ConsumerNames is used to retrieve a list of Consumer names. -func (jsc *js) ConsumerNames(stream string, opts ...JSOpt) <-chan string { - o, cancel, err := getJSContextOpts(jsc.opts, opts...) - if err != nil { - return nil - } - - ch := make(chan string) - l := &consumerNamesLister{stream: stream, js: &js{nc: jsc.nc, opts: o}} - go func() { - if cancel != nil { - defer cancel() - } - defer close(ch) - for l.Next() { - for _, info := range l.Page() { - select { - case ch <- info: - case <-o.ctx.Done(): - return - } - } - } - }() - - return ch -} - -// streamCreateResponse stream creation. -type streamCreateResponse struct { - apiResponse - *StreamInfo -} - -func (js *js) AddStream(cfg *StreamConfig, opts ...JSOpt) (*StreamInfo, error) { - if cfg == nil { - return nil, ErrStreamConfigRequired - } - if err := checkStreamName(cfg.Name); err != nil { - return nil, err - } - o, cancel, err := getJSContextOpts(js.opts, opts...) - if err != nil { - return nil, err - } - if cancel != nil { - defer cancel() - } - - // In case we need to change anything, copy so we do not change the caller's version. - ncfg := *cfg - - // If we have a mirror and an external domain, convert to ext.APIPrefix. - if cfg.Mirror != nil && cfg.Mirror.Domain != _EMPTY_ { - // Copy so we do not change the caller's version. - ncfg.Mirror = ncfg.Mirror.copy() - if err := ncfg.Mirror.convertDomain(); err != nil { - return nil, err - } - } - // Check sources for the same. - if len(ncfg.Sources) > 0 { - ncfg.Sources = append([]*StreamSource(nil), ncfg.Sources...) - for i, ss := range ncfg.Sources { - if ss.Domain != _EMPTY_ { - ncfg.Sources[i] = ss.copy() - if err := ncfg.Sources[i].convertDomain(); err != nil { - return nil, err - } - } - } - } - - req, err := json.Marshal(&ncfg) - if err != nil { - return nil, err - } - - csSubj := js.apiSubj(fmt.Sprintf(apiStreamCreateT, cfg.Name)) - r, err := js.apiRequestWithContext(o.ctx, csSubj, req) - if err != nil { - return nil, err - } - var resp streamCreateResponse - if err := json.Unmarshal(r.Data, &resp); err != nil { - return nil, err - } - if resp.Error != nil { - if errors.Is(resp.Error, ErrStreamNameAlreadyInUse) { - return nil, ErrStreamNameAlreadyInUse - } - return nil, resp.Error - } - - // check that input subject transform (if used) is reflected in the returned ConsumerInfo - if cfg.SubjectTransform != nil && resp.StreamInfo.Config.SubjectTransform == nil { - return nil, ErrStreamSubjectTransformNotSupported - } - if len(cfg.Sources) != 0 { - if len(cfg.Sources) != len(resp.Config.Sources) { - return nil, ErrStreamSourceNotSupported - } - for i := range cfg.Sources { - if len(cfg.Sources[i].SubjectTransforms) != 0 && len(resp.Sources[i].SubjectTransforms) == 0 { - return nil, ErrStreamSourceMultipleSubjectTransformsNotSupported - } - } - } - - return resp.StreamInfo, nil -} - -type ( - // StreamInfoRequest contains additional option to return - StreamInfoRequest struct { - apiPagedRequest - // DeletedDetails when true includes information about deleted messages - DeletedDetails bool `json:"deleted_details,omitempty"` - // SubjectsFilter when set, returns information on the matched subjects - SubjectsFilter string `json:"subjects_filter,omitempty"` - } - streamInfoResponse = struct { - apiResponse - apiPaged - *StreamInfo - } -) - -func (js *js) StreamInfo(stream string, opts ...JSOpt) (*StreamInfo, error) { - if err := checkStreamName(stream); err != nil { - return nil, err - } - o, cancel, err := getJSContextOpts(js.opts, opts...) - if err != nil { - return nil, err - } - if cancel != nil { - defer cancel() - } - - var i int - var subjectMessagesMap map[string]uint64 - var req []byte - var requestPayload bool - - var siOpts StreamInfoRequest - if o.streamInfoOpts != nil { - requestPayload = true - siOpts = *o.streamInfoOpts - } - - for { - if requestPayload { - siOpts.Offset = i - if req, err = json.Marshal(&siOpts); err != nil { - return nil, err - } - } - - siSubj := js.apiSubj(fmt.Sprintf(apiStreamInfoT, stream)) - - r, err := js.apiRequestWithContext(o.ctx, siSubj, req) - if err != nil { - return nil, err - } - - var resp streamInfoResponse - if err := json.Unmarshal(r.Data, &resp); err != nil { - return nil, err - } - - if resp.Error != nil { - if errors.Is(resp.Error, ErrStreamNotFound) { - return nil, ErrStreamNotFound - } - return nil, resp.Error - } - - var total int - // for backwards compatibility - if resp.Total != 0 { - total = resp.Total - } else { - total = len(resp.State.Subjects) - } - - if requestPayload && len(resp.StreamInfo.State.Subjects) > 0 { - if subjectMessagesMap == nil { - subjectMessagesMap = make(map[string]uint64, total) - } - - for k, j := range resp.State.Subjects { - subjectMessagesMap[k] = j - i++ - } - } - - if i >= total { - if requestPayload { - resp.StreamInfo.State.Subjects = subjectMessagesMap - } - return resp.StreamInfo, nil - } - } -} - -// StreamInfo shows config and current state for this stream. -type StreamInfo struct { - Config StreamConfig `json:"config"` - Created time.Time `json:"created"` - State StreamState `json:"state"` - Cluster *ClusterInfo `json:"cluster,omitempty"` - Mirror *StreamSourceInfo `json:"mirror,omitempty"` - Sources []*StreamSourceInfo `json:"sources,omitempty"` - Alternates []*StreamAlternate `json:"alternates,omitempty"` -} - -// StreamAlternate is an alternate stream represented by a mirror. -type StreamAlternate struct { - Name string `json:"name"` - Domain string `json:"domain,omitempty"` - Cluster string `json:"cluster"` -} - -// StreamSourceInfo shows information about an upstream stream source. -type StreamSourceInfo struct { - Name string `json:"name"` - Lag uint64 `json:"lag"` - Active time.Duration `json:"active"` - External *ExternalStream `json:"external"` - Error *APIError `json:"error"` - FilterSubject string `json:"filter_subject,omitempty"` - SubjectTransforms []SubjectTransformConfig `json:"subject_transforms,omitempty"` -} - -// StreamState is information about the given stream. -type StreamState struct { - Msgs uint64 `json:"messages"` - Bytes uint64 `json:"bytes"` - FirstSeq uint64 `json:"first_seq"` - FirstTime time.Time `json:"first_ts"` - LastSeq uint64 `json:"last_seq"` - LastTime time.Time `json:"last_ts"` - Consumers int `json:"consumer_count"` - Deleted []uint64 `json:"deleted"` - NumDeleted int `json:"num_deleted"` - NumSubjects uint64 `json:"num_subjects"` - Subjects map[string]uint64 `json:"subjects"` -} - -// ClusterInfo shows information about the underlying set of servers -// that make up the stream or consumer. -type ClusterInfo struct { - Name string `json:"name,omitempty"` - Leader string `json:"leader,omitempty"` - Replicas []*PeerInfo `json:"replicas,omitempty"` -} - -// PeerInfo shows information about all the peers in the cluster that -// are supporting the stream or consumer. -type PeerInfo struct { - Name string `json:"name"` - Current bool `json:"current"` - Offline bool `json:"offline,omitempty"` - Active time.Duration `json:"active"` - Lag uint64 `json:"lag,omitempty"` -} - -// UpdateStream updates a Stream. -func (js *js) UpdateStream(cfg *StreamConfig, opts ...JSOpt) (*StreamInfo, error) { - if cfg == nil { - return nil, ErrStreamConfigRequired - } - if err := checkStreamName(cfg.Name); err != nil { - return nil, err - } - o, cancel, err := getJSContextOpts(js.opts, opts...) - if err != nil { - return nil, err - } - if cancel != nil { - defer cancel() - } - - req, err := json.Marshal(cfg) - if err != nil { - return nil, err - } - - usSubj := js.apiSubj(fmt.Sprintf(apiStreamUpdateT, cfg.Name)) - r, err := js.apiRequestWithContext(o.ctx, usSubj, req) - if err != nil { - return nil, err - } - var resp streamInfoResponse - if err := json.Unmarshal(r.Data, &resp); err != nil { - return nil, err - } - if resp.Error != nil { - if errors.Is(resp.Error, ErrStreamNotFound) { - return nil, ErrStreamNotFound - } - return nil, resp.Error - } - - // check that input subject transform (if used) is reflected in the returned StreamInfo - if cfg.SubjectTransform != nil && resp.StreamInfo.Config.SubjectTransform == nil { - return nil, ErrStreamSubjectTransformNotSupported - } - - if len(cfg.Sources) != 0 { - if len(cfg.Sources) != len(resp.Config.Sources) { - return nil, ErrStreamSourceNotSupported - } - for i := range cfg.Sources { - if len(cfg.Sources[i].SubjectTransforms) != 0 && len(resp.Sources[i].SubjectTransforms) == 0 { - return nil, ErrStreamSourceMultipleSubjectTransformsNotSupported - } - } - } - - return resp.StreamInfo, nil -} - -// streamDeleteResponse is the response for a Stream delete request. -type streamDeleteResponse struct { - apiResponse - Success bool `json:"success,omitempty"` -} - -// DeleteStream deletes a Stream. -func (js *js) DeleteStream(name string, opts ...JSOpt) error { - if err := checkStreamName(name); err != nil { - return err - } - o, cancel, err := getJSContextOpts(js.opts, opts...) - if err != nil { - return err - } - if cancel != nil { - defer cancel() - } - - dsSubj := js.apiSubj(fmt.Sprintf(apiStreamDeleteT, name)) - r, err := js.apiRequestWithContext(o.ctx, dsSubj, nil) - if err != nil { - return err - } - var resp streamDeleteResponse - if err := json.Unmarshal(r.Data, &resp); err != nil { - return err - } - - if resp.Error != nil { - if errors.Is(resp.Error, ErrStreamNotFound) { - return ErrStreamNotFound - } - return resp.Error - } - return nil -} - -type apiMsgGetRequest struct { - Seq uint64 `json:"seq,omitempty"` - LastFor string `json:"last_by_subj,omitempty"` - NextFor string `json:"next_by_subj,omitempty"` -} - -// RawStreamMsg is a raw message stored in JetStream. -type RawStreamMsg struct { - Subject string - Sequence uint64 - Header Header - Data []byte - Time time.Time -} - -// storedMsg is a raw message stored in JetStream. -type storedMsg struct { - Subject string `json:"subject"` - Sequence uint64 `json:"seq"` - Header []byte `json:"hdrs,omitempty"` - Data []byte `json:"data,omitempty"` - Time time.Time `json:"time"` -} - -// apiMsgGetResponse is the response for a Stream get request. -type apiMsgGetResponse struct { - apiResponse - Message *storedMsg `json:"message,omitempty"` -} - -// GetLastMsg retrieves the last raw stream message stored in JetStream by subject. -func (js *js) GetLastMsg(name, subject string, opts ...JSOpt) (*RawStreamMsg, error) { - return js.getMsg(name, &apiMsgGetRequest{LastFor: subject}, opts...) -} - -// GetMsg retrieves a raw stream message stored in JetStream by sequence number. -func (js *js) GetMsg(name string, seq uint64, opts ...JSOpt) (*RawStreamMsg, error) { - return js.getMsg(name, &apiMsgGetRequest{Seq: seq}, opts...) -} - -// Low level getMsg -func (js *js) getMsg(name string, mreq *apiMsgGetRequest, opts ...JSOpt) (*RawStreamMsg, error) { - o, cancel, err := getJSContextOpts(js.opts, opts...) - if err != nil { - return nil, err - } - if cancel != nil { - defer cancel() - } - - if err := checkStreamName(name); err != nil { - return nil, err - } - - var apiSubj string - if o.directGet && mreq.LastFor != _EMPTY_ { - apiSubj = apiDirectMsgGetLastBySubjectT - dsSubj := js.apiSubj(fmt.Sprintf(apiSubj, name, mreq.LastFor)) - r, err := js.apiRequestWithContext(o.ctx, dsSubj, nil) - if err != nil { - return nil, err - } - return convertDirectGetMsgResponseToMsg(name, r) - } - - if o.directGet { - apiSubj = apiDirectMsgGetT - mreq.NextFor = o.directNextFor - } else { - apiSubj = apiMsgGetT - } - - req, err := json.Marshal(mreq) - if err != nil { - return nil, err - } - - dsSubj := js.apiSubj(fmt.Sprintf(apiSubj, name)) - r, err := js.apiRequestWithContext(o.ctx, dsSubj, req) - if err != nil { - return nil, err - } - - if o.directGet { - return convertDirectGetMsgResponseToMsg(name, r) - } - - var resp apiMsgGetResponse - if err := json.Unmarshal(r.Data, &resp); err != nil { - return nil, err - } - if resp.Error != nil { - if errors.Is(resp.Error, ErrMsgNotFound) { - return nil, ErrMsgNotFound - } - if errors.Is(resp.Error, ErrStreamNotFound) { - return nil, ErrStreamNotFound - } - return nil, resp.Error - } - - msg := resp.Message - - var hdr Header - if len(msg.Header) > 0 { - hdr, err = DecodeHeadersMsg(msg.Header) - if err != nil { - return nil, err - } - } - - return &RawStreamMsg{ - Subject: msg.Subject, - Sequence: msg.Sequence, - Header: hdr, - Data: msg.Data, - Time: msg.Time, - }, nil -} - -func convertDirectGetMsgResponseToMsg(name string, r *Msg) (*RawStreamMsg, error) { - // Check for 404/408. We would get a no-payload message and a "Status" header - if len(r.Data) == 0 { - val := r.Header.Get(statusHdr) - if val != _EMPTY_ { - switch val { - case noMessagesSts: - return nil, ErrMsgNotFound - default: - desc := r.Header.Get(descrHdr) - if desc == _EMPTY_ { - desc = "unable to get message" - } - return nil, fmt.Errorf("nats: %s", desc) - } - } - } - // Check for headers that give us the required information to - // reconstruct the message. - if len(r.Header) == 0 { - return nil, fmt.Errorf("nats: response should have headers") - } - stream := r.Header.Get(JSStream) - if stream == _EMPTY_ { - return nil, fmt.Errorf("nats: missing stream header") - } - - // Mirrors can now answer direct gets, so removing check for name equality. - // TODO(dlc) - We could have server also have a header with origin and check that? - - seqStr := r.Header.Get(JSSequence) - if seqStr == _EMPTY_ { - return nil, fmt.Errorf("nats: missing sequence header") - } - seq, err := strconv.ParseUint(seqStr, 10, 64) - if err != nil { - return nil, fmt.Errorf("nats: invalid sequence header '%s': %v", seqStr, err) - } - timeStr := r.Header.Get(JSTimeStamp) - if timeStr == _EMPTY_ { - return nil, fmt.Errorf("nats: missing timestamp header") - } - // Temporary code: the server in main branch is sending with format - // "2006-01-02 15:04:05.999999999 +0000 UTC", but will be changed - // to use format RFC3339Nano. Because of server test deps/cycle, - // support both until the server PR lands. - tm, err := time.Parse(time.RFC3339Nano, timeStr) - if err != nil { - tm, err = time.Parse("2006-01-02 15:04:05.999999999 +0000 UTC", timeStr) - if err != nil { - return nil, fmt.Errorf("nats: invalid timestamp header '%s': %v", timeStr, err) - } - } - subj := r.Header.Get(JSSubject) - if subj == _EMPTY_ { - return nil, fmt.Errorf("nats: missing subject header") - } - return &RawStreamMsg{ - Subject: subj, - Sequence: seq, - Header: r.Header, - Data: r.Data, - Time: tm, - }, nil -} - -type msgDeleteRequest struct { - Seq uint64 `json:"seq"` - NoErase bool `json:"no_erase,omitempty"` -} - -// msgDeleteResponse is the response for a Stream delete request. -type msgDeleteResponse struct { - apiResponse - Success bool `json:"success,omitempty"` -} - -// DeleteMsg deletes a message from a stream. -// The message is marked as erased, but not overwritten -func (js *js) DeleteMsg(name string, seq uint64, opts ...JSOpt) error { - o, cancel, err := getJSContextOpts(js.opts, opts...) - if err != nil { - return err - } - if cancel != nil { - defer cancel() - } - - return js.deleteMsg(o.ctx, name, &msgDeleteRequest{Seq: seq, NoErase: true}) -} - -// SecureDeleteMsg deletes a message from a stream. The deleted message is overwritten with random data -// As a result, this operation is slower than DeleteMsg() -func (js *js) SecureDeleteMsg(name string, seq uint64, opts ...JSOpt) error { - o, cancel, err := getJSContextOpts(js.opts, opts...) - if err != nil { - return err - } - if cancel != nil { - defer cancel() - } - - return js.deleteMsg(o.ctx, name, &msgDeleteRequest{Seq: seq}) -} - -func (js *js) deleteMsg(ctx context.Context, stream string, req *msgDeleteRequest) error { - if err := checkStreamName(stream); err != nil { - return err - } - reqJSON, err := json.Marshal(req) - if err != nil { - return err - } - - dsSubj := js.apiSubj(fmt.Sprintf(apiMsgDeleteT, stream)) - r, err := js.apiRequestWithContext(ctx, dsSubj, reqJSON) - if err != nil { - return err - } - var resp msgDeleteResponse - if err := json.Unmarshal(r.Data, &resp); err != nil { - return err - } - if resp.Error != nil { - return resp.Error - } - return nil -} - -// StreamPurgeRequest is optional request information to the purge API. -type StreamPurgeRequest struct { - // Purge up to but not including sequence. - Sequence uint64 `json:"seq,omitempty"` - // Subject to match against messages for the purge command. - Subject string `json:"filter,omitempty"` - // Number of messages to keep. - Keep uint64 `json:"keep,omitempty"` -} - -type streamPurgeResponse struct { - apiResponse - Success bool `json:"success,omitempty"` - Purged uint64 `json:"purged"` -} - -// PurgeStream purges messages on a Stream. -func (js *js) PurgeStream(stream string, opts ...JSOpt) error { - if err := checkStreamName(stream); err != nil { - return err - } - var req *StreamPurgeRequest - var ok bool - for _, opt := range opts { - // For PurgeStream, only request body opt is relevant - if req, ok = opt.(*StreamPurgeRequest); ok { - break - } - } - return js.purgeStream(stream, req) -} - -func (js *js) purgeStream(stream string, req *StreamPurgeRequest, opts ...JSOpt) error { - o, cancel, err := getJSContextOpts(js.opts, opts...) - if err != nil { - return err - } - if cancel != nil { - defer cancel() - } - - var b []byte - if req != nil { - if b, err = json.Marshal(req); err != nil { - return err - } - } - - psSubj := js.apiSubj(fmt.Sprintf(apiStreamPurgeT, stream)) - r, err := js.apiRequestWithContext(o.ctx, psSubj, b) - if err != nil { - return err - } - var resp streamPurgeResponse - if err := json.Unmarshal(r.Data, &resp); err != nil { - return err - } - if resp.Error != nil { - if errors.Is(resp.Error, ErrBadRequest) { - return fmt.Errorf("%w: %s", ErrBadRequest, "invalid purge request body") - } - return resp.Error - } - return nil -} - -// streamLister fetches pages of StreamInfo objects. This object is not safe -// to use for multiple threads. -type streamLister struct { - js *js - page []*StreamInfo - err error - - offset int - pageInfo *apiPaged -} - -// streamListResponse list of detailed stream information. -// A nil request is valid and means all streams. -type streamListResponse struct { - apiResponse - apiPaged - Streams []*StreamInfo `json:"streams"` -} - -// streamNamesRequest is used for Stream Name requests. -type streamNamesRequest struct { - apiPagedRequest - // These are filters that can be applied to the list. - Subject string `json:"subject,omitempty"` -} - -// Next fetches the next StreamInfo page. -func (s *streamLister) Next() bool { - if s.err != nil { - return false - } - if s.pageInfo != nil && s.offset >= s.pageInfo.Total { - return false - } - - req, err := json.Marshal(streamNamesRequest{ - apiPagedRequest: apiPagedRequest{Offset: s.offset}, - Subject: s.js.opts.streamListSubject, - }) - if err != nil { - s.err = err - return false - } - - var cancel context.CancelFunc - ctx := s.js.opts.ctx - if ctx == nil { - ctx, cancel = context.WithTimeout(context.Background(), s.js.opts.wait) - defer cancel() - } - - slSubj := s.js.apiSubj(apiStreamListT) - r, err := s.js.apiRequestWithContext(ctx, slSubj, req) - if err != nil { - s.err = err - return false - } - var resp streamListResponse - if err := json.Unmarshal(r.Data, &resp); err != nil { - s.err = err - return false - } - if resp.Error != nil { - s.err = resp.Error - return false - } - - s.pageInfo = &resp.apiPaged - s.page = resp.Streams - s.offset += len(s.page) - return true -} - -// Page returns the current StreamInfo page. -func (s *streamLister) Page() []*StreamInfo { - return s.page -} - -// Err returns any errors found while fetching pages. -func (s *streamLister) Err() error { - return s.err -} - -// Streams can be used to retrieve a list of StreamInfo objects. -func (jsc *js) Streams(opts ...JSOpt) <-chan *StreamInfo { - o, cancel, err := getJSContextOpts(jsc.opts, opts...) - if err != nil { - return nil - } - - ch := make(chan *StreamInfo) - l := &streamLister{js: &js{nc: jsc.nc, opts: o}} - go func() { - if cancel != nil { - defer cancel() - } - defer close(ch) - for l.Next() { - for _, info := range l.Page() { - select { - case ch <- info: - case <-o.ctx.Done(): - return - } - } - } - }() - - return ch -} - -// StreamsInfo can be used to retrieve a list of StreamInfo objects. -// DEPRECATED: Use Streams() instead. -func (jsc *js) StreamsInfo(opts ...JSOpt) <-chan *StreamInfo { - return jsc.Streams(opts...) -} - -type streamNamesLister struct { - js *js - - err error - offset int - page []string - pageInfo *apiPaged -} - -// Next fetches the next stream names page. -func (l *streamNamesLister) Next() bool { - if l.err != nil { - return false - } - if l.pageInfo != nil && l.offset >= l.pageInfo.Total { - return false - } - - var cancel context.CancelFunc - ctx := l.js.opts.ctx - if ctx == nil { - ctx, cancel = context.WithTimeout(context.Background(), l.js.opts.wait) - defer cancel() - } - - req, err := json.Marshal(streamNamesRequest{ - apiPagedRequest: apiPagedRequest{Offset: l.offset}, - Subject: l.js.opts.streamListSubject, - }) - if err != nil { - l.err = err - return false - } - r, err := l.js.apiRequestWithContext(ctx, l.js.apiSubj(apiStreams), req) - if err != nil { - l.err = err - return false - } - var resp streamNamesResponse - if err := json.Unmarshal(r.Data, &resp); err != nil { - l.err = err - return false - } - if resp.Error != nil { - l.err = resp.Error - return false - } - - l.pageInfo = &resp.apiPaged - l.page = resp.Streams - l.offset += len(l.page) - return true -} - -// Page returns the current ConsumerInfo page. -func (l *streamNamesLister) Page() []string { - return l.page -} - -// Err returns any errors found while fetching pages. -func (l *streamNamesLister) Err() error { - return l.err -} - -// StreamNames is used to retrieve a list of Stream names. -func (jsc *js) StreamNames(opts ...JSOpt) <-chan string { - o, cancel, err := getJSContextOpts(jsc.opts, opts...) - if err != nil { - return nil - } - - ch := make(chan string) - l := &streamNamesLister{js: &js{nc: jsc.nc, opts: o}} - go func() { - if cancel != nil { - defer cancel() - } - defer close(ch) - for l.Next() { - for _, info := range l.Page() { - select { - case ch <- info: - case <-o.ctx.Done(): - return - } - } - } - }() - - return ch -} - -// StreamNameBySubject returns a stream name that matches the subject. -func (jsc *js) StreamNameBySubject(subj string, opts ...JSOpt) (string, error) { - o, cancel, err := getJSContextOpts(jsc.opts, opts...) - if err != nil { - return "", err - } - if cancel != nil { - defer cancel() - } - - var slr streamNamesResponse - req := &streamRequest{subj} - j, err := json.Marshal(req) - if err != nil { - return _EMPTY_, err - } - - resp, err := jsc.apiRequestWithContext(o.ctx, jsc.apiSubj(apiStreams), j) - if err != nil { - if errors.Is(err, ErrNoResponders) { - err = ErrJetStreamNotEnabled - } - return _EMPTY_, err - } - if err := json.Unmarshal(resp.Data, &slr); err != nil { - return _EMPTY_, err - } - - if slr.Error != nil || len(slr.Streams) != 1 { - return _EMPTY_, ErrNoMatchingStream - } - return slr.Streams[0], nil -} - -func getJSContextOpts(defs *jsOpts, opts ...JSOpt) (*jsOpts, context.CancelFunc, error) { - var o jsOpts - for _, opt := range opts { - if err := opt.configureJSContext(&o); err != nil { - return nil, nil, err - } - } - - // Check for option collisions. Right now just timeout and context. - if o.ctx != nil && o.wait != 0 { - return nil, nil, ErrContextAndTimeout - } - if o.wait == 0 && o.ctx == nil { - o.wait = defs.wait - } - var cancel context.CancelFunc - if o.ctx == nil && o.wait > 0 { - o.ctx, cancel = context.WithTimeout(context.Background(), o.wait) - } - if o.pre == _EMPTY_ { - o.pre = defs.pre - } - - return &o, cancel, nil -} diff --git a/vendor/github.com/nats-io/nats.go/kv.go b/vendor/github.com/nats-io/nats.go/kv.go deleted file mode 100644 index 0864f30cc..000000000 --- a/vendor/github.com/nats-io/nats.go/kv.go +++ /dev/null @@ -1,1178 +0,0 @@ -// Copyright 2021-2023 The NATS 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 nats - -import ( - "context" - "errors" - "fmt" - "reflect" - "regexp" - "strconv" - "strings" - "sync" - "time" - - "github.com/nats-io/nats.go/internal/parser" -) - -// KeyValueManager is used to manage KeyValue stores. -type KeyValueManager interface { - // KeyValue will lookup and bind to an existing KeyValue store. - KeyValue(bucket string) (KeyValue, error) - // CreateKeyValue will create a KeyValue store with the following configuration. - CreateKeyValue(cfg *KeyValueConfig) (KeyValue, error) - // DeleteKeyValue will delete this KeyValue store (JetStream stream). - DeleteKeyValue(bucket string) error - // KeyValueStoreNames is used to retrieve a list of key value store names - KeyValueStoreNames() <-chan string - // KeyValueStores is used to retrieve a list of key value store statuses - KeyValueStores() <-chan KeyValueStatus -} - -// KeyValue contains methods to operate on a KeyValue store. -type KeyValue interface { - // Get returns the latest value for the key. - Get(key string) (entry KeyValueEntry, err error) - // GetRevision returns a specific revision value for the key. - GetRevision(key string, revision uint64) (entry KeyValueEntry, err error) - // Put will place the new value for the key into the store. - Put(key string, value []byte) (revision uint64, err error) - // PutString will place the string for the key into the store. - PutString(key string, value string) (revision uint64, err error) - // Create will add the key/value pair iff it does not exist. - Create(key string, value []byte) (revision uint64, err error) - // Update will update the value iff the latest revision matches. - Update(key string, value []byte, last uint64) (revision uint64, err error) - // Delete will place a delete marker and leave all revisions. - Delete(key string, opts ...DeleteOpt) error - // Purge will place a delete marker and remove all previous revisions. - Purge(key string, opts ...DeleteOpt) error - // Watch for any updates to keys that match the keys argument which could include wildcards. - // Watch will send a nil entry when it has received all initial values. - Watch(keys string, opts ...WatchOpt) (KeyWatcher, error) - // WatchAll will invoke the callback for all updates. - WatchAll(opts ...WatchOpt) (KeyWatcher, error) - // Keys will return all keys. - // DEPRECATED: Use ListKeys instead to avoid memory issues. - Keys(opts ...WatchOpt) ([]string, error) - // ListKeys will return all keys in a channel. - ListKeys(opts ...WatchOpt) (KeyLister, error) - // History will return all historical values for the key. - History(key string, opts ...WatchOpt) ([]KeyValueEntry, error) - // Bucket returns the current bucket name. - Bucket() string - // PurgeDeletes will remove all current delete markers. - PurgeDeletes(opts ...PurgeOpt) error - // Status retrieves the status and configuration of a bucket - Status() (KeyValueStatus, error) -} - -// KeyValueStatus is run-time status about a Key-Value bucket -type KeyValueStatus interface { - // Bucket the name of the bucket - Bucket() string - - // Values is how many messages are in the bucket, including historical values - Values() uint64 - - // History returns the configured history kept per key - History() int64 - - // TTL is how long the bucket keeps values for - TTL() time.Duration - - // BackingStore indicates what technology is used for storage of the bucket - BackingStore() string - - // Bytes returns the size in bytes of the bucket - Bytes() uint64 - - // IsCompressed indicates if the data is compressed on disk - IsCompressed() bool -} - -// KeyWatcher is what is returned when doing a watch. -type KeyWatcher interface { - // Context returns watcher context optionally provided by nats.Context option. - Context() context.Context - // Updates returns a channel to read any updates to entries. - Updates() <-chan KeyValueEntry - // Stop will stop this watcher. - Stop() error -} - -// KeyLister is used to retrieve a list of key value store keys -type KeyLister interface { - Keys() <-chan string - Stop() error -} - -type WatchOpt interface { - configureWatcher(opts *watchOpts) error -} - -// For nats.Context() support. -func (ctx ContextOpt) configureWatcher(opts *watchOpts) error { - opts.ctx = ctx - return nil -} - -type watchOpts struct { - ctx context.Context - // Do not send delete markers to the update channel. - ignoreDeletes bool - // Include all history per subject, not just last one. - includeHistory bool - // Include only updates for keys. - updatesOnly bool - // retrieve only the meta data of the entry - metaOnly bool -} - -type watchOptFn func(opts *watchOpts) error - -func (opt watchOptFn) configureWatcher(opts *watchOpts) error { - return opt(opts) -} - -// IncludeHistory instructs the key watcher to include historical values as well. -func IncludeHistory() WatchOpt { - return watchOptFn(func(opts *watchOpts) error { - if opts.updatesOnly { - return errors.New("nats: include history can not be used with updates only") - } - opts.includeHistory = true - return nil - }) -} - -// UpdatesOnly instructs the key watcher to only include updates on values (without latest values when started). -func UpdatesOnly() WatchOpt { - return watchOptFn(func(opts *watchOpts) error { - if opts.includeHistory { - return errors.New("nats: updates only can not be used with include history") - } - opts.updatesOnly = true - return nil - }) -} - -// IgnoreDeletes will have the key watcher not pass any deleted keys. -func IgnoreDeletes() WatchOpt { - return watchOptFn(func(opts *watchOpts) error { - opts.ignoreDeletes = true - return nil - }) -} - -// MetaOnly instructs the key watcher to retrieve only the entry meta data, not the entry value -func MetaOnly() WatchOpt { - return watchOptFn(func(opts *watchOpts) error { - opts.metaOnly = true - return nil - }) -} - -type PurgeOpt interface { - configurePurge(opts *purgeOpts) error -} - -type purgeOpts struct { - dmthr time.Duration // Delete markers threshold - ctx context.Context -} - -// DeleteMarkersOlderThan indicates that delete or purge markers older than that -// will be deleted as part of PurgeDeletes() operation, otherwise, only the data -// will be removed but markers that are recent will be kept. -// Note that if no option is specified, the default is 30 minutes. You can set -// this option to a negative value to instruct to always remove the markers, -// regardless of their age. -type DeleteMarkersOlderThan time.Duration - -func (ttl DeleteMarkersOlderThan) configurePurge(opts *purgeOpts) error { - opts.dmthr = time.Duration(ttl) - return nil -} - -// For nats.Context() support. -func (ctx ContextOpt) configurePurge(opts *purgeOpts) error { - opts.ctx = ctx - return nil -} - -type DeleteOpt interface { - configureDelete(opts *deleteOpts) error -} - -type deleteOpts struct { - // Remove all previous revisions. - purge bool - - // Delete only if the latest revision matches. - revision uint64 -} - -type deleteOptFn func(opts *deleteOpts) error - -func (opt deleteOptFn) configureDelete(opts *deleteOpts) error { - return opt(opts) -} - -// LastRevision deletes if the latest revision matches. -func LastRevision(revision uint64) DeleteOpt { - return deleteOptFn(func(opts *deleteOpts) error { - opts.revision = revision - return nil - }) -} - -// purge removes all previous revisions. -func purge() DeleteOpt { - return deleteOptFn(func(opts *deleteOpts) error { - opts.purge = true - return nil - }) -} - -// KeyValueConfig is for configuring a KeyValue store. -type KeyValueConfig struct { - Bucket string - Description string - MaxValueSize int32 - History uint8 - TTL time.Duration - MaxBytes int64 - Storage StorageType - Replicas int - Placement *Placement - RePublish *RePublish - Mirror *StreamSource - Sources []*StreamSource - - // Enable underlying stream compression. - // NOTE: Compression is supported for nats-server 2.10.0+ - Compression bool -} - -// Used to watch all keys. -const ( - KeyValueMaxHistory = 64 - AllKeys = ">" - kvLatestRevision = 0 - kvop = "KV-Operation" - kvdel = "DEL" - kvpurge = "PURGE" -) - -type KeyValueOp uint8 - -const ( - KeyValuePut KeyValueOp = iota - KeyValueDelete - KeyValuePurge -) - -func (op KeyValueOp) String() string { - switch op { - case KeyValuePut: - return "KeyValuePutOp" - case KeyValueDelete: - return "KeyValueDeleteOp" - case KeyValuePurge: - return "KeyValuePurgeOp" - default: - return "Unknown Operation" - } -} - -// KeyValueEntry is a retrieved entry for Get or List or Watch. -type KeyValueEntry interface { - // Bucket is the bucket the data was loaded from. - Bucket() string - // Key is the key that was retrieved. - Key() string - // Value is the retrieved value. - Value() []byte - // Revision is a unique sequence for this value. - Revision() uint64 - // Created is the time the data was put in the bucket. - Created() time.Time - // Delta is distance from the latest value. - Delta() uint64 - // Operation returns Put or Delete or Purge. - Operation() KeyValueOp -} - -// Errors -var ( - ErrKeyValueConfigRequired = errors.New("nats: config required") - ErrInvalidBucketName = errors.New("nats: invalid bucket name") - ErrInvalidKey = errors.New("nats: invalid key") - ErrBucketNotFound = errors.New("nats: bucket not found") - ErrBadBucket = errors.New("nats: bucket not valid key-value store") - ErrKeyNotFound = errors.New("nats: key not found") - ErrKeyDeleted = errors.New("nats: key was deleted") - ErrHistoryToLarge = errors.New("nats: history limited to a max of 64") - ErrNoKeysFound = errors.New("nats: no keys found") -) - -var ( - ErrKeyExists JetStreamError = &jsError{apiErr: &APIError{ErrorCode: JSErrCodeStreamWrongLastSequence, Code: 400}, message: "key exists"} -) - -const ( - kvBucketNamePre = "KV_" - kvBucketNameTmpl = "KV_%s" - kvSubjectsTmpl = "$KV.%s.>" - kvSubjectsPreTmpl = "$KV.%s." - kvSubjectsPreDomainTmpl = "%s.$KV.%s." - kvNoPending = "0" -) - -// Regex for valid keys and buckets. -var ( - validBucketRe = regexp.MustCompile(`\A[a-zA-Z0-9_-]+\z`) - validKeyRe = regexp.MustCompile(`\A[-/_=\.a-zA-Z0-9]+\z`) -) - -// KeyValue will lookup and bind to an existing KeyValue store. -func (js *js) KeyValue(bucket string) (KeyValue, error) { - if !js.nc.serverMinVersion(2, 6, 2) { - return nil, errors.New("nats: key-value requires at least server version 2.6.2") - } - if !validBucketRe.MatchString(bucket) { - return nil, ErrInvalidBucketName - } - stream := fmt.Sprintf(kvBucketNameTmpl, bucket) - si, err := js.StreamInfo(stream) - if err != nil { - if errors.Is(err, ErrStreamNotFound) { - err = ErrBucketNotFound - } - return nil, err - } - // Do some quick sanity checks that this is a correctly formed stream for KV. - // Max msgs per subject should be > 0. - if si.Config.MaxMsgsPerSubject < 1 { - return nil, ErrBadBucket - } - - return mapStreamToKVS(js, si), nil -} - -// CreateKeyValue will create a KeyValue store with the following configuration. -func (js *js) CreateKeyValue(cfg *KeyValueConfig) (KeyValue, error) { - if !js.nc.serverMinVersion(2, 6, 2) { - return nil, errors.New("nats: key-value requires at least server version 2.6.2") - } - if cfg == nil { - return nil, ErrKeyValueConfigRequired - } - if !validBucketRe.MatchString(cfg.Bucket) { - return nil, ErrInvalidBucketName - } - if _, err := js.AccountInfo(); err != nil { - return nil, err - } - - // Default to 1 for history. Max is 64 for now. - history := int64(1) - if cfg.History > 0 { - if cfg.History > KeyValueMaxHistory { - return nil, ErrHistoryToLarge - } - history = int64(cfg.History) - } - - replicas := cfg.Replicas - if replicas == 0 { - replicas = 1 - } - - // We will set explicitly some values so that we can do comparison - // if we get an "already in use" error and need to check if it is same. - maxBytes := cfg.MaxBytes - if maxBytes == 0 { - maxBytes = -1 - } - maxMsgSize := cfg.MaxValueSize - if maxMsgSize == 0 { - maxMsgSize = -1 - } - // When stream's MaxAge is not set, server uses 2 minutes as the default - // for the duplicate window. If MaxAge is set, and lower than 2 minutes, - // then the duplicate window will be set to that. If MaxAge is greater, - // we will cap the duplicate window to 2 minutes (to be consistent with - // previous behavior). - duplicateWindow := 2 * time.Minute - if cfg.TTL > 0 && cfg.TTL < duplicateWindow { - duplicateWindow = cfg.TTL - } - var compression StoreCompression - if cfg.Compression { - compression = S2Compression - } - scfg := &StreamConfig{ - Name: fmt.Sprintf(kvBucketNameTmpl, cfg.Bucket), - Description: cfg.Description, - MaxMsgsPerSubject: history, - MaxBytes: maxBytes, - MaxAge: cfg.TTL, - MaxMsgSize: maxMsgSize, - Storage: cfg.Storage, - Replicas: replicas, - Placement: cfg.Placement, - AllowRollup: true, - DenyDelete: true, - Duplicates: duplicateWindow, - MaxMsgs: -1, - MaxConsumers: -1, - AllowDirect: true, - RePublish: cfg.RePublish, - Compression: compression, - } - if cfg.Mirror != nil { - // Copy in case we need to make changes so we do not change caller's version. - m := cfg.Mirror.copy() - if !strings.HasPrefix(m.Name, kvBucketNamePre) { - m.Name = fmt.Sprintf(kvBucketNameTmpl, m.Name) - } - scfg.Mirror = m - scfg.MirrorDirect = true - } else if len(cfg.Sources) > 0 { - for _, ss := range cfg.Sources { - var sourceBucketName string - if strings.HasPrefix(ss.Name, kvBucketNamePre) { - sourceBucketName = ss.Name[len(kvBucketNamePre):] - } else { - sourceBucketName = ss.Name - ss.Name = fmt.Sprintf(kvBucketNameTmpl, ss.Name) - } - - if ss.External == nil || sourceBucketName != cfg.Bucket { - ss.SubjectTransforms = []SubjectTransformConfig{{Source: fmt.Sprintf(kvSubjectsTmpl, sourceBucketName), Destination: fmt.Sprintf(kvSubjectsTmpl, cfg.Bucket)}} - } - scfg.Sources = append(scfg.Sources, ss) - } - scfg.Subjects = []string{fmt.Sprintf(kvSubjectsTmpl, cfg.Bucket)} - } else { - scfg.Subjects = []string{fmt.Sprintf(kvSubjectsTmpl, cfg.Bucket)} - } - - // If we are at server version 2.7.2 or above use DiscardNew. We can not use DiscardNew for 2.7.1 or below. - if js.nc.serverMinVersion(2, 7, 2) { - scfg.Discard = DiscardNew - } - - si, err := js.AddStream(scfg) - if err != nil { - // If we have a failure to add, it could be because we have - // a config change if the KV was created against a pre 2.7.2 - // and we are now moving to a v2.7.2+. If that is the case - // and the only difference is the discard policy, then update - // the stream. - // The same logic applies for KVs created pre 2.9.x and - // the AllowDirect setting. - if errors.Is(err, ErrStreamNameAlreadyInUse) { - if si, _ = js.StreamInfo(scfg.Name); si != nil { - // To compare, make the server's stream info discard - // policy same than ours. - si.Config.Discard = scfg.Discard - // Also need to set allow direct for v2.9.x+ - si.Config.AllowDirect = scfg.AllowDirect - if reflect.DeepEqual(&si.Config, scfg) { - si, err = js.UpdateStream(scfg) - } - } - } - if err != nil { - return nil, err - } - } - return mapStreamToKVS(js, si), nil -} - -// DeleteKeyValue will delete this KeyValue store (JetStream stream). -func (js *js) DeleteKeyValue(bucket string) error { - if !validBucketRe.MatchString(bucket) { - return ErrInvalidBucketName - } - stream := fmt.Sprintf(kvBucketNameTmpl, bucket) - return js.DeleteStream(stream) -} - -type kvs struct { - name string - stream string - pre string - putPre string - js *js - // If true, it means that APIPrefix/Domain was set in the context - // and we need to add something to some of our high level protocols - // (such as Put, etc..) - useJSPfx bool - // To know if we can use the stream direct get API - useDirect bool -} - -// Underlying entry. -type kve struct { - bucket string - key string - value []byte - revision uint64 - delta uint64 - created time.Time - op KeyValueOp -} - -func (e *kve) Bucket() string { return e.bucket } -func (e *kve) Key() string { return e.key } -func (e *kve) Value() []byte { return e.value } -func (e *kve) Revision() uint64 { return e.revision } -func (e *kve) Created() time.Time { return e.created } -func (e *kve) Delta() uint64 { return e.delta } -func (e *kve) Operation() KeyValueOp { return e.op } - -func keyValid(key string) bool { - if len(key) == 0 || key[0] == '.' || key[len(key)-1] == '.' { - return false - } - return validKeyRe.MatchString(key) -} - -// Get returns the latest value for the key. -func (kv *kvs) Get(key string) (KeyValueEntry, error) { - e, err := kv.get(key, kvLatestRevision) - if err != nil { - if errors.Is(err, ErrKeyDeleted) { - return nil, ErrKeyNotFound - } - return nil, err - } - - return e, nil -} - -// GetRevision returns a specific revision value for the key. -func (kv *kvs) GetRevision(key string, revision uint64) (KeyValueEntry, error) { - e, err := kv.get(key, revision) - if err != nil { - if errors.Is(err, ErrKeyDeleted) { - return nil, ErrKeyNotFound - } - return nil, err - } - - return e, nil -} - -func (kv *kvs) get(key string, revision uint64) (KeyValueEntry, error) { - if !keyValid(key) { - return nil, ErrInvalidKey - } - - var b strings.Builder - b.WriteString(kv.pre) - b.WriteString(key) - - var m *RawStreamMsg - var err error - var _opts [1]JSOpt - opts := _opts[:0] - if kv.useDirect { - opts = append(opts, DirectGet()) - } - - if revision == kvLatestRevision { - m, err = kv.js.GetLastMsg(kv.stream, b.String(), opts...) - } else { - m, err = kv.js.GetMsg(kv.stream, revision, opts...) - // If a sequence was provided, just make sure that the retrieved - // message subject matches the request. - if err == nil && m.Subject != b.String() { - return nil, ErrKeyNotFound - } - } - if err != nil { - if errors.Is(err, ErrMsgNotFound) { - err = ErrKeyNotFound - } - return nil, err - } - - entry := &kve{ - bucket: kv.name, - key: key, - value: m.Data, - revision: m.Sequence, - created: m.Time, - } - - // Double check here that this is not a DEL Operation marker. - if len(m.Header) > 0 { - switch m.Header.Get(kvop) { - case kvdel: - entry.op = KeyValueDelete - return entry, ErrKeyDeleted - case kvpurge: - entry.op = KeyValuePurge - return entry, ErrKeyDeleted - } - } - - return entry, nil -} - -// Put will place the new value for the key into the store. -func (kv *kvs) Put(key string, value []byte) (revision uint64, err error) { - if !keyValid(key) { - return 0, ErrInvalidKey - } - - var b strings.Builder - if kv.useJSPfx { - b.WriteString(kv.js.opts.pre) - } - if kv.putPre != _EMPTY_ { - b.WriteString(kv.putPre) - } else { - b.WriteString(kv.pre) - } - b.WriteString(key) - - pa, err := kv.js.Publish(b.String(), value) - if err != nil { - return 0, err - } - return pa.Sequence, err -} - -// PutString will place the string for the key into the store. -func (kv *kvs) PutString(key string, value string) (revision uint64, err error) { - return kv.Put(key, []byte(value)) -} - -// Create will add the key/value pair if it does not exist. -func (kv *kvs) Create(key string, value []byte) (revision uint64, err error) { - v, err := kv.Update(key, value, 0) - if err == nil { - return v, nil - } - - // TODO(dlc) - Since we have tombstones for DEL ops for watchers, this could be from that - // so we need to double check. - if e, err := kv.get(key, kvLatestRevision); errors.Is(err, ErrKeyDeleted) { - return kv.Update(key, value, e.Revision()) - } - - // Check if the expected last subject sequence is not zero which implies - // the key already exists. - if errors.Is(err, ErrKeyExists) { - jserr := ErrKeyExists.(*jsError) - return 0, fmt.Errorf("%w: %s", err, jserr.message) - } - - return 0, err -} - -// Update will update the value if the latest revision matches. -func (kv *kvs) Update(key string, value []byte, revision uint64) (uint64, error) { - if !keyValid(key) { - return 0, ErrInvalidKey - } - - var b strings.Builder - if kv.useJSPfx { - b.WriteString(kv.js.opts.pre) - } - b.WriteString(kv.pre) - b.WriteString(key) - - m := Msg{Subject: b.String(), Header: Header{}, Data: value} - m.Header.Set(ExpectedLastSubjSeqHdr, strconv.FormatUint(revision, 10)) - - pa, err := kv.js.PublishMsg(&m) - if err != nil { - return 0, err - } - return pa.Sequence, err -} - -// Delete will place a delete marker and leave all revisions. -func (kv *kvs) Delete(key string, opts ...DeleteOpt) error { - if !keyValid(key) { - return ErrInvalidKey - } - - var b strings.Builder - if kv.useJSPfx { - b.WriteString(kv.js.opts.pre) - } - if kv.putPre != _EMPTY_ { - b.WriteString(kv.putPre) - } else { - b.WriteString(kv.pre) - } - b.WriteString(key) - - // DEL op marker. For watch functionality. - m := NewMsg(b.String()) - - var o deleteOpts - for _, opt := range opts { - if opt != nil { - if err := opt.configureDelete(&o); err != nil { - return err - } - } - } - - if o.purge { - m.Header.Set(kvop, kvpurge) - m.Header.Set(MsgRollup, MsgRollupSubject) - } else { - m.Header.Set(kvop, kvdel) - } - - if o.revision != 0 { - m.Header.Set(ExpectedLastSubjSeqHdr, strconv.FormatUint(o.revision, 10)) - } - - _, err := kv.js.PublishMsg(m) - return err -} - -// Purge will remove the key and all revisions. -func (kv *kvs) Purge(key string, opts ...DeleteOpt) error { - return kv.Delete(key, append(opts, purge())...) -} - -const kvDefaultPurgeDeletesMarkerThreshold = 30 * time.Minute - -// PurgeDeletes will remove all current delete markers. -// This is a maintenance option if there is a larger buildup of delete markers. -// See DeleteMarkersOlderThan() option for more information. -func (kv *kvs) PurgeDeletes(opts ...PurgeOpt) error { - var o purgeOpts - for _, opt := range opts { - if opt != nil { - if err := opt.configurePurge(&o); err != nil { - return err - } - } - } - // Transfer possible context purge option to the watcher. This is the - // only option that matters for the PurgeDeletes() feature. - var wopts []WatchOpt - if o.ctx != nil { - wopts = append(wopts, Context(o.ctx)) - } - watcher, err := kv.WatchAll(wopts...) - if err != nil { - return err - } - defer watcher.Stop() - - var limit time.Time - olderThan := o.dmthr - // Negative value is used to instruct to always remove markers, regardless - // of age. If set to 0 (or not set), use our default value. - if olderThan == 0 { - olderThan = kvDefaultPurgeDeletesMarkerThreshold - } - if olderThan > 0 { - limit = time.Now().Add(-olderThan) - } - - var deleteMarkers []KeyValueEntry - for entry := range watcher.Updates() { - if entry == nil { - break - } - if op := entry.Operation(); op == KeyValueDelete || op == KeyValuePurge { - deleteMarkers = append(deleteMarkers, entry) - } - } - - var ( - pr StreamPurgeRequest - b strings.Builder - ) - // Do actual purges here. - for _, entry := range deleteMarkers { - b.WriteString(kv.pre) - b.WriteString(entry.Key()) - pr.Subject = b.String() - pr.Keep = 0 - if olderThan > 0 && entry.Created().After(limit) { - pr.Keep = 1 - } - if err := kv.js.purgeStream(kv.stream, &pr); err != nil { - return err - } - b.Reset() - } - return nil -} - -// Keys() will return all keys. -func (kv *kvs) Keys(opts ...WatchOpt) ([]string, error) { - opts = append(opts, IgnoreDeletes(), MetaOnly()) - watcher, err := kv.WatchAll(opts...) - if err != nil { - return nil, err - } - defer watcher.Stop() - - var keys []string - for entry := range watcher.Updates() { - if entry == nil { - break - } - keys = append(keys, entry.Key()) - } - if len(keys) == 0 { - return nil, ErrNoKeysFound - } - return keys, nil -} - -type keyLister struct { - watcher KeyWatcher - keys chan string -} - -// ListKeys will return all keys. -func (kv *kvs) ListKeys(opts ...WatchOpt) (KeyLister, error) { - opts = append(opts, IgnoreDeletes(), MetaOnly()) - watcher, err := kv.WatchAll(opts...) - if err != nil { - return nil, err - } - kl := &keyLister{watcher: watcher, keys: make(chan string, 256)} - - go func() { - defer close(kl.keys) - defer watcher.Stop() - for entry := range watcher.Updates() { - if entry == nil { - return - } - kl.keys <- entry.Key() - } - }() - return kl, nil -} - -func (kl *keyLister) Keys() <-chan string { - return kl.keys -} - -func (kl *keyLister) Stop() error { - return kl.watcher.Stop() -} - -// History will return all values for the key. -func (kv *kvs) History(key string, opts ...WatchOpt) ([]KeyValueEntry, error) { - opts = append(opts, IncludeHistory()) - watcher, err := kv.Watch(key, opts...) - if err != nil { - return nil, err - } - defer watcher.Stop() - - var entries []KeyValueEntry - for entry := range watcher.Updates() { - if entry == nil { - break - } - entries = append(entries, entry) - } - if len(entries) == 0 { - return nil, ErrKeyNotFound - } - return entries, nil -} - -// Implementation for Watch -type watcher struct { - mu sync.Mutex - updates chan KeyValueEntry - sub *Subscription - initDone bool - initPending uint64 - received uint64 - ctx context.Context -} - -// Context returns the context for the watcher if set. -func (w *watcher) Context() context.Context { - if w == nil { - return nil - } - return w.ctx -} - -// Updates returns the interior channel. -func (w *watcher) Updates() <-chan KeyValueEntry { - if w == nil { - return nil - } - return w.updates -} - -// Stop will unsubscribe from the watcher. -func (w *watcher) Stop() error { - if w == nil { - return nil - } - return w.sub.Unsubscribe() -} - -// WatchAll watches all keys. -func (kv *kvs) WatchAll(opts ...WatchOpt) (KeyWatcher, error) { - return kv.Watch(AllKeys, opts...) -} - -// Watch will fire the callback when a key that matches the keys pattern is updated. -// keys needs to be a valid NATS subject. -func (kv *kvs) Watch(keys string, opts ...WatchOpt) (KeyWatcher, error) { - var o watchOpts - for _, opt := range opts { - if opt != nil { - if err := opt.configureWatcher(&o); err != nil { - return nil, err - } - } - } - - // Could be a pattern so don't check for validity as we normally do. - var b strings.Builder - b.WriteString(kv.pre) - b.WriteString(keys) - keys = b.String() - - // We will block below on placing items on the chan. That is by design. - w := &watcher{updates: make(chan KeyValueEntry, 256), ctx: o.ctx} - - update := func(m *Msg) { - tokens, err := parser.GetMetadataFields(m.Reply) - if err != nil { - return - } - if len(m.Subject) <= len(kv.pre) { - return - } - subj := m.Subject[len(kv.pre):] - - var op KeyValueOp - if len(m.Header) > 0 { - switch m.Header.Get(kvop) { - case kvdel: - op = KeyValueDelete - case kvpurge: - op = KeyValuePurge - } - } - delta := parser.ParseNum(tokens[parser.AckNumPendingTokenPos]) - w.mu.Lock() - defer w.mu.Unlock() - if !o.ignoreDeletes || (op != KeyValueDelete && op != KeyValuePurge) { - entry := &kve{ - bucket: kv.name, - key: subj, - value: m.Data, - revision: parser.ParseNum(tokens[parser.AckStreamSeqTokenPos]), - created: time.Unix(0, int64(parser.ParseNum(tokens[parser.AckTimestampSeqTokenPos]))), - delta: delta, - op: op, - } - w.updates <- entry - } - // Check if done and initial values. - // Skip if UpdatesOnly() is set, since there will never be updates initially. - if !w.initDone { - w.received++ - // We set this on the first trip through.. - if w.initPending == 0 { - w.initPending = delta - } - if w.received > w.initPending || delta == 0 { - w.initDone = true - w.updates <- nil - } - } - } - - // Used ordered consumer to deliver results. - subOpts := []SubOpt{BindStream(kv.stream), OrderedConsumer()} - if !o.includeHistory { - subOpts = append(subOpts, DeliverLastPerSubject()) - } - if o.updatesOnly { - subOpts = append(subOpts, DeliverNew()) - } - if o.metaOnly { - subOpts = append(subOpts, HeadersOnly()) - } - if o.ctx != nil { - subOpts = append(subOpts, Context(o.ctx)) - } - // Create the sub and rest of initialization under the lock. - // We want to prevent the race between this code and the - // update() callback. - w.mu.Lock() - defer w.mu.Unlock() - sub, err := kv.js.Subscribe(keys, update, subOpts...) - if err != nil { - return nil, err - } - sub.mu.Lock() - // If there were no pending messages at the time of the creation - // of the consumer, send the marker. - // Skip if UpdatesOnly() is set, since there will never be updates initially. - if !o.updatesOnly { - if sub.jsi != nil && sub.jsi.pending == 0 { - w.initDone = true - w.updates <- nil - } - } else { - // if UpdatesOnly was used, mark initialization as complete - w.initDone = true - } - // Set us up to close when the waitForMessages func returns. - sub.pDone = func(_ string) { - close(w.updates) - } - sub.mu.Unlock() - - w.sub = sub - return w, nil -} - -// Bucket returns the current bucket name (JetStream stream). -func (kv *kvs) Bucket() string { - return kv.name -} - -// KeyValueBucketStatus represents status of a Bucket, implements KeyValueStatus -type KeyValueBucketStatus struct { - nfo *StreamInfo - bucket string -} - -// Bucket the name of the bucket -func (s *KeyValueBucketStatus) Bucket() string { return s.bucket } - -// Values is how many messages are in the bucket, including historical values -func (s *KeyValueBucketStatus) Values() uint64 { return s.nfo.State.Msgs } - -// History returns the configured history kept per key -func (s *KeyValueBucketStatus) History() int64 { return s.nfo.Config.MaxMsgsPerSubject } - -// TTL is how long the bucket keeps values for -func (s *KeyValueBucketStatus) TTL() time.Duration { return s.nfo.Config.MaxAge } - -// BackingStore indicates what technology is used for storage of the bucket -func (s *KeyValueBucketStatus) BackingStore() string { return "JetStream" } - -// StreamInfo is the stream info retrieved to create the status -func (s *KeyValueBucketStatus) StreamInfo() *StreamInfo { return s.nfo } - -// Bytes is the size of the stream -func (s *KeyValueBucketStatus) Bytes() uint64 { return s.nfo.State.Bytes } - -// IsCompressed indicates if the data is compressed on disk -func (s *KeyValueBucketStatus) IsCompressed() bool { return s.nfo.Config.Compression != NoCompression } - -// Status retrieves the status and configuration of a bucket -func (kv *kvs) Status() (KeyValueStatus, error) { - nfo, err := kv.js.StreamInfo(kv.stream) - if err != nil { - return nil, err - } - - return &KeyValueBucketStatus{nfo: nfo, bucket: kv.name}, nil -} - -// KeyValueStoreNames is used to retrieve a list of key value store names -func (js *js) KeyValueStoreNames() <-chan string { - ch := make(chan string) - l := &streamNamesLister{js: js} - l.js.opts.streamListSubject = fmt.Sprintf(kvSubjectsTmpl, "*") - go func() { - defer close(ch) - for l.Next() { - for _, name := range l.Page() { - if !strings.HasPrefix(name, kvBucketNamePre) { - continue - } - ch <- strings.TrimPrefix(name, kvBucketNamePre) - } - } - }() - - return ch -} - -// KeyValueStores is used to retrieve a list of key value store statuses -func (js *js) KeyValueStores() <-chan KeyValueStatus { - ch := make(chan KeyValueStatus) - l := &streamLister{js: js} - l.js.opts.streamListSubject = fmt.Sprintf(kvSubjectsTmpl, "*") - go func() { - defer close(ch) - for l.Next() { - for _, info := range l.Page() { - if !strings.HasPrefix(info.Config.Name, kvBucketNamePre) { - continue - } - ch <- &KeyValueBucketStatus{nfo: info, bucket: strings.TrimPrefix(info.Config.Name, kvBucketNamePre)} - } - } - }() - return ch -} - -func mapStreamToKVS(js *js, info *StreamInfo) *kvs { - bucket := strings.TrimPrefix(info.Config.Name, kvBucketNamePre) - - kv := &kvs{ - name: bucket, - stream: info.Config.Name, - pre: fmt.Sprintf(kvSubjectsPreTmpl, bucket), - js: js, - // Determine if we need to use the JS prefix in front of Put and Delete operations - useJSPfx: js.opts.pre != defaultAPIPrefix, - useDirect: info.Config.AllowDirect, - } - - // If we are mirroring, we will have mirror direct on, so just use the mirror name - // and override use - if m := info.Config.Mirror; m != nil { - bucket := strings.TrimPrefix(m.Name, kvBucketNamePre) - if m.External != nil && m.External.APIPrefix != _EMPTY_ { - kv.useJSPfx = false - kv.pre = fmt.Sprintf(kvSubjectsPreTmpl, bucket) - kv.putPre = fmt.Sprintf(kvSubjectsPreDomainTmpl, m.External.APIPrefix, bucket) - } else { - kv.putPre = fmt.Sprintf(kvSubjectsPreTmpl, bucket) - } - } - - return kv -} diff --git a/vendor/github.com/nats-io/nats.go/legacy_jetstream.md b/vendor/github.com/nats-io/nats.go/legacy_jetstream.md deleted file mode 100644 index 43e1c73b3..000000000 --- a/vendor/github.com/nats-io/nats.go/legacy_jetstream.md +++ /dev/null @@ -1,83 +0,0 @@ -# Legacy JetStream API - -This is a documentation for the legacy JetStream API. A README for the current -API can be found [here](jetstream/README.md) - -## JetStream Basic Usage - -```go -import "github.com/nats-io/nats.go" - -// Connect to NATS -nc, _ := nats.Connect(nats.DefaultURL) - -// Create JetStream Context -js, _ := nc.JetStream(nats.PublishAsyncMaxPending(256)) - -// Simple Stream Publisher -js.Publish("ORDERS.scratch", []byte("hello")) - -// Simple Async Stream Publisher -for i := 0; i < 500; i++ { - js.PublishAsync("ORDERS.scratch", []byte("hello")) -} -select { -case <-js.PublishAsyncComplete(): -case <-time.After(5 * time.Second): - fmt.Println("Did not resolve in time") -} - -// Simple Async Ephemeral Consumer -js.Subscribe("ORDERS.*", func(m *nats.Msg) { - fmt.Printf("Received a JetStream message: %s\n", string(m.Data)) -}) - -// Simple Sync Durable Consumer (optional SubOpts at the end) -sub, err := js.SubscribeSync("ORDERS.*", nats.Durable("MONITOR"), nats.MaxDeliver(3)) -m, err := sub.NextMsg(timeout) - -// Simple Pull Consumer -sub, err := js.PullSubscribe("ORDERS.*", "MONITOR") -msgs, err := sub.Fetch(10) - -// Unsubscribe -sub.Unsubscribe() - -// Drain -sub.Drain() -``` - -## JetStream Basic Management - -```go -import "github.com/nats-io/nats.go" - -// Connect to NATS -nc, _ := nats.Connect(nats.DefaultURL) - -// Create JetStream Context -js, _ := nc.JetStream() - -// Create a Stream -js.AddStream(&nats.StreamConfig{ - Name: "ORDERS", - Subjects: []string{"ORDERS.*"}, -}) - -// Update a Stream -js.UpdateStream(&nats.StreamConfig{ - Name: "ORDERS", - MaxBytes: 8, -}) - -// Create a Consumer -js.AddConsumer("ORDERS", &nats.ConsumerConfig{ - Durable: "MONITOR", -}) - -// Delete Consumer -js.DeleteConsumer("ORDERS", "MONITOR") - -// Delete Stream -js.DeleteStream("ORDERS") -``` diff --git a/vendor/github.com/nats-io/nats.go/nats.go b/vendor/github.com/nats-io/nats.go/nats.go deleted file mode 100644 index 5b145c62b..000000000 --- a/vendor/github.com/nats-io/nats.go/nats.go +++ /dev/null @@ -1,5694 +0,0 @@ -// Copyright 2012-2023 The NATS 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. - -// A Go client for the NATS messaging system (https://nats.io). -package nats - -import ( - "bufio" - "bytes" - "crypto/tls" - "crypto/x509" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "math/rand" - "net" - "net/http" - "net/textproto" - "net/url" - "os" - "path/filepath" - "regexp" - "runtime" - "strconv" - "strings" - "sync" - "sync/atomic" - "time" - - "github.com/nats-io/nkeys" - "github.com/nats-io/nuid" - - "github.com/nats-io/nats.go/util" -) - -// Default Constants -const ( - Version = "1.33.1" - DefaultURL = "nats://127.0.0.1:4222" - DefaultPort = 4222 - DefaultMaxReconnect = 60 - DefaultReconnectWait = 2 * time.Second - DefaultReconnectJitter = 100 * time.Millisecond - DefaultReconnectJitterTLS = time.Second - DefaultTimeout = 2 * time.Second - DefaultPingInterval = 2 * time.Minute - DefaultMaxPingOut = 2 - DefaultMaxChanLen = 64 * 1024 // 64k - DefaultReconnectBufSize = 8 * 1024 * 1024 // 8MB - RequestChanLen = 8 - DefaultDrainTimeout = 30 * time.Second - DefaultFlusherTimeout = time.Minute - LangString = "go" -) - -const ( - // STALE_CONNECTION is for detection and proper handling of stale connections. - STALE_CONNECTION = "stale connection" - - // PERMISSIONS_ERR is for when nats server subject authorization has failed. - PERMISSIONS_ERR = "permissions violation" - - // AUTHORIZATION_ERR is for when nats server user authorization has failed. - AUTHORIZATION_ERR = "authorization violation" - - // AUTHENTICATION_EXPIRED_ERR is for when nats server user authorization has expired. - AUTHENTICATION_EXPIRED_ERR = "user authentication expired" - - // AUTHENTICATION_REVOKED_ERR is for when user authorization has been revoked. - AUTHENTICATION_REVOKED_ERR = "user authentication revoked" - - // ACCOUNT_AUTHENTICATION_EXPIRED_ERR is for when nats server account authorization has expired. - ACCOUNT_AUTHENTICATION_EXPIRED_ERR = "account authentication expired" - - // MAX_CONNECTIONS_ERR is for when nats server denies the connection due to server max_connections limit - MAX_CONNECTIONS_ERR = "maximum connections exceeded" -) - -// Errors -var ( - ErrConnectionClosed = errors.New("nats: connection closed") - ErrConnectionDraining = errors.New("nats: connection draining") - ErrDrainTimeout = errors.New("nats: draining connection timed out") - ErrConnectionReconnecting = errors.New("nats: connection reconnecting") - ErrSecureConnRequired = errors.New("nats: secure connection required") - ErrSecureConnWanted = errors.New("nats: secure connection not available") - ErrBadSubscription = errors.New("nats: invalid subscription") - ErrTypeSubscription = errors.New("nats: invalid subscription type") - ErrBadSubject = errors.New("nats: invalid subject") - ErrBadQueueName = errors.New("nats: invalid queue name") - ErrSlowConsumer = errors.New("nats: slow consumer, messages dropped") - ErrTimeout = errors.New("nats: timeout") - ErrBadTimeout = errors.New("nats: timeout invalid") - ErrAuthorization = errors.New("nats: authorization violation") - ErrAuthExpired = errors.New("nats: authentication expired") - ErrAuthRevoked = errors.New("nats: authentication revoked") - ErrAccountAuthExpired = errors.New("nats: account authentication expired") - ErrNoServers = errors.New("nats: no servers available for connection") - ErrJsonParse = errors.New("nats: connect message, json parse error") - ErrChanArg = errors.New("nats: argument needs to be a channel type") - ErrMaxPayload = errors.New("nats: maximum payload exceeded") - ErrMaxMessages = errors.New("nats: maximum messages delivered") - ErrSyncSubRequired = errors.New("nats: illegal call on an async subscription") - ErrMultipleTLSConfigs = errors.New("nats: multiple tls.Configs not allowed") - ErrNoInfoReceived = errors.New("nats: protocol exception, INFO not received") - ErrReconnectBufExceeded = errors.New("nats: outbound buffer limit exceeded") - ErrInvalidConnection = errors.New("nats: invalid connection") - ErrInvalidMsg = errors.New("nats: invalid message or message nil") - ErrInvalidArg = errors.New("nats: invalid argument") - ErrInvalidContext = errors.New("nats: invalid context") - ErrNoDeadlineContext = errors.New("nats: context requires a deadline") - ErrNoEchoNotSupported = errors.New("nats: no echo option not supported by this server") - ErrClientIDNotSupported = errors.New("nats: client ID not supported by this server") - ErrUserButNoSigCB = errors.New("nats: user callback defined without a signature handler") - ErrNkeyButNoSigCB = errors.New("nats: nkey defined without a signature handler") - ErrNoUserCB = errors.New("nats: user callback not defined") - ErrNkeyAndUser = errors.New("nats: user callback and nkey defined") - ErrNkeysNotSupported = errors.New("nats: nkeys not supported by the server") - ErrStaleConnection = errors.New("nats: " + STALE_CONNECTION) - ErrTokenAlreadySet = errors.New("nats: token and token handler both set") - ErrMsgNotBound = errors.New("nats: message is not bound to subscription/connection") - ErrMsgNoReply = errors.New("nats: message does not have a reply") - ErrClientIPNotSupported = errors.New("nats: client IP not supported by this server") - ErrDisconnected = errors.New("nats: server is disconnected") - ErrHeadersNotSupported = errors.New("nats: headers not supported by this server") - ErrBadHeaderMsg = errors.New("nats: message could not decode headers") - ErrNoResponders = errors.New("nats: no responders available for request") - ErrMaxConnectionsExceeded = errors.New("nats: server maximum connections exceeded") - ErrConnectionNotTLS = errors.New("nats: connection is not tls") -) - -// GetDefaultOptions returns default configuration options for the client. -func GetDefaultOptions() Options { - return Options{ - AllowReconnect: true, - MaxReconnect: DefaultMaxReconnect, - ReconnectWait: DefaultReconnectWait, - ReconnectJitter: DefaultReconnectJitter, - ReconnectJitterTLS: DefaultReconnectJitterTLS, - Timeout: DefaultTimeout, - PingInterval: DefaultPingInterval, - MaxPingsOut: DefaultMaxPingOut, - SubChanLen: DefaultMaxChanLen, - ReconnectBufSize: DefaultReconnectBufSize, - DrainTimeout: DefaultDrainTimeout, - FlusherTimeout: DefaultFlusherTimeout, - } -} - -// DEPRECATED: Use GetDefaultOptions() instead. -// DefaultOptions is not safe for use by multiple clients. -// For details see #308. -var DefaultOptions = GetDefaultOptions() - -// Status represents the state of the connection. -type Status int - -const ( - DISCONNECTED = Status(iota) - CONNECTED - CLOSED - RECONNECTING - CONNECTING - DRAINING_SUBS - DRAINING_PUBS -) - -func (s Status) String() string { - switch s { - case DISCONNECTED: - return "DISCONNECTED" - case CONNECTED: - return "CONNECTED" - case CLOSED: - return "CLOSED" - case RECONNECTING: - return "RECONNECTING" - case CONNECTING: - return "CONNECTING" - case DRAINING_SUBS: - return "DRAINING_SUBS" - case DRAINING_PUBS: - return "DRAINING_PUBS" - } - return "unknown status" -} - -// ConnHandler is used for asynchronous events such as -// disconnected and closed connections. -type ConnHandler func(*Conn) - -// ConnErrHandler is used to process asynchronous events like -// disconnected connection with the error (if any). -type ConnErrHandler func(*Conn, error) - -// ErrHandler is used to process asynchronous errors encountered -// while processing inbound messages. -type ErrHandler func(*Conn, *Subscription, error) - -// UserJWTHandler is used to fetch and return the account signed -// JWT for this user. -type UserJWTHandler func() (string, error) - -// TLSCertHandler is used to fetch and return tls certificate. -type TLSCertHandler func() (tls.Certificate, error) - -// RootCAsHandler is used to fetch and return a set of root certificate -// authorities that clients use when verifying server certificates. -type RootCAsHandler func() (*x509.CertPool, error) - -// SignatureHandler is used to sign a nonce from the server while -// authenticating with nkeys. The user should sign the nonce and -// return the raw signature. The client will base64 encode this to -// send to the server. -type SignatureHandler func([]byte) ([]byte, error) - -// AuthTokenHandler is used to generate a new token. -type AuthTokenHandler func() string - -// ReconnectDelayHandler is used to get from the user the desired -// delay the library should pause before attempting to reconnect -// again. Note that this is invoked after the library tried the -// whole list of URLs and failed to reconnect. -type ReconnectDelayHandler func(attempts int) time.Duration - -// asyncCB is used to preserve order for async callbacks. -type asyncCB struct { - f func() - next *asyncCB -} - -type asyncCallbacksHandler struct { - mu sync.Mutex - cond *sync.Cond - head *asyncCB - tail *asyncCB -} - -// Option is a function on the options for a connection. -type Option func(*Options) error - -// CustomDialer can be used to specify any dialer, not necessarily a -// *net.Dialer. A CustomDialer may also implement `SkipTLSHandshake() bool` -// in order to skip the TLS handshake in case not required. -type CustomDialer interface { - Dial(network, address string) (net.Conn, error) -} - -type InProcessConnProvider interface { - InProcessConn() (net.Conn, error) -} - -// Options can be used to create a customized connection. -type Options struct { - - // Url represents a single NATS server url to which the client - // will be connecting. If the Servers option is also set, it - // then becomes the first server in the Servers array. - Url string - - // InProcessServer represents a NATS server running within the - // same process. If this is set then we will attempt to connect - // to the server directly rather than using external TCP conns. - InProcessServer InProcessConnProvider - - // Servers is a configured set of servers which this client - // will use when attempting to connect. - Servers []string - - // NoRandomize configures whether we will randomize the - // server pool. - NoRandomize bool - - // NoEcho configures whether the server will echo back messages - // that are sent on this connection if we also have matching subscriptions. - // Note this is supported on servers >= version 1.2. Proto 1 or greater. - NoEcho bool - - // Name is an optional name label which will be sent to the server - // on CONNECT to identify the client. - Name string - - // Verbose signals the server to send an OK ack for commands - // successfully processed by the server. - Verbose bool - - // Pedantic signals the server whether it should be doing further - // validation of subjects. - Pedantic bool - - // Secure enables TLS secure connections that skip server - // verification by default. NOT RECOMMENDED. - Secure bool - - // TLSConfig is a custom TLS configuration to use for secure - // transports. - TLSConfig *tls.Config - - // TLSCertCB is used to fetch and return custom tls certificate. - TLSCertCB TLSCertHandler - - // TLSHandshakeFirst is used to instruct the library perform - // the TLS handshake right after the connect and before receiving - // the INFO protocol from the server. If this option is enabled - // but the server is not configured to perform the TLS handshake - // first, the connection will fail. - TLSHandshakeFirst bool - - // RootCAsCB is used to fetch and return a set of root certificate - // authorities that clients use when verifying server certificates. - RootCAsCB RootCAsHandler - - // AllowReconnect enables reconnection logic to be used when we - // encounter a disconnect from the current server. - AllowReconnect bool - - // MaxReconnect sets the number of reconnect attempts that will be - // tried before giving up. If negative, then it will never give up - // trying to reconnect. - // Defaults to 60. - MaxReconnect int - - // ReconnectWait sets the time to backoff after attempting a reconnect - // to a server that we were already connected to previously. - // Defaults to 2s. - ReconnectWait time.Duration - - // CustomReconnectDelayCB is invoked after the library tried every - // URL in the server list and failed to reconnect. It passes to the - // user the current number of attempts. This function returns the - // amount of time the library will sleep before attempting to reconnect - // again. It is strongly recommended that this value contains some - // jitter to prevent all connections to attempt reconnecting at the same time. - CustomReconnectDelayCB ReconnectDelayHandler - - // ReconnectJitter sets the upper bound for a random delay added to - // ReconnectWait during a reconnect when no TLS is used. - // Defaults to 100ms. - ReconnectJitter time.Duration - - // ReconnectJitterTLS sets the upper bound for a random delay added to - // ReconnectWait during a reconnect when TLS is used. - // Defaults to 1s. - ReconnectJitterTLS time.Duration - - // Timeout sets the timeout for a Dial operation on a connection. - // Defaults to 2s. - Timeout time.Duration - - // DrainTimeout sets the timeout for a Drain Operation to complete. - // Defaults to 30s. - DrainTimeout time.Duration - - // FlusherTimeout is the maximum time to wait for write operations - // to the underlying connection to complete (including the flusher loop). - // Defaults to 1m. - FlusherTimeout time.Duration - - // PingInterval is the period at which the client will be sending ping - // commands to the server, disabled if 0 or negative. - // Defaults to 2m. - PingInterval time.Duration - - // MaxPingsOut is the maximum number of pending ping commands that can - // be awaiting a response before raising an ErrStaleConnection error. - // Defaults to 2. - MaxPingsOut int - - // ClosedCB sets the closed handler that is called when a client will - // no longer be connected. - ClosedCB ConnHandler - - // DisconnectedCB sets the disconnected handler that is called - // whenever the connection is disconnected. - // Will not be called if DisconnectedErrCB is set - // DEPRECATED. Use DisconnectedErrCB which passes error that caused - // the disconnect event. - DisconnectedCB ConnHandler - - // DisconnectedErrCB sets the disconnected error handler that is called - // whenever the connection is disconnected. - // Disconnected error could be nil, for instance when user explicitly closes the connection. - // DisconnectedCB will not be called if DisconnectedErrCB is set - DisconnectedErrCB ConnErrHandler - - // ConnectedCB sets the connected handler called when the initial connection - // is established. It is not invoked on successful reconnects - for reconnections, - // use ReconnectedCB. ConnectedCB can be used in conjunction with RetryOnFailedConnect - // to detect whether the initial connect was successful. - ConnectedCB ConnHandler - - // ReconnectedCB sets the reconnected handler called whenever - // the connection is successfully reconnected. - ReconnectedCB ConnHandler - - // DiscoveredServersCB sets the callback that is invoked whenever a new - // server has joined the cluster. - DiscoveredServersCB ConnHandler - - // AsyncErrorCB sets the async error handler (e.g. slow consumer errors) - AsyncErrorCB ErrHandler - - // ReconnectBufSize is the size of the backing bufio during reconnect. - // Once this has been exhausted publish operations will return an error. - // Defaults to 8388608 bytes (8MB). - ReconnectBufSize int - - // SubChanLen is the size of the buffered channel used between the socket - // Go routine and the message delivery for SyncSubscriptions. - // NOTE: This does not affect AsyncSubscriptions which are - // dictated by PendingLimits() - // Defaults to 65536. - SubChanLen int - - // UserJWT sets the callback handler that will fetch a user's JWT. - UserJWT UserJWTHandler - - // Nkey sets the public nkey that will be used to authenticate - // when connecting to the server. UserJWT and Nkey are mutually exclusive - // and if defined, UserJWT will take precedence. - Nkey string - - // SignatureCB designates the function used to sign the nonce - // presented from the server. - SignatureCB SignatureHandler - - // User sets the username to be used when connecting to the server. - User string - - // Password sets the password to be used when connecting to a server. - Password string - - // Token sets the token to be used when connecting to a server. - Token string - - // TokenHandler designates the function used to generate the token to be used when connecting to a server. - TokenHandler AuthTokenHandler - - // Dialer allows a custom net.Dialer when forming connections. - // DEPRECATED: should use CustomDialer instead. - Dialer *net.Dialer - - // CustomDialer allows to specify a custom dialer (not necessarily - // a *net.Dialer). - CustomDialer CustomDialer - - // UseOldRequestStyle forces the old method of Requests that utilize - // a new Inbox and a new Subscription for each request. - UseOldRequestStyle bool - - // NoCallbacksAfterClientClose allows preventing the invocation of - // callbacks after Close() is called. Client won't receive notifications - // when Close is invoked by user code. Default is to invoke the callbacks. - NoCallbacksAfterClientClose bool - - // LameDuckModeHandler sets the callback to invoke when the server notifies - // the connection that it entered lame duck mode, that is, going to - // gradually disconnect all its connections before shutting down. This is - // often used in deployments when upgrading NATS Servers. - LameDuckModeHandler ConnHandler - - // RetryOnFailedConnect sets the connection in reconnecting state right - // away if it can't connect to a server in the initial set. The - // MaxReconnect and ReconnectWait options are used for this process, - // similarly to when an established connection is disconnected. - // If a ReconnectHandler is set, it will be invoked on the first - // successful reconnect attempt (if the initial connect fails), - // and if a ClosedHandler is set, it will be invoked if - // it fails to connect (after exhausting the MaxReconnect attempts). - RetryOnFailedConnect bool - - // For websocket connections, indicates to the server that the connection - // supports compression. If the server does too, then data will be compressed. - Compression bool - - // For websocket connections, adds a path to connections url. - // This is useful when connecting to NATS behind a proxy. - ProxyPath string - - // InboxPrefix allows the default _INBOX prefix to be customized - InboxPrefix string - - // IgnoreAuthErrorAbort - if set to true, client opts out of the default connect behavior of aborting - // subsequent reconnect attempts if server returns the same auth error twice (regardless of reconnect policy). - IgnoreAuthErrorAbort bool - - // SkipHostLookup skips the DNS lookup for the server hostname. - SkipHostLookup bool -} - -const ( - // Scratch storage for assembling protocol headers - scratchSize = 512 - - // The size of the bufio reader/writer on top of the socket. - defaultBufSize = 32768 - - // The buffered size of the flush "kick" channel - flushChanSize = 1 - - // Default server pool size - srvPoolSize = 4 - - // NUID size - nuidSize = 22 - - // Default ports used if none is specified in given URL(s) - defaultWSPortString = "80" - defaultWSSPortString = "443" - defaultPortString = "4222" -) - -// A Conn represents a bare connection to a nats-server. -// It can send and receive []byte payloads. -// The connection is safe to use in multiple Go routines concurrently. -type Conn struct { - // Keep all members for which we use atomic at the beginning of the - // struct and make sure they are all 64bits (or use padding if necessary). - // atomic.* functions crash on 32bit machines if operand is not aligned - // at 64bit. See https://github.com/golang/go/issues/599 - Statistics - mu sync.RWMutex - // Opts holds the configuration of the Conn. - // Modifying the configuration of a running Conn is a race. - Opts Options - wg sync.WaitGroup - srvPool []*srv - current *srv - urls map[string]struct{} // Keep track of all known URLs (used by processInfo) - conn net.Conn - bw *natsWriter - br *natsReader - fch chan struct{} - info serverInfo - ssid int64 - subsMu sync.RWMutex - subs map[int64]*Subscription - ach *asyncCallbacksHandler - pongs []chan struct{} - scratch [scratchSize]byte - status Status - statListeners map[Status][]chan Status - initc bool // true if the connection is performing the initial connect - err error - ps *parseState - ptmr *time.Timer - pout int - ar bool // abort reconnect - rqch chan struct{} - ws bool // true if a websocket connection - - // New style response handler - respSub string // The wildcard subject - respSubPrefix string // the wildcard prefix including trailing . - respSubLen int // the length of the wildcard prefix excluding trailing . - respScanf string // The scanf template to extract mux token - respMux *Subscription // A single response subscription - respMap map[string]chan *Msg // Request map for the response msg channels - respRand *rand.Rand // Used for generating suffix - - // Msg filters for testing. - // Protected by subsMu - filters map[string]msgFilter -} - -type natsReader struct { - r io.Reader - buf []byte - off int - n int -} - -type natsWriter struct { - w io.Writer - bufs []byte - limit int - pending *bytes.Buffer - plimit int -} - -// Subscription represents interest in a given subject. -type Subscription struct { - mu sync.Mutex - sid int64 - - // Subject that represents this subscription. This can be different - // than the received subject inside a Msg if this is a wildcard. - Subject string - - // Optional queue group name. If present, all subscriptions with the - // same name will form a distributed queue, and each message will - // only be processed by one member of the group. - Queue string - - // For holding information about a JetStream consumer. - jsi *jsSub - - delivered uint64 - max uint64 - conn *Conn - mcb MsgHandler - mch chan *Msg - closed bool - sc bool - connClosed bool - - // Type of Subscription - typ SubscriptionType - - // Async linked list - pHead *Msg - pTail *Msg - pCond *sync.Cond - pDone func(subject string) - - // Pending stats, async subscriptions, high-speed etc. - pMsgs int - pBytes int - pMsgsMax int - pBytesMax int - pMsgsLimit int - pBytesLimit int - dropped int -} - -// Msg represents a message delivered by NATS. This structure is used -// by Subscribers and PublishMsg(). -// -// # Types of Acknowledgements -// -// In case using JetStream, there are multiple ways to ack a Msg: -// -// // Acknowledgement that a message has been processed. -// msg.Ack() -// -// // Negatively acknowledges a message. -// msg.Nak() -// -// // Terminate a message so that it is not redelivered further. -// msg.Term() -// -// // Signal the server that the message is being worked on and reset redelivery timer. -// msg.InProgress() -type Msg struct { - Subject string - Reply string - Header Header - Data []byte - Sub *Subscription - // Internal - next *Msg - wsz int - barrier *barrierInfo - ackd uint32 -} - -// Compares two msgs, ignores sub but checks all other public fields. -func (m *Msg) Equal(msg *Msg) bool { - if m == msg { - return true - } - if m == nil || msg == nil { - return false - } - if m.Subject != msg.Subject || m.Reply != msg.Reply { - return false - } - if !bytes.Equal(m.Data, msg.Data) { - return false - } - if len(m.Header) != len(msg.Header) { - return false - } - for k, v := range m.Header { - val, ok := msg.Header[k] - if !ok || len(v) != len(val) { - return false - } - for i, hdr := range v { - if hdr != val[i] { - return false - } - } - } - return true -} - -// Size returns a message size in bytes. -func (m *Msg) Size() int { - if m.wsz != 0 { - return m.wsz - } - hdr, _ := m.headerBytes() - return len(m.Subject) + len(m.Reply) + len(hdr) + len(m.Data) -} - -func (m *Msg) headerBytes() ([]byte, error) { - var hdr []byte - if len(m.Header) == 0 { - return hdr, nil - } - - var b bytes.Buffer - _, err := b.WriteString(hdrLine) - if err != nil { - return nil, ErrBadHeaderMsg - } - - err = http.Header(m.Header).Write(&b) - if err != nil { - return nil, ErrBadHeaderMsg - } - - _, err = b.WriteString(crlf) - if err != nil { - return nil, ErrBadHeaderMsg - } - - return b.Bytes(), nil -} - -type barrierInfo struct { - refs int64 - f func() -} - -// Tracks various stats received and sent on this connection, -// including counts for messages and bytes. -type Statistics struct { - InMsgs uint64 - OutMsgs uint64 - InBytes uint64 - OutBytes uint64 - Reconnects uint64 -} - -// Tracks individual backend servers. -type srv struct { - url *url.URL - didConnect bool - reconnects int - lastErr error - isImplicit bool - tlsName string -} - -// The INFO block received from the server. -type serverInfo struct { - ID string `json:"server_id"` - Name string `json:"server_name"` - Proto int `json:"proto"` - Version string `json:"version"` - Host string `json:"host"` - Port int `json:"port"` - Headers bool `json:"headers"` - AuthRequired bool `json:"auth_required,omitempty"` - TLSRequired bool `json:"tls_required,omitempty"` - TLSAvailable bool `json:"tls_available,omitempty"` - MaxPayload int64 `json:"max_payload"` - CID uint64 `json:"client_id,omitempty"` - ClientIP string `json:"client_ip,omitempty"` - Nonce string `json:"nonce,omitempty"` - Cluster string `json:"cluster,omitempty"` - ConnectURLs []string `json:"connect_urls,omitempty"` - LameDuckMode bool `json:"ldm,omitempty"` -} - -const ( - // clientProtoZero is the original client protocol from 2009. - // http://nats.io/documentation/internals/nats-protocol/ - /* clientProtoZero */ _ = iota - // clientProtoInfo signals a client can receive more then the original INFO block. - // This can be used to update clients on other cluster members, etc. - clientProtoInfo -) - -type connectInfo struct { - Verbose bool `json:"verbose"` - Pedantic bool `json:"pedantic"` - UserJWT string `json:"jwt,omitempty"` - Nkey string `json:"nkey,omitempty"` - Signature string `json:"sig,omitempty"` - User string `json:"user,omitempty"` - Pass string `json:"pass,omitempty"` - Token string `json:"auth_token,omitempty"` - TLS bool `json:"tls_required"` - Name string `json:"name"` - Lang string `json:"lang"` - Version string `json:"version"` - Protocol int `json:"protocol"` - Echo bool `json:"echo"` - Headers bool `json:"headers"` - NoResponders bool `json:"no_responders"` -} - -// MsgHandler is a callback function that processes messages delivered to -// asynchronous subscribers. -type MsgHandler func(msg *Msg) - -// Connect will attempt to connect to the NATS system. -// The url can contain username/password semantics. e.g. nats://derek:pass@localhost:4222 -// Comma separated arrays are also supported, e.g. urlA, urlB. -// Options start with the defaults but can be overridden. -// To connect to a NATS Server's websocket port, use the `ws` or `wss` scheme, such as -// `ws://localhost:8080`. Note that websocket schemes cannot be mixed with others (nats/tls). -func Connect(url string, options ...Option) (*Conn, error) { - opts := GetDefaultOptions() - opts.Servers = processUrlString(url) - for _, opt := range options { - if opt != nil { - if err := opt(&opts); err != nil { - return nil, err - } - } - } - return opts.Connect() -} - -// Options that can be passed to Connect. - -// Name is an Option to set the client name. -func Name(name string) Option { - return func(o *Options) error { - o.Name = name - return nil - } -} - -// InProcessServer is an Option that will try to establish a direction to a NATS server -// running within the process instead of dialing via TCP. -func InProcessServer(server InProcessConnProvider) Option { - return func(o *Options) error { - o.InProcessServer = server - return nil - } -} - -// Secure is an Option to enable TLS secure connections that skip server verification by default. -// Pass a TLS Configuration for proper TLS. -// A TLS Configuration using InsecureSkipVerify should NOT be used in a production setting. -func Secure(tls ...*tls.Config) Option { - return func(o *Options) error { - o.Secure = true - // Use of variadic just simplifies testing scenarios. We only take the first one. - if len(tls) > 1 { - return ErrMultipleTLSConfigs - } - if len(tls) == 1 { - o.TLSConfig = tls[0] - } - return nil - } -} - -// RootCAs is a helper option to provide the RootCAs pool from a list of filenames. -// If Secure is not already set this will set it as well. -func RootCAs(file ...string) Option { - return func(o *Options) error { - rootCAsCB := func() (*x509.CertPool, error) { - pool := x509.NewCertPool() - for _, f := range file { - rootPEM, err := os.ReadFile(f) - if err != nil || rootPEM == nil { - return nil, fmt.Errorf("nats: error loading or parsing rootCA file: %w", err) - } - ok := pool.AppendCertsFromPEM(rootPEM) - if !ok { - return nil, fmt.Errorf("nats: failed to parse root certificate from %q", f) - } - } - return pool, nil - } - if o.TLSConfig == nil { - o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} - } - if _, err := rootCAsCB(); err != nil { - return err - } - o.RootCAsCB = rootCAsCB - o.Secure = true - return nil - } -} - -// ClientCert is a helper option to provide the client certificate from a file. -// If Secure is not already set this will set it as well. -func ClientCert(certFile, keyFile string) Option { - return func(o *Options) error { - tlsCertCB := func() (tls.Certificate, error) { - cert, err := tls.LoadX509KeyPair(certFile, keyFile) - if err != nil { - return tls.Certificate{}, fmt.Errorf("nats: error loading client certificate: %w", err) - } - cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0]) - if err != nil { - return tls.Certificate{}, fmt.Errorf("nats: error parsing client certificate: %w", err) - } - return cert, nil - } - if o.TLSConfig == nil { - o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} - } - if _, err := tlsCertCB(); err != nil { - return err - } - o.TLSCertCB = tlsCertCB - o.Secure = true - return nil - } -} - -// NoReconnect is an Option to turn off reconnect behavior. -func NoReconnect() Option { - return func(o *Options) error { - o.AllowReconnect = false - return nil - } -} - -// DontRandomize is an Option to turn off randomizing the server pool. -func DontRandomize() Option { - return func(o *Options) error { - o.NoRandomize = true - return nil - } -} - -// NoEcho is an Option to turn off messages echoing back from a server. -// Note this is supported on servers >= version 1.2. Proto 1 or greater. -func NoEcho() Option { - return func(o *Options) error { - o.NoEcho = true - return nil - } -} - -// ReconnectWait is an Option to set the wait time between reconnect attempts. -// Defaults to 2s. -func ReconnectWait(t time.Duration) Option { - return func(o *Options) error { - o.ReconnectWait = t - return nil - } -} - -// MaxReconnects is an Option to set the maximum number of reconnect attempts. -// If negative, it will never stop trying to reconnect. -// Defaults to 60. -func MaxReconnects(max int) Option { - return func(o *Options) error { - o.MaxReconnect = max - return nil - } -} - -// ReconnectJitter is an Option to set the upper bound of a random delay added ReconnectWait. -// Defaults to 100ms and 1s, respectively. -func ReconnectJitter(jitter, jitterForTLS time.Duration) Option { - return func(o *Options) error { - o.ReconnectJitter = jitter - o.ReconnectJitterTLS = jitterForTLS - return nil - } -} - -// CustomReconnectDelay is an Option to set the CustomReconnectDelayCB option. -// See CustomReconnectDelayCB Option for more details. -func CustomReconnectDelay(cb ReconnectDelayHandler) Option { - return func(o *Options) error { - o.CustomReconnectDelayCB = cb - return nil - } -} - -// PingInterval is an Option to set the period for client ping commands. -// Defaults to 2m. -func PingInterval(t time.Duration) Option { - return func(o *Options) error { - o.PingInterval = t - return nil - } -} - -// MaxPingsOutstanding is an Option to set the maximum number of ping requests -// that can go unanswered by the server before closing the connection. -// Defaults to 2. -func MaxPingsOutstanding(max int) Option { - return func(o *Options) error { - o.MaxPingsOut = max - return nil - } -} - -// ReconnectBufSize sets the buffer size of messages kept while busy reconnecting. -// Defaults to 8388608 bytes (8MB). It can be disabled by setting it to -1. -func ReconnectBufSize(size int) Option { - return func(o *Options) error { - o.ReconnectBufSize = size - return nil - } -} - -// Timeout is an Option to set the timeout for Dial on a connection. -// Defaults to 2s. -func Timeout(t time.Duration) Option { - return func(o *Options) error { - o.Timeout = t - return nil - } -} - -// FlusherTimeout is an Option to set the write (and flush) timeout on a connection. -func FlusherTimeout(t time.Duration) Option { - return func(o *Options) error { - o.FlusherTimeout = t - return nil - } -} - -// DrainTimeout is an Option to set the timeout for draining a connection. -// Defaults to 30s. -func DrainTimeout(t time.Duration) Option { - return func(o *Options) error { - o.DrainTimeout = t - return nil - } -} - -// DisconnectErrHandler is an Option to set the disconnected error handler. -func DisconnectErrHandler(cb ConnErrHandler) Option { - return func(o *Options) error { - o.DisconnectedErrCB = cb - return nil - } -} - -// DisconnectHandler is an Option to set the disconnected handler. -// DEPRECATED: Use DisconnectErrHandler. -func DisconnectHandler(cb ConnHandler) Option { - return func(o *Options) error { - o.DisconnectedCB = cb - return nil - } -} - -// ConnectHandler is an Option to set the connected handler. -func ConnectHandler(cb ConnHandler) Option { - return func(o *Options) error { - o.ConnectedCB = cb - return nil - } -} - -// ReconnectHandler is an Option to set the reconnected handler. -func ReconnectHandler(cb ConnHandler) Option { - return func(o *Options) error { - o.ReconnectedCB = cb - return nil - } -} - -// ClosedHandler is an Option to set the closed handler. -func ClosedHandler(cb ConnHandler) Option { - return func(o *Options) error { - o.ClosedCB = cb - return nil - } -} - -// DiscoveredServersHandler is an Option to set the new servers handler. -func DiscoveredServersHandler(cb ConnHandler) Option { - return func(o *Options) error { - o.DiscoveredServersCB = cb - return nil - } -} - -// ErrorHandler is an Option to set the async error handler. -func ErrorHandler(cb ErrHandler) Option { - return func(o *Options) error { - o.AsyncErrorCB = cb - return nil - } -} - -// UserInfo is an Option to set the username and password to -// use when not included directly in the URLs. -func UserInfo(user, password string) Option { - return func(o *Options) error { - o.User = user - o.Password = password - return nil - } -} - -// Token is an Option to set the token to use -// when a token is not included directly in the URLs -// and when a token handler is not provided. -func Token(token string) Option { - return func(o *Options) error { - if o.TokenHandler != nil { - return ErrTokenAlreadySet - } - o.Token = token - return nil - } -} - -// TokenHandler is an Option to set the token handler to use -// when a token is not included directly in the URLs -// and when a token is not set. -func TokenHandler(cb AuthTokenHandler) Option { - return func(o *Options) error { - if o.Token != "" { - return ErrTokenAlreadySet - } - o.TokenHandler = cb - return nil - } -} - -// UserCredentials is a convenience function that takes a filename -// for a user's JWT and a filename for the user's private Nkey seed. -func UserCredentials(userOrChainedFile string, seedFiles ...string) Option { - userCB := func() (string, error) { - return userFromFile(userOrChainedFile) - } - var keyFile string - if len(seedFiles) > 0 { - keyFile = seedFiles[0] - } else { - keyFile = userOrChainedFile - } - sigCB := func(nonce []byte) ([]byte, error) { - return sigHandler(nonce, keyFile) - } - return UserJWT(userCB, sigCB) -} - -// UserJWTAndSeed is a convenience function that takes the JWT and seed -// values as strings. -func UserJWTAndSeed(jwt string, seed string) Option { - userCB := func() (string, error) { - return jwt, nil - } - - sigCB := func(nonce []byte) ([]byte, error) { - kp, err := nkeys.FromSeed([]byte(seed)) - if err != nil { - return nil, fmt.Errorf("unable to extract key pair from seed: %w", err) - } - // Wipe our key on exit. - defer kp.Wipe() - - sig, _ := kp.Sign(nonce) - return sig, nil - } - - return UserJWT(userCB, sigCB) -} - -// UserJWT will set the callbacks to retrieve the user's JWT and -// the signature callback to sign the server nonce. This an the Nkey -// option are mutually exclusive. -func UserJWT(userCB UserJWTHandler, sigCB SignatureHandler) Option { - return func(o *Options) error { - if userCB == nil { - return ErrNoUserCB - } - if sigCB == nil { - return ErrUserButNoSigCB - } - // Smoke test the user callback to ensure it is setup properly - // when processing options. - if _, err := userCB(); err != nil { - return err - } - - o.UserJWT = userCB - o.SignatureCB = sigCB - return nil - } -} - -// Nkey will set the public Nkey and the signature callback to -// sign the server nonce. -func Nkey(pubKey string, sigCB SignatureHandler) Option { - return func(o *Options) error { - o.Nkey = pubKey - o.SignatureCB = sigCB - if pubKey != "" && sigCB == nil { - return ErrNkeyButNoSigCB - } - return nil - } -} - -// SyncQueueLen will set the maximum queue len for the internal -// channel used for SubscribeSync(). -// Defaults to 65536. -func SyncQueueLen(max int) Option { - return func(o *Options) error { - o.SubChanLen = max - return nil - } -} - -// Dialer is an Option to set the dialer which will be used when -// attempting to establish a connection. -// DEPRECATED: Should use CustomDialer instead. -func Dialer(dialer *net.Dialer) Option { - return func(o *Options) error { - o.Dialer = dialer - return nil - } -} - -// SetCustomDialer is an Option to set a custom dialer which will be -// used when attempting to establish a connection. If both Dialer -// and CustomDialer are specified, CustomDialer takes precedence. -func SetCustomDialer(dialer CustomDialer) Option { - return func(o *Options) error { - o.CustomDialer = dialer - return nil - } -} - -// UseOldRequestStyle is an Option to force usage of the old Request style. -func UseOldRequestStyle() Option { - return func(o *Options) error { - o.UseOldRequestStyle = true - return nil - } -} - -// NoCallbacksAfterClientClose is an Option to disable callbacks when user code -// calls Close(). If close is initiated by any other condition, callbacks -// if any will be invoked. -func NoCallbacksAfterClientClose() Option { - return func(o *Options) error { - o.NoCallbacksAfterClientClose = true - return nil - } -} - -// LameDuckModeHandler sets the callback to invoke when the server notifies -// the connection that it entered lame duck mode, that is, going to -// gradually disconnect all its connections before shutting down. This is -// often used in deployments when upgrading NATS Servers. -func LameDuckModeHandler(cb ConnHandler) Option { - return func(o *Options) error { - o.LameDuckModeHandler = cb - return nil - } -} - -// RetryOnFailedConnect sets the connection in reconnecting state right away -// if it can't connect to a server in the initial set. -// See RetryOnFailedConnect option for more details. -func RetryOnFailedConnect(retry bool) Option { - return func(o *Options) error { - o.RetryOnFailedConnect = retry - return nil - } -} - -// Compression is an Option to indicate if this connection supports -// compression. Currently only supported for Websocket connections. -func Compression(enabled bool) Option { - return func(o *Options) error { - o.Compression = enabled - return nil - } -} - -// ProxyPath is an option for websocket connections that adds a path to connections url. -// This is useful when connecting to NATS behind a proxy. -func ProxyPath(path string) Option { - return func(o *Options) error { - o.ProxyPath = path - return nil - } -} - -// CustomInboxPrefix configures the request + reply inbox prefix -func CustomInboxPrefix(p string) Option { - return func(o *Options) error { - if p == "" || strings.Contains(p, ">") || strings.Contains(p, "*") || strings.HasSuffix(p, ".") { - return fmt.Errorf("nats: invalid custom prefix") - } - o.InboxPrefix = p - return nil - } -} - -// IgnoreAuthErrorAbort opts out of the default connect behavior of aborting -// subsequent reconnect attempts if server returns the same auth error twice. -func IgnoreAuthErrorAbort() Option { - return func(o *Options) error { - o.IgnoreAuthErrorAbort = true - return nil - } -} - -// SkipHostLookup is an Option to skip the host lookup when connecting to a server. -func SkipHostLookup() Option { - return func(o *Options) error { - o.SkipHostLookup = true - return nil - } -} - -// TLSHandshakeFirst is an Option to perform the TLS handshake first, that is -// before receiving the INFO protocol. This requires the server to also be -// configured with such option, otherwise the connection will fail. -func TLSHandshakeFirst() Option { - return func(o *Options) error { - o.TLSHandshakeFirst = true - o.Secure = true - return nil - } -} - -// Handler processing - -// SetDisconnectHandler will set the disconnect event handler. -// DEPRECATED: Use SetDisconnectErrHandler -func (nc *Conn) SetDisconnectHandler(dcb ConnHandler) { - if nc == nil { - return - } - nc.mu.Lock() - defer nc.mu.Unlock() - nc.Opts.DisconnectedCB = dcb -} - -// SetDisconnectErrHandler will set the disconnect event handler. -func (nc *Conn) SetDisconnectErrHandler(dcb ConnErrHandler) { - if nc == nil { - return - } - nc.mu.Lock() - defer nc.mu.Unlock() - nc.Opts.DisconnectedErrCB = dcb -} - -// DisconnectErrHandler will return the disconnect event handler. -func (nc *Conn) DisconnectErrHandler() ConnErrHandler { - if nc == nil { - return nil - } - nc.mu.Lock() - defer nc.mu.Unlock() - return nc.Opts.DisconnectedErrCB -} - -// SetReconnectHandler will set the reconnect event handler. -func (nc *Conn) SetReconnectHandler(rcb ConnHandler) { - if nc == nil { - return - } - nc.mu.Lock() - defer nc.mu.Unlock() - nc.Opts.ReconnectedCB = rcb -} - -// ReconnectHandler will return the reconnect event handler. -func (nc *Conn) ReconnectHandler() ConnHandler { - if nc == nil { - return nil - } - nc.mu.Lock() - defer nc.mu.Unlock() - return nc.Opts.ReconnectedCB -} - -// SetDiscoveredServersHandler will set the discovered servers handler. -func (nc *Conn) SetDiscoveredServersHandler(dscb ConnHandler) { - if nc == nil { - return - } - nc.mu.Lock() - defer nc.mu.Unlock() - nc.Opts.DiscoveredServersCB = dscb -} - -// DiscoveredServersHandler will return the discovered servers handler. -func (nc *Conn) DiscoveredServersHandler() ConnHandler { - if nc == nil { - return nil - } - nc.mu.Lock() - defer nc.mu.Unlock() - return nc.Opts.DiscoveredServersCB -} - -// SetClosedHandler will set the closed event handler. -func (nc *Conn) SetClosedHandler(cb ConnHandler) { - if nc == nil { - return - } - nc.mu.Lock() - defer nc.mu.Unlock() - nc.Opts.ClosedCB = cb -} - -// ClosedHandler will return the closed event handler. -func (nc *Conn) ClosedHandler() ConnHandler { - if nc == nil { - return nil - } - nc.mu.Lock() - defer nc.mu.Unlock() - return nc.Opts.ClosedCB -} - -// SetErrorHandler will set the async error handler. -func (nc *Conn) SetErrorHandler(cb ErrHandler) { - if nc == nil { - return - } - nc.mu.Lock() - defer nc.mu.Unlock() - nc.Opts.AsyncErrorCB = cb -} - -// ErrorHandler will return the async error handler. -func (nc *Conn) ErrorHandler() ErrHandler { - if nc == nil { - return nil - } - nc.mu.Lock() - defer nc.mu.Unlock() - return nc.Opts.AsyncErrorCB -} - -// Process the url string argument to Connect. -// Return an array of urls, even if only one. -func processUrlString(url string) []string { - urls := strings.Split(url, ",") - var j int - for _, s := range urls { - u := strings.TrimSpace(s) - if len(u) > 0 { - urls[j] = u - j++ - } - } - return urls[:j] -} - -// Connect will attempt to connect to a NATS server with multiple options. -func (o Options) Connect() (*Conn, error) { - nc := &Conn{Opts: o} - - // Some default options processing. - if nc.Opts.MaxPingsOut == 0 { - nc.Opts.MaxPingsOut = DefaultMaxPingOut - } - // Allow old default for channel length to work correctly. - if nc.Opts.SubChanLen == 0 { - nc.Opts.SubChanLen = DefaultMaxChanLen - } - // Default ReconnectBufSize - if nc.Opts.ReconnectBufSize == 0 { - nc.Opts.ReconnectBufSize = DefaultReconnectBufSize - } - // Ensure that Timeout is not 0 - if nc.Opts.Timeout == 0 { - nc.Opts.Timeout = DefaultTimeout - } - - // Check first for user jwt callback being defined and nkey. - if nc.Opts.UserJWT != nil && nc.Opts.Nkey != "" { - return nil, ErrNkeyAndUser - } - - // Check if we have an nkey but no signature callback defined. - if nc.Opts.Nkey != "" && nc.Opts.SignatureCB == nil { - return nil, ErrNkeyButNoSigCB - } - - // Allow custom Dialer for connecting using a timeout by default - if nc.Opts.Dialer == nil { - nc.Opts.Dialer = &net.Dialer{ - Timeout: nc.Opts.Timeout, - } - } - - // If the TLSHandshakeFirst option is specified, make sure that - // the Secure boolean is true. - if nc.Opts.TLSHandshakeFirst { - nc.Opts.Secure = true - } - - if err := nc.setupServerPool(); err != nil { - return nil, err - } - - // Create the async callback handler. - nc.ach = &asyncCallbacksHandler{} - nc.ach.cond = sync.NewCond(&nc.ach.mu) - - // Set a default error handler that will print to stderr. - if nc.Opts.AsyncErrorCB == nil { - nc.Opts.AsyncErrorCB = defaultErrHandler - } - - // Create reader/writer - nc.newReaderWriter() - - connectionEstablished, err := nc.connect() - if err != nil { - return nil, err - } - - // Spin up the async cb dispatcher on success - go nc.ach.asyncCBDispatcher() - - if connectionEstablished && nc.Opts.ConnectedCB != nil { - nc.ach.push(func() { nc.Opts.ConnectedCB(nc) }) - } - - return nc, nil -} - -func defaultErrHandler(nc *Conn, sub *Subscription, err error) { - var cid uint64 - if nc != nil { - nc.mu.RLock() - cid = nc.info.CID - nc.mu.RUnlock() - } - var errStr string - if sub != nil { - var subject string - sub.mu.Lock() - if sub.jsi != nil { - subject = sub.jsi.psubj - } else { - subject = sub.Subject - } - sub.mu.Unlock() - errStr = fmt.Sprintf("%s on connection [%d] for subscription on %q\n", err.Error(), cid, subject) - } else { - errStr = fmt.Sprintf("%s on connection [%d]\n", err.Error(), cid) - } - os.Stderr.WriteString(errStr) -} - -const ( - _CRLF_ = "\r\n" - _EMPTY_ = "" - _SPC_ = " " - _PUB_P_ = "PUB " - _HPUB_P_ = "HPUB " -) - -var _CRLF_BYTES_ = []byte(_CRLF_) - -const ( - _OK_OP_ = "+OK" - _ERR_OP_ = "-ERR" - _PONG_OP_ = "PONG" - _INFO_OP_ = "INFO" -) - -const ( - connectProto = "CONNECT %s" + _CRLF_ - pingProto = "PING" + _CRLF_ - pongProto = "PONG" + _CRLF_ - subProto = "SUB %s %s %d" + _CRLF_ - unsubProto = "UNSUB %d %s" + _CRLF_ - okProto = _OK_OP_ + _CRLF_ -) - -// Return the currently selected server -func (nc *Conn) currentServer() (int, *srv) { - for i, s := range nc.srvPool { - if s == nil { - continue - } - if s == nc.current { - return i, s - } - } - return -1, nil -} - -// Pop the current server and put onto the end of the list. Select head of list as long -// as number of reconnect attempts under MaxReconnect. -func (nc *Conn) selectNextServer() (*srv, error) { - i, s := nc.currentServer() - if i < 0 { - return nil, ErrNoServers - } - sp := nc.srvPool - num := len(sp) - copy(sp[i:num-1], sp[i+1:num]) - maxReconnect := nc.Opts.MaxReconnect - if maxReconnect < 0 || s.reconnects < maxReconnect { - nc.srvPool[num-1] = s - } else { - nc.srvPool = sp[0 : num-1] - } - if len(nc.srvPool) <= 0 { - nc.current = nil - return nil, ErrNoServers - } - nc.current = nc.srvPool[0] - return nc.srvPool[0], nil -} - -// Will assign the correct server to nc.current -func (nc *Conn) pickServer() error { - nc.current = nil - if len(nc.srvPool) <= 0 { - return ErrNoServers - } - - for _, s := range nc.srvPool { - if s != nil { - nc.current = s - return nil - } - } - return ErrNoServers -} - -const tlsScheme = "tls" - -// Create the server pool using the options given. -// We will place a Url option first, followed by any -// Server Options. We will randomize the server pool unless -// the NoRandomize flag is set. -func (nc *Conn) setupServerPool() error { - nc.srvPool = make([]*srv, 0, srvPoolSize) - nc.urls = make(map[string]struct{}, srvPoolSize) - - // Create srv objects from each url string in nc.Opts.Servers - // and add them to the pool. - for _, urlString := range nc.Opts.Servers { - if err := nc.addURLToPool(urlString, false, false); err != nil { - return err - } - } - - // Randomize if allowed to - if !nc.Opts.NoRandomize { - nc.shufflePool(0) - } - - // Normally, if this one is set, Options.Servers should not be, - // but we always allowed that, so continue to do so. - if nc.Opts.Url != _EMPTY_ { - // Add to the end of the array - if err := nc.addURLToPool(nc.Opts.Url, false, false); err != nil { - return err - } - // Then swap it with first to guarantee that Options.Url is tried first. - last := len(nc.srvPool) - 1 - if last > 0 { - nc.srvPool[0], nc.srvPool[last] = nc.srvPool[last], nc.srvPool[0] - } - } else if len(nc.srvPool) <= 0 { - // Place default URL if pool is empty. - if err := nc.addURLToPool(DefaultURL, false, false); err != nil { - return err - } - } - - // Check for Scheme hint to move to TLS mode. - for _, srv := range nc.srvPool { - if srv.url.Scheme == tlsScheme || srv.url.Scheme == wsSchemeTLS { - // FIXME(dlc), this is for all in the pool, should be case by case. - nc.Opts.Secure = true - if nc.Opts.TLSConfig == nil { - nc.Opts.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} - } - } - } - - return nc.pickServer() -} - -// Helper function to return scheme -func (nc *Conn) connScheme() string { - if nc.ws { - if nc.Opts.Secure { - return wsSchemeTLS - } - return wsScheme - } - if nc.Opts.Secure { - return tlsScheme - } - return "nats" -} - -// Return true iff u.Hostname() is an IP address. -func hostIsIP(u *url.URL) bool { - return net.ParseIP(u.Hostname()) != nil -} - -// addURLToPool adds an entry to the server pool -func (nc *Conn) addURLToPool(sURL string, implicit, saveTLSName bool) error { - if !strings.Contains(sURL, "://") { - sURL = fmt.Sprintf("%s://%s", nc.connScheme(), sURL) - } - var ( - u *url.URL - err error - ) - for i := 0; i < 2; i++ { - u, err = url.Parse(sURL) - if err != nil { - return err - } - if u.Port() != "" { - break - } - // In case given URL is of the form "localhost:", just add - // the port number at the end, otherwise, add ":4222". - if sURL[len(sURL)-1] != ':' { - sURL += ":" - } - switch u.Scheme { - case wsScheme: - sURL += defaultWSPortString - case wsSchemeTLS: - sURL += defaultWSSPortString - default: - sURL += defaultPortString - } - } - - isWS := isWebsocketScheme(u) - // We don't support mix and match of websocket and non websocket URLs. - // If this is the first URL, then we accept and switch the global state - // to websocket. After that, we will know how to reject mixed URLs. - if len(nc.srvPool) == 0 { - nc.ws = isWS - } else if isWS && !nc.ws || !isWS && nc.ws { - return fmt.Errorf("mixing of websocket and non websocket URLs is not allowed") - } - - var tlsName string - if implicit { - curl := nc.current.url - // Check to see if we do not have a url.User but current connected - // url does. If so copy over. - if u.User == nil && curl.User != nil { - u.User = curl.User - } - // We are checking to see if we have a secure connection and are - // adding an implicit server that just has an IP. If so we will remember - // the current hostname we are connected to. - if saveTLSName && hostIsIP(u) { - tlsName = curl.Hostname() - } - } - - s := &srv{url: u, isImplicit: implicit, tlsName: tlsName} - nc.srvPool = append(nc.srvPool, s) - nc.urls[u.Host] = struct{}{} - return nil -} - -// shufflePool swaps randomly elements in the server pool -// The `offset` value indicates that the shuffling should start at -// this offset and leave the elements from [0..offset) intact. -func (nc *Conn) shufflePool(offset int) { - if len(nc.srvPool) <= offset+1 { - return - } - source := rand.NewSource(time.Now().UnixNano()) - r := rand.New(source) - for i := offset; i < len(nc.srvPool); i++ { - j := offset + r.Intn(i+1-offset) - nc.srvPool[i], nc.srvPool[j] = nc.srvPool[j], nc.srvPool[i] - } -} - -func (nc *Conn) newReaderWriter() { - nc.br = &natsReader{ - buf: make([]byte, defaultBufSize), - off: -1, - } - nc.bw = &natsWriter{ - limit: defaultBufSize, - plimit: nc.Opts.ReconnectBufSize, - } -} - -func (nc *Conn) bindToNewConn() { - bw := nc.bw - bw.w, bw.bufs = nc.newWriter(), nil - br := nc.br - br.r, br.n, br.off = nc.conn, 0, -1 -} - -func (nc *Conn) newWriter() io.Writer { - var w io.Writer = nc.conn - if nc.Opts.FlusherTimeout > 0 { - w = &timeoutWriter{conn: nc.conn, timeout: nc.Opts.FlusherTimeout} - } - return w -} - -func (w *natsWriter) appendString(str string) error { - return w.appendBufs([]byte(str)) -} - -func (w *natsWriter) appendBufs(bufs ...[]byte) error { - for _, buf := range bufs { - if len(buf) == 0 { - continue - } - if w.pending != nil { - w.pending.Write(buf) - } else { - w.bufs = append(w.bufs, buf...) - } - } - if w.pending == nil && len(w.bufs) >= w.limit { - return w.flush() - } - return nil -} - -func (w *natsWriter) writeDirect(strs ...string) error { - for _, str := range strs { - if _, err := w.w.Write([]byte(str)); err != nil { - return err - } - } - return nil -} - -func (w *natsWriter) flush() error { - // If a pending buffer is set, we don't flush. Code that needs to - // write directly to the socket, by-passing buffers during (re)connect, - // will use the writeDirect() API. - if w.pending != nil { - return nil - } - // Do not skip calling w.w.Write() here if len(w.bufs) is 0 because - // the actual writer (if websocket for instance) may have things - // to do such as sending control frames, etc.. - _, err := w.w.Write(w.bufs) - w.bufs = w.bufs[:0] - return err -} - -func (w *natsWriter) buffered() int { - if w.pending != nil { - return w.pending.Len() - } - return len(w.bufs) -} - -func (w *natsWriter) switchToPending() { - w.pending = new(bytes.Buffer) -} - -func (w *natsWriter) flushPendingBuffer() error { - if w.pending == nil || w.pending.Len() == 0 { - return nil - } - _, err := w.w.Write(w.pending.Bytes()) - // Reset the pending buffer at this point because we don't want - // to take the risk of sending duplicates or partials. - w.pending.Reset() - return err -} - -func (w *natsWriter) atLimitIfUsingPending() bool { - if w.pending == nil { - return false - } - return w.pending.Len() >= w.plimit -} - -func (w *natsWriter) doneWithPending() { - w.pending = nil -} - -// Notify the reader that we are done with the connect, where "read" operations -// happen synchronously and under the connection lock. After this point, "read" -// will be happening from the read loop, without the connection lock. -// -// Note: this runs under the connection lock. -func (r *natsReader) doneWithConnect() { - if wsr, ok := r.r.(*websocketReader); ok { - wsr.doneWithConnect() - } -} - -func (r *natsReader) Read() ([]byte, error) { - if r.off >= 0 { - off := r.off - r.off = -1 - return r.buf[off:r.n], nil - } - var err error - r.n, err = r.r.Read(r.buf) - return r.buf[:r.n], err -} - -func (r *natsReader) ReadString(delim byte) (string, error) { - var s string -build_string: - // First look if we have something in the buffer - if r.off >= 0 { - i := bytes.IndexByte(r.buf[r.off:r.n], delim) - if i >= 0 { - end := r.off + i + 1 - s += string(r.buf[r.off:end]) - r.off = end - if r.off >= r.n { - r.off = -1 - } - return s, nil - } - // We did not find the delim, so will have to read more. - s += string(r.buf[r.off:r.n]) - r.off = -1 - } - if _, err := r.Read(); err != nil { - return s, err - } - r.off = 0 - goto build_string -} - -// createConn will connect to the server and wrap the appropriate -// bufio structures. It will do the right thing when an existing -// connection is in place. -func (nc *Conn) createConn() (err error) { - if nc.Opts.Timeout < 0 { - return ErrBadTimeout - } - if _, cur := nc.currentServer(); cur == nil { - return ErrNoServers - } - - // If we have a reference to an in-process server then establish a - // connection using that. - if nc.Opts.InProcessServer != nil { - conn, err := nc.Opts.InProcessServer.InProcessConn() - if err != nil { - return fmt.Errorf("failed to get in-process connection: %w", err) - } - nc.conn = conn - nc.bindToNewConn() - return nil - } - - // We will auto-expand host names if they resolve to multiple IPs - hosts := []string{} - u := nc.current.url - - if !nc.Opts.SkipHostLookup && net.ParseIP(u.Hostname()) == nil { - addrs, _ := net.LookupHost(u.Hostname()) - for _, addr := range addrs { - hosts = append(hosts, net.JoinHostPort(addr, u.Port())) - } - } - // Fall back to what we were given. - if len(hosts) == 0 { - hosts = append(hosts, u.Host) - } - - // CustomDialer takes precedence. If not set, use Opts.Dialer which - // is set to a default *net.Dialer (in Connect()) if not explicitly - // set by the user. - dialer := nc.Opts.CustomDialer - if dialer == nil { - // We will copy and shorten the timeout if we have multiple hosts to try. - copyDialer := *nc.Opts.Dialer - copyDialer.Timeout = copyDialer.Timeout / time.Duration(len(hosts)) - dialer = ©Dialer - } - - if len(hosts) > 1 && !nc.Opts.NoRandomize { - rand.Shuffle(len(hosts), func(i, j int) { - hosts[i], hosts[j] = hosts[j], hosts[i] - }) - } - for _, host := range hosts { - nc.conn, err = dialer.Dial("tcp", host) - if err == nil { - break - } - } - if err != nil { - return err - } - - // If scheme starts with "ws" then branch out to websocket code. - if isWebsocketScheme(u) { - return nc.wsInitHandshake(u) - } - - // Reset reader/writer to this new TCP connection - nc.bindToNewConn() - return nil -} - -type skipTLSDialer interface { - SkipTLSHandshake() bool -} - -// makeTLSConn will wrap an existing Conn using TLS -func (nc *Conn) makeTLSConn() error { - if nc.Opts.CustomDialer != nil { - // we do nothing when asked to skip the TLS wrapper - sd, ok := nc.Opts.CustomDialer.(skipTLSDialer) - if ok && sd.SkipTLSHandshake() { - return nil - } - } - // Allow the user to configure their own tls.Config structure. - tlsCopy := &tls.Config{} - if nc.Opts.TLSConfig != nil { - tlsCopy = util.CloneTLSConfig(nc.Opts.TLSConfig) - } - if nc.Opts.TLSCertCB != nil { - cert, err := nc.Opts.TLSCertCB() - if err != nil { - return err - } - tlsCopy.Certificates = []tls.Certificate{cert} - } - if nc.Opts.RootCAsCB != nil { - rootCAs, err := nc.Opts.RootCAsCB() - if err != nil { - return err - } - tlsCopy.RootCAs = rootCAs - } - // If its blank we will override it with the current host - if tlsCopy.ServerName == _EMPTY_ { - if nc.current.tlsName != _EMPTY_ { - tlsCopy.ServerName = nc.current.tlsName - } else { - h, _, _ := net.SplitHostPort(nc.current.url.Host) - tlsCopy.ServerName = h - } - } - nc.conn = tls.Client(nc.conn, tlsCopy) - conn := nc.conn.(*tls.Conn) - if err := conn.Handshake(); err != nil { - return err - } - nc.bindToNewConn() - return nil -} - -// TLSConnectionState retrieves the state of the TLS connection to the server -func (nc *Conn) TLSConnectionState() (tls.ConnectionState, error) { - if !nc.isConnected() { - return tls.ConnectionState{}, ErrDisconnected - } - - nc.mu.RLock() - conn := nc.conn - nc.mu.RUnlock() - - tc, ok := conn.(*tls.Conn) - if !ok { - return tls.ConnectionState{}, ErrConnectionNotTLS - } - - return tc.ConnectionState(), nil -} - -// waitForExits will wait for all socket watcher Go routines to -// be shutdown before proceeding. -func (nc *Conn) waitForExits() { - // Kick old flusher forcefully. - select { - case nc.fch <- struct{}{}: - default: - } - - // Wait for any previous go routines. - nc.wg.Wait() -} - -// ConnectedUrl reports the connected server's URL -func (nc *Conn) ConnectedUrl() string { - if nc == nil { - return _EMPTY_ - } - - nc.mu.RLock() - defer nc.mu.RUnlock() - - if nc.status != CONNECTED { - return _EMPTY_ - } - return nc.current.url.String() -} - -// ConnectedUrlRedacted reports the connected server's URL with passwords redacted -func (nc *Conn) ConnectedUrlRedacted() string { - if nc == nil { - return _EMPTY_ - } - - nc.mu.RLock() - defer nc.mu.RUnlock() - - if nc.status != CONNECTED { - return _EMPTY_ - } - return nc.current.url.Redacted() -} - -// ConnectedAddr returns the connected server's IP -func (nc *Conn) ConnectedAddr() string { - if nc == nil { - return _EMPTY_ - } - - nc.mu.RLock() - defer nc.mu.RUnlock() - - if nc.status != CONNECTED { - return _EMPTY_ - } - return nc.conn.RemoteAddr().String() -} - -// ConnectedServerId reports the connected server's Id -func (nc *Conn) ConnectedServerId() string { - if nc == nil { - return _EMPTY_ - } - - nc.mu.RLock() - defer nc.mu.RUnlock() - - if nc.status != CONNECTED { - return _EMPTY_ - } - return nc.info.ID -} - -// ConnectedServerName reports the connected server's name -func (nc *Conn) ConnectedServerName() string { - if nc == nil { - return _EMPTY_ - } - - nc.mu.RLock() - defer nc.mu.RUnlock() - - if nc.status != CONNECTED { - return _EMPTY_ - } - return nc.info.Name -} - -var semVerRe = regexp.MustCompile(`\Av?([0-9]+)\.?([0-9]+)?\.?([0-9]+)?`) - -func versionComponents(version string) (major, minor, patch int, err error) { - m := semVerRe.FindStringSubmatch(version) - if m == nil { - return 0, 0, 0, errors.New("invalid semver") - } - major, err = strconv.Atoi(m[1]) - if err != nil { - return -1, -1, -1, err - } - minor, err = strconv.Atoi(m[2]) - if err != nil { - return -1, -1, -1, err - } - patch, err = strconv.Atoi(m[3]) - if err != nil { - return -1, -1, -1, err - } - return major, minor, patch, err -} - -// Check for minimum server requirement. -func (nc *Conn) serverMinVersion(major, minor, patch int) bool { - smajor, sminor, spatch, _ := versionComponents(nc.ConnectedServerVersion()) - if smajor < major || (smajor == major && sminor < minor) || (smajor == major && sminor == minor && spatch < patch) { - return false - } - return true -} - -// ConnectedServerVersion reports the connected server's version as a string -func (nc *Conn) ConnectedServerVersion() string { - if nc == nil { - return _EMPTY_ - } - - nc.mu.RLock() - defer nc.mu.RUnlock() - - if nc.status != CONNECTED { - return _EMPTY_ - } - return nc.info.Version -} - -// ConnectedClusterName reports the connected server's cluster name if any -func (nc *Conn) ConnectedClusterName() string { - if nc == nil { - return _EMPTY_ - } - - nc.mu.RLock() - defer nc.mu.RUnlock() - - if nc.status != CONNECTED { - return _EMPTY_ - } - return nc.info.Cluster -} - -// Low level setup for structs, etc -func (nc *Conn) setup() { - nc.subs = make(map[int64]*Subscription) - nc.pongs = make([]chan struct{}, 0, 8) - - nc.fch = make(chan struct{}, flushChanSize) - nc.rqch = make(chan struct{}) - - // Setup scratch outbound buffer for PUB/HPUB - pub := nc.scratch[:len(_HPUB_P_)] - copy(pub, _HPUB_P_) -} - -// Process a connected connection and initialize properly. -func (nc *Conn) processConnectInit() error { - - // Set our deadline for the whole connect process - nc.conn.SetDeadline(time.Now().Add(nc.Opts.Timeout)) - defer nc.conn.SetDeadline(time.Time{}) - - // Set our status to connecting. - nc.changeConnStatus(CONNECTING) - - // If we need to have a TLS connection and want the TLS handshake to occur - // first, do it now. - if nc.Opts.Secure && nc.Opts.TLSHandshakeFirst { - if err := nc.makeTLSConn(); err != nil { - return err - } - } - - // Process the INFO protocol received from the server - err := nc.processExpectedInfo() - if err != nil { - return err - } - - // Send the CONNECT protocol along with the initial PING protocol. - // Wait for the PONG response (or any error that we get from the server). - err = nc.sendConnect() - if err != nil { - return err - } - - // Reset the number of PING sent out - nc.pout = 0 - - // Start or reset Timer - if nc.Opts.PingInterval > 0 { - if nc.ptmr == nil { - nc.ptmr = time.AfterFunc(nc.Opts.PingInterval, nc.processPingTimer) - } else { - nc.ptmr.Reset(nc.Opts.PingInterval) - } - } - - // Start the readLoop and flusher go routines, we will wait on both on a reconnect event. - nc.wg.Add(2) - go nc.readLoop() - go nc.flusher() - - // Notify the reader that we are done with the connect handshake, where - // reads were done synchronously and under the connection lock. - nc.br.doneWithConnect() - - return nil -} - -// Main connect function. Will connect to the nats-server. -func (nc *Conn) connect() (bool, error) { - var err error - var connectionEstablished bool - - // Create actual socket connection - // For first connect we walk all servers in the pool and try - // to connect immediately. - nc.mu.Lock() - defer nc.mu.Unlock() - nc.initc = true - // The pool may change inside the loop iteration due to INFO protocol. - for i := 0; i < len(nc.srvPool); i++ { - nc.current = nc.srvPool[i] - - if err = nc.createConn(); err == nil { - // This was moved out of processConnectInit() because - // that function is now invoked from doReconnect() too. - nc.setup() - - err = nc.processConnectInit() - - if err == nil { - nc.current.didConnect = true - nc.current.reconnects = 0 - nc.current.lastErr = nil - break - } else { - nc.mu.Unlock() - nc.close(DISCONNECTED, false, err) - nc.mu.Lock() - // Do not reset nc.current here since it would prevent - // RetryOnFailedConnect to work should this be the last server - // to try before starting doReconnect(). - } - } else { - // Cancel out default connection refused, will trigger the - // No servers error conditional - if strings.Contains(err.Error(), "connection refused") { - err = nil - } - } - } - - if err == nil && nc.status != CONNECTED { - err = ErrNoServers - } - - if err == nil { - connectionEstablished = true - nc.initc = false - } else if nc.Opts.RetryOnFailedConnect { - nc.setup() - nc.changeConnStatus(RECONNECTING) - nc.bw.switchToPending() - go nc.doReconnect(ErrNoServers) - err = nil - } else { - nc.current = nil - } - - return connectionEstablished, err -} - -// This will check to see if the connection should be -// secure. This can be dictated from either end and should -// only be called after the INIT protocol has been received. -func (nc *Conn) checkForSecure() error { - // Check to see if we need to engage TLS - o := nc.Opts - - // Check for mismatch in setups - if o.Secure && !nc.info.TLSRequired && !nc.info.TLSAvailable { - return ErrSecureConnWanted - } else if nc.info.TLSRequired && !o.Secure { - // Switch to Secure since server needs TLS. - o.Secure = true - } - - if o.Secure { - // If TLS handshake first is true, we have already done - // the handshake, so we are done here. - if o.TLSHandshakeFirst { - return nil - } - // Need to rewrap with bufio - if err := nc.makeTLSConn(); err != nil { - return err - } - } - return nil -} - -// processExpectedInfo will look for the expected first INFO message -// sent when a connection is established. The lock should be held entering. -func (nc *Conn) processExpectedInfo() error { - - c := &control{} - - // Read the protocol - err := nc.readOp(c) - if err != nil { - return err - } - - // The nats protocol should send INFO first always. - if c.op != _INFO_OP_ { - return ErrNoInfoReceived - } - - // Parse the protocol - if err := nc.processInfo(c.args); err != nil { - return err - } - - if nc.Opts.Nkey != "" && nc.info.Nonce == "" { - return ErrNkeysNotSupported - } - - // For websocket connections, we already switched to TLS if need be, - // so we are done here. - if nc.ws { - return nil - } - - return nc.checkForSecure() -} - -// Sends a protocol control message by queuing into the bufio writer -// and kicking the flush Go routine. These writes are protected. -func (nc *Conn) sendProto(proto string) { - nc.mu.Lock() - nc.bw.appendString(proto) - nc.kickFlusher() - nc.mu.Unlock() -} - -// Generate a connect protocol message, issuing user/password if -// applicable. The lock is assumed to be held upon entering. -func (nc *Conn) connectProto() (string, error) { - o := nc.Opts - var nkey, sig, user, pass, token, ujwt string - u := nc.current.url.User - if u != nil { - // if no password, assume username is authToken - if _, ok := u.Password(); !ok { - token = u.Username() - } else { - user = u.Username() - pass, _ = u.Password() - } - } else { - // Take from options (possibly all empty strings) - user = o.User - pass = o.Password - token = o.Token - nkey = o.Nkey - } - - // Look for user jwt. - if o.UserJWT != nil { - if jwt, err := o.UserJWT(); err != nil { - return _EMPTY_, err - } else { - ujwt = jwt - } - if nkey != _EMPTY_ { - return _EMPTY_, ErrNkeyAndUser - } - } - - if ujwt != _EMPTY_ || nkey != _EMPTY_ { - if o.SignatureCB == nil { - if ujwt == _EMPTY_ { - return _EMPTY_, ErrNkeyButNoSigCB - } - return _EMPTY_, ErrUserButNoSigCB - } - sigraw, err := o.SignatureCB([]byte(nc.info.Nonce)) - if err != nil { - return _EMPTY_, fmt.Errorf("error signing nonce: %w", err) - } - sig = base64.RawURLEncoding.EncodeToString(sigraw) - } - - if nc.Opts.TokenHandler != nil { - if token != _EMPTY_ { - return _EMPTY_, ErrTokenAlreadySet - } - token = nc.Opts.TokenHandler() - } - - // If our server does not support headers then we can't do them or no responders. - hdrs := nc.info.Headers - cinfo := connectInfo{o.Verbose, o.Pedantic, ujwt, nkey, sig, user, pass, token, - o.Secure, o.Name, LangString, Version, clientProtoInfo, !o.NoEcho, hdrs, hdrs} - - b, err := json.Marshal(cinfo) - if err != nil { - return _EMPTY_, ErrJsonParse - } - - // Check if NoEcho is set and we have a server that supports it. - if o.NoEcho && nc.info.Proto < 1 { - return _EMPTY_, ErrNoEchoNotSupported - } - - return fmt.Sprintf(connectProto, b), nil -} - -// normalizeErr removes the prefix -ERR, trim spaces and remove the quotes. -func normalizeErr(line string) string { - s := strings.TrimSpace(strings.TrimPrefix(line, _ERR_OP_)) - s = strings.TrimLeft(strings.TrimRight(s, "'"), "'") - return s -} - -// natsProtoErr represents an -ERR protocol message sent by the server. -type natsProtoErr struct { - description string -} - -func (nerr *natsProtoErr) Error() string { - return fmt.Sprintf("nats: %s", nerr.description) -} - -func (nerr *natsProtoErr) Is(err error) bool { - return strings.ToLower(nerr.Error()) == err.Error() -} - -// Send a connect protocol message to the server, issue user/password if -// applicable. Will wait for a flush to return from the server for error -// processing. -func (nc *Conn) sendConnect() error { - // Construct the CONNECT protocol string - cProto, err := nc.connectProto() - if err != nil { - if !nc.initc && nc.Opts.AsyncErrorCB != nil { - nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, err) }) - } - return err - } - - // Write the protocol and PING directly to the underlying writer. - if err := nc.bw.writeDirect(cProto, pingProto); err != nil { - return err - } - - // We don't want to read more than we need here, otherwise - // we would need to transfer the excess read data to the readLoop. - // Since in normal situations we just are looking for a PONG\r\n, - // reading byte-by-byte here is ok. - proto, err := nc.readProto() - if err != nil { - if !nc.initc && nc.Opts.AsyncErrorCB != nil { - nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, err) }) - } - return err - } - - // If opts.Verbose is set, handle +OK - if nc.Opts.Verbose && proto == okProto { - // Read the rest now... - proto, err = nc.readProto() - if err != nil { - if !nc.initc && nc.Opts.AsyncErrorCB != nil { - nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, err) }) - } - return err - } - } - - // We expect a PONG - if proto != pongProto { - // But it could be something else, like -ERR - - // Since we no longer use ReadLine(), trim the trailing "\r\n" - proto = strings.TrimRight(proto, "\r\n") - - // If it's a server error... - if strings.HasPrefix(proto, _ERR_OP_) { - // Remove -ERR, trim spaces and quotes, and convert to lower case. - proto = normalizeErr(proto) - - // Check if this is an auth error - if authErr := checkAuthError(strings.ToLower(proto)); authErr != nil { - // This will schedule an async error if we are in reconnect, - // and keep track of the auth error for the current server. - // If we have got the same error twice, this sets nc.ar to true to - // indicate that the reconnect should be aborted (will be checked - // in doReconnect()). - nc.processAuthError(authErr) - } - return &natsProtoErr{proto} - } - - // Notify that we got an unexpected protocol. - return fmt.Errorf("nats: expected '%s', got '%s'", _PONG_OP_, proto) - } - - // This is where we are truly connected. - nc.changeConnStatus(CONNECTED) - - return nil -} - -// reads a protocol line. -func (nc *Conn) readProto() (string, error) { - return nc.br.ReadString('\n') -} - -// A control protocol line. -type control struct { - op, args string -} - -// Read a control line and process the intended op. -func (nc *Conn) readOp(c *control) error { - line, err := nc.readProto() - if err != nil { - return err - } - parseControl(line, c) - return nil -} - -// Parse a control line from the server. -func parseControl(line string, c *control) { - toks := strings.SplitN(line, _SPC_, 2) - if len(toks) == 1 { - c.op = strings.TrimSpace(toks[0]) - c.args = _EMPTY_ - } else if len(toks) == 2 { - c.op, c.args = strings.TrimSpace(toks[0]), strings.TrimSpace(toks[1]) - } else { - c.op = _EMPTY_ - } -} - -// flushReconnectPendingItems will push the pending items that were -// gathered while we were in a RECONNECTING state to the socket. -func (nc *Conn) flushReconnectPendingItems() error { - return nc.bw.flushPendingBuffer() -} - -// Stops the ping timer if set. -// Connection lock is held on entry. -func (nc *Conn) stopPingTimer() { - if nc.ptmr != nil { - nc.ptmr.Stop() - } -} - -// Try to reconnect using the option parameters. -// This function assumes we are allowed to reconnect. -func (nc *Conn) doReconnect(err error) { - // We want to make sure we have the other watchers shutdown properly - // here before we proceed past this point. - nc.waitForExits() - - // FIXME(dlc) - We have an issue here if we have - // outstanding flush points (pongs) and they were not - // sent out, but are still in the pipe. - - // Hold the lock manually and release where needed below, - // can't do defer here. - nc.mu.Lock() - - // Clear any errors. - nc.err = nil - // Perform appropriate callback if needed for a disconnect. - // DisconnectedErrCB has priority over deprecated DisconnectedCB - if !nc.initc { - if nc.Opts.DisconnectedErrCB != nil { - nc.ach.push(func() { nc.Opts.DisconnectedErrCB(nc, err) }) - } else if nc.Opts.DisconnectedCB != nil { - nc.ach.push(func() { nc.Opts.DisconnectedCB(nc) }) - } - } - - // This is used to wait on go routines exit if we start them in the loop - // but an error occurs after that. - waitForGoRoutines := false - var rt *time.Timer - // Channel used to kick routine out of sleep when conn is closed. - rqch := nc.rqch - // Counter that is increased when the whole list of servers has been tried. - var wlf int - - var jitter time.Duration - var rw time.Duration - // If a custom reconnect delay handler is set, this takes precedence. - crd := nc.Opts.CustomReconnectDelayCB - if crd == nil { - rw = nc.Opts.ReconnectWait - // TODO: since we sleep only after the whole list has been tried, we can't - // rely on individual *srv to know if it is a TLS or non-TLS url. - // We have to pick which type of jitter to use, for now, we use these hints: - jitter = nc.Opts.ReconnectJitter - if nc.Opts.Secure || nc.Opts.TLSConfig != nil { - jitter = nc.Opts.ReconnectJitterTLS - } - } - - for i := 0; len(nc.srvPool) > 0; { - cur, err := nc.selectNextServer() - if err != nil { - nc.err = err - break - } - - doSleep := i+1 >= len(nc.srvPool) - nc.mu.Unlock() - - if !doSleep { - i++ - // Release the lock to give a chance to a concurrent nc.Close() to break the loop. - runtime.Gosched() - } else { - i = 0 - var st time.Duration - if crd != nil { - wlf++ - st = crd(wlf) - } else { - st = rw - if jitter > 0 { - st += time.Duration(rand.Int63n(int64(jitter))) - } - } - if rt == nil { - rt = time.NewTimer(st) - } else { - rt.Reset(st) - } - select { - case <-rqch: - rt.Stop() - case <-rt.C: - } - } - // If the readLoop, etc.. go routines were started, wait for them to complete. - if waitForGoRoutines { - nc.waitForExits() - waitForGoRoutines = false - } - nc.mu.Lock() - - // Check if we have been closed first. - if nc.isClosed() { - break - } - - // Mark that we tried a reconnect - cur.reconnects++ - - // Try to create a new connection - err = nc.createConn() - - // Not yet connected, retry... - // Continue to hold the lock - if err != nil { - nc.err = nil - continue - } - - // We are reconnected - nc.Reconnects++ - - // Process connect logic - if nc.err = nc.processConnectInit(); nc.err != nil { - // Check if we should abort reconnect. If so, break out - // of the loop and connection will be closed. - if nc.ar { - break - } - nc.changeConnStatus(RECONNECTING) - continue - } - - // Clear possible lastErr under the connection lock after - // a successful processConnectInit(). - nc.current.lastErr = nil - - // Clear out server stats for the server we connected to.. - cur.didConnect = true - cur.reconnects = 0 - - // Send existing subscription state - nc.resendSubscriptions() - - // Now send off and clear pending buffer - nc.err = nc.flushReconnectPendingItems() - if nc.err != nil { - nc.changeConnStatus(RECONNECTING) - // Stop the ping timer (if set) - nc.stopPingTimer() - // Since processConnectInit() returned without error, the - // go routines were started, so wait for them to return - // on the next iteration (after releasing the lock). - waitForGoRoutines = true - continue - } - - // Done with the pending buffer - nc.bw.doneWithPending() - - // This is where we are truly connected. - nc.status = CONNECTED - - // If we are here with a retry on failed connect, indicate that the - // initial connect is now complete. - nc.initc = false - - // Queue up the reconnect callback. - if nc.Opts.ReconnectedCB != nil { - nc.ach.push(func() { nc.Opts.ReconnectedCB(nc) }) - } - - // Release lock here, we will return below. - nc.mu.Unlock() - - // Make sure to flush everything - nc.Flush() - - return - } - - // Call into close.. We have no servers left.. - if nc.err == nil { - nc.err = ErrNoServers - } - nc.mu.Unlock() - nc.close(CLOSED, true, nil) -} - -// processOpErr handles errors from reading or parsing the protocol. -// The lock should not be held entering this function. -func (nc *Conn) processOpErr(err error) { - nc.mu.Lock() - if nc.isConnecting() || nc.isClosed() || nc.isReconnecting() { - nc.mu.Unlock() - return - } - - if nc.Opts.AllowReconnect && nc.status == CONNECTED { - // Set our new status - nc.changeConnStatus(RECONNECTING) - // Stop ping timer if set - nc.stopPingTimer() - if nc.conn != nil { - nc.conn.Close() - nc.conn = nil - } - - // Create pending buffer before reconnecting. - nc.bw.switchToPending() - - // Clear any queued pongs, e.g. pending flush calls. - nc.clearPendingFlushCalls() - - go nc.doReconnect(err) - nc.mu.Unlock() - return - } - - nc.changeConnStatus(DISCONNECTED) - nc.err = err - nc.mu.Unlock() - nc.close(CLOSED, true, nil) -} - -// dispatch is responsible for calling any async callbacks -func (ac *asyncCallbacksHandler) asyncCBDispatcher() { - for { - ac.mu.Lock() - // Protect for spurious wakeups. We should get out of the - // wait only if there is an element to pop from the list. - for ac.head == nil { - ac.cond.Wait() - } - cur := ac.head - ac.head = cur.next - if cur == ac.tail { - ac.tail = nil - } - ac.mu.Unlock() - - // This signals that the dispatcher has been closed and all - // previous callbacks have been dispatched. - if cur.f == nil { - return - } - // Invoke callback outside of handler's lock - cur.f() - } -} - -// Add the given function to the tail of the list and -// signals the dispatcher. -func (ac *asyncCallbacksHandler) push(f func()) { - ac.pushOrClose(f, false) -} - -// Signals that we are closing... -func (ac *asyncCallbacksHandler) close() { - ac.pushOrClose(nil, true) -} - -// Add the given function to the tail of the list and -// signals the dispatcher. -func (ac *asyncCallbacksHandler) pushOrClose(f func(), close bool) { - ac.mu.Lock() - defer ac.mu.Unlock() - // Make sure that library is not calling push with nil function, - // since this is used to notify the dispatcher that it should stop. - if !close && f == nil { - panic("pushing a nil callback") - } - cb := &asyncCB{f: f} - if ac.tail != nil { - ac.tail.next = cb - } else { - ac.head = cb - } - ac.tail = cb - if close { - ac.cond.Broadcast() - } else { - ac.cond.Signal() - } -} - -// readLoop() will sit on the socket reading and processing the -// protocol from the server. It will dispatch appropriately based -// on the op type. -func (nc *Conn) readLoop() { - // Release the wait group on exit - defer nc.wg.Done() - - // Create a parseState if needed. - nc.mu.Lock() - if nc.ps == nil { - nc.ps = &parseState{} - } - conn := nc.conn - br := nc.br - nc.mu.Unlock() - - if conn == nil { - return - } - - for { - buf, err := br.Read() - if err == nil { - // With websocket, it is possible that there is no error but - // also no buffer returned (either WS control message or read of a - // partial compressed message). We could call parse(buf) which - // would ignore an empty buffer, but simply go back to top of the loop. - if len(buf) == 0 { - continue - } - err = nc.parse(buf) - } - if err != nil { - nc.processOpErr(err) - break - } - } - // Clear the parseState here.. - nc.mu.Lock() - nc.ps = nil - nc.mu.Unlock() -} - -// waitForMsgs waits on the conditional shared with readLoop and processMsg. -// It is used to deliver messages to asynchronous subscribers. -func (nc *Conn) waitForMsgs(s *Subscription) { - var closed bool - var delivered, max uint64 - - // Used to account for adjustments to sub.pBytes when we wrap back around. - msgLen := -1 - - for { - s.mu.Lock() - // Do accounting for last msg delivered here so we only lock once - // and drain state trips after callback has returned. - if msgLen >= 0 { - s.pMsgs-- - s.pBytes -= msgLen - msgLen = -1 - } - - if s.pHead == nil && !s.closed { - s.pCond.Wait() - } - // Pop the msg off the list - m := s.pHead - if m != nil { - s.pHead = m.next - if s.pHead == nil { - s.pTail = nil - } - if m.barrier != nil { - s.mu.Unlock() - if atomic.AddInt64(&m.barrier.refs, -1) == 0 { - m.barrier.f() - } - continue - } - msgLen = len(m.Data) - } - mcb := s.mcb - max = s.max - closed = s.closed - var fcReply string - if !s.closed { - s.delivered++ - delivered = s.delivered - if s.jsi != nil { - fcReply = s.checkForFlowControlResponse() - } - } - s.mu.Unlock() - - // Respond to flow control if applicable - if fcReply != _EMPTY_ { - nc.Publish(fcReply, nil) - } - - if closed { - break - } - - // Deliver the message. - if m != nil && (max == 0 || delivered <= max) { - mcb(m) - } - // If we have hit the max for delivered msgs, remove sub. - if max > 0 && delivered >= max { - nc.mu.Lock() - nc.removeSub(s) - nc.mu.Unlock() - break - } - } - // Check for barrier messages - s.mu.Lock() - for m := s.pHead; m != nil; m = s.pHead { - if m.barrier != nil { - s.mu.Unlock() - if atomic.AddInt64(&m.barrier.refs, -1) == 0 { - m.barrier.f() - } - s.mu.Lock() - } - s.pHead = m.next - } - // Now check for pDone - done := s.pDone - s.mu.Unlock() - - if done != nil { - done(s.Subject) - } -} - -// Used for debugging and simulating loss for certain tests. -// Return what is to be used. If we return nil the message will be dropped. -type msgFilter func(m *Msg) *Msg - -// processMsg is called by parse and will place the msg on the -// appropriate channel/pending queue for processing. If the channel is full, -// or the pending queue is over the pending limits, the connection is -// considered a slow consumer. -func (nc *Conn) processMsg(data []byte) { - // Stats - atomic.AddUint64(&nc.InMsgs, 1) - atomic.AddUint64(&nc.InBytes, uint64(len(data))) - - // Don't lock the connection to avoid server cutting us off if the - // flusher is holding the connection lock, trying to send to the server - // that is itself trying to send data to us. - nc.subsMu.RLock() - sub := nc.subs[nc.ps.ma.sid] - var mf msgFilter - if nc.filters != nil { - mf = nc.filters[string(nc.ps.ma.subject)] - } - nc.subsMu.RUnlock() - - if sub == nil { - return - } - - // Copy them into string - subj := string(nc.ps.ma.subject) - reply := string(nc.ps.ma.reply) - - // Doing message create outside of the sub's lock to reduce contention. - // It's possible that we end-up not using the message, but that's ok. - - // FIXME(dlc): Need to copy, should/can do COW? - var msgPayload = data - if !nc.ps.msgCopied { - msgPayload = make([]byte, len(data)) - copy(msgPayload, data) - } - - // Check if we have headers encoded here. - var h Header - var err error - var ctrlMsg bool - var ctrlType int - var fcReply string - - if nc.ps.ma.hdr > 0 { - hbuf := msgPayload[:nc.ps.ma.hdr] - msgPayload = msgPayload[nc.ps.ma.hdr:] - h, err = DecodeHeadersMsg(hbuf) - if err != nil { - // We will pass the message through but send async error. - nc.mu.Lock() - nc.err = ErrBadHeaderMsg - if nc.Opts.AsyncErrorCB != nil { - nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, sub, ErrBadHeaderMsg) }) - } - nc.mu.Unlock() - } - } - - // FIXME(dlc): Should we recycle these containers? - m := &Msg{ - Subject: subj, - Reply: reply, - Header: h, - Data: msgPayload, - Sub: sub, - wsz: len(data) + len(subj) + len(reply), - } - - // Check for message filters. - if mf != nil { - if m = mf(m); m == nil { - // Drop message. - return - } - } - - sub.mu.Lock() - - // Check if closed. - if sub.closed { - sub.mu.Unlock() - return - } - - // Skip flow control messages in case of using a JetStream context. - jsi := sub.jsi - if jsi != nil { - // There has to be a header for it to be a control message. - if h != nil { - ctrlMsg, ctrlType = isJSControlMessage(m) - if ctrlMsg && ctrlType == jsCtrlHB { - // Check if the heartbeat has a "Consumer Stalled" header, if - // so, the value is the FC reply to send a nil message to. - // We will send it at the end of this function. - fcReply = m.Header.Get(consumerStalledHdr) - } - } - // Check for ordered consumer here. If checkOrderedMsgs returns true that means it detected a gap. - if !ctrlMsg && jsi.ordered && sub.checkOrderedMsgs(m) { - sub.mu.Unlock() - return - } - } - - // Skip processing if this is a control message and - // if not a pull consumer heartbeat. For pull consumers, - // heartbeats have to be handled on per request basis. - if !ctrlMsg || (jsi != nil && jsi.pull) { - var chanSubCheckFC bool - // Subscription internal stats (applicable only for non ChanSubscription's) - if sub.typ != ChanSubscription { - sub.pMsgs++ - if sub.pMsgs > sub.pMsgsMax { - sub.pMsgsMax = sub.pMsgs - } - sub.pBytes += len(m.Data) - if sub.pBytes > sub.pBytesMax { - sub.pBytesMax = sub.pBytes - } - - // Check for a Slow Consumer - if (sub.pMsgsLimit > 0 && sub.pMsgs > sub.pMsgsLimit) || - (sub.pBytesLimit > 0 && sub.pBytes > sub.pBytesLimit) { - goto slowConsumer - } - } else if jsi != nil { - chanSubCheckFC = true - } - - // We have two modes of delivery. One is the channel, used by channel - // subscribers and syncSubscribers, the other is a linked list for async. - if sub.mch != nil { - select { - case sub.mch <- m: - default: - goto slowConsumer - } - } else { - // Push onto the async pList - if sub.pHead == nil { - sub.pHead = m - sub.pTail = m - if sub.pCond != nil { - sub.pCond.Signal() - } - } else { - sub.pTail.next = m - sub.pTail = m - } - } - if jsi != nil { - // Store the ACK metadata from the message to - // compare later on with the received heartbeat. - sub.trackSequences(m.Reply) - if chanSubCheckFC { - // For ChanSubscription, since we can't call this when a message - // is "delivered" (since user is pull from their own channel), - // we have a go routine that does this check, however, we do it - // also here to make it much more responsive. The go routine is - // really to avoid stalling when there is no new messages coming. - fcReply = sub.checkForFlowControlResponse() - } - } - } else if ctrlType == jsCtrlFC && m.Reply != _EMPTY_ { - // This is a flow control message. - // We will schedule the send of the FC reply once we have delivered the - // DATA message that was received before this flow control message, which - // has sequence `jsi.fciseq`. However, it is possible that this message - // has already been delivered, in that case, we need to send the FC reply now. - if sub.getJSDelivered() >= jsi.fciseq { - fcReply = m.Reply - } else { - // Schedule a reply after the previous message is delivered. - sub.scheduleFlowControlResponse(m.Reply) - } - } - - // Clear any SlowConsumer status. - sub.sc = false - sub.mu.Unlock() - - if fcReply != _EMPTY_ { - nc.Publish(fcReply, nil) - } - - // Handle control heartbeat messages. - if ctrlMsg && ctrlType == jsCtrlHB && m.Reply == _EMPTY_ { - nc.checkForSequenceMismatch(m, sub, jsi) - } - - return - -slowConsumer: - sub.dropped++ - sc := !sub.sc - sub.sc = true - // Undo stats from above - if sub.typ != ChanSubscription { - sub.pMsgs-- - sub.pBytes -= len(m.Data) - } - sub.mu.Unlock() - if sc { - // Now we need connection's lock and we may end-up in the situation - // that we were trying to avoid, except that in this case, the client - // is already experiencing client-side slow consumer situation. - nc.mu.Lock() - nc.err = ErrSlowConsumer - if nc.Opts.AsyncErrorCB != nil { - nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, sub, ErrSlowConsumer) }) - } - nc.mu.Unlock() - } -} - -// processPermissionsViolation is called when the server signals a subject -// permissions violation on either publish or subscribe. -func (nc *Conn) processPermissionsViolation(err string) { - nc.mu.Lock() - // create error here so we can pass it as a closure to the async cb dispatcher. - e := errors.New("nats: " + err) - nc.err = e - if nc.Opts.AsyncErrorCB != nil { - nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, e) }) - } - nc.mu.Unlock() -} - -// processAuthError generally processing for auth errors. We want to do retries -// unless we get the same error again. This allows us for instance to swap credentials -// and have the app reconnect, but if nothing is changing we should bail. -// This function will return true if the connection should be closed, false otherwise. -// Connection lock is held on entry -func (nc *Conn) processAuthError(err error) bool { - nc.err = err - if !nc.initc && nc.Opts.AsyncErrorCB != nil { - nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, err) }) - } - // We should give up if we tried twice on this server and got the - // same error. This behavior can be modified using IgnoreAuthErrorAbort. - if nc.current.lastErr == err && !nc.Opts.IgnoreAuthErrorAbort { - nc.ar = true - } else { - nc.current.lastErr = err - } - return nc.ar -} - -// flusher is a separate Go routine that will process flush requests for the write -// bufio. This allows coalescing of writes to the underlying socket. -func (nc *Conn) flusher() { - // Release the wait group - defer nc.wg.Done() - - // snapshot the bw and conn since they can change from underneath of us. - nc.mu.Lock() - bw := nc.bw - conn := nc.conn - fch := nc.fch - nc.mu.Unlock() - - if conn == nil || bw == nil { - return - } - - for { - if _, ok := <-fch; !ok { - return - } - nc.mu.Lock() - - // Check to see if we should bail out. - if !nc.isConnected() || nc.isConnecting() || conn != nc.conn { - nc.mu.Unlock() - return - } - if bw.buffered() > 0 { - if err := bw.flush(); err != nil { - if nc.err == nil { - nc.err = err - } - if nc.Opts.AsyncErrorCB != nil { - nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, err) }) - } - } - } - nc.mu.Unlock() - } -} - -// processPing will send an immediate pong protocol response to the -// server. The server uses this mechanism to detect dead clients. -func (nc *Conn) processPing() { - nc.sendProto(pongProto) -} - -// processPong is used to process responses to the client's ping -// messages. We use pings for the flush mechanism as well. -func (nc *Conn) processPong() { - var ch chan struct{} - - nc.mu.Lock() - if len(nc.pongs) > 0 { - ch = nc.pongs[0] - nc.pongs = append(nc.pongs[:0], nc.pongs[1:]...) - } - nc.pout = 0 - nc.mu.Unlock() - if ch != nil { - ch <- struct{}{} - } -} - -// processOK is a placeholder for processing OK messages. -func (nc *Conn) processOK() { - // do nothing -} - -// processInfo is used to parse the info messages sent -// from the server. -// This function may update the server pool. -func (nc *Conn) processInfo(info string) error { - if info == _EMPTY_ { - return nil - } - var ncInfo serverInfo - if err := json.Unmarshal([]byte(info), &ncInfo); err != nil { - return err - } - - // Copy content into connection's info structure. - nc.info = ncInfo - // The array could be empty/not present on initial connect, - // if advertise is disabled on that server, or servers that - // did not include themselves in the async INFO protocol. - // If empty, do not remove the implicit servers from the pool. - if len(nc.info.ConnectURLs) == 0 { - if !nc.initc && ncInfo.LameDuckMode && nc.Opts.LameDuckModeHandler != nil { - nc.ach.push(func() { nc.Opts.LameDuckModeHandler(nc) }) - } - return nil - } - // Note about pool randomization: when the pool was first created, - // it was randomized (if allowed). We keep the order the same (removing - // implicit servers that are no longer sent to us). New URLs are sent - // to us in no specific order so don't need extra randomization. - hasNew := false - // This is what we got from the server we are connected to. - urls := nc.info.ConnectURLs - // Transform that to a map for easy lookups - tmp := make(map[string]struct{}, len(urls)) - for _, curl := range urls { - tmp[curl] = struct{}{} - } - // Walk the pool and removed the implicit servers that are no longer in the - // given array/map - sp := nc.srvPool - for i := 0; i < len(sp); i++ { - srv := sp[i] - curl := srv.url.Host - // Check if this URL is in the INFO protocol - _, inInfo := tmp[curl] - // Remove from the temp map so that at the end we are left with only - // new (or restarted) servers that need to be added to the pool. - delete(tmp, curl) - // Keep servers that were set through Options, but also the one that - // we are currently connected to (even if it is a discovered server). - if !srv.isImplicit || srv.url == nc.current.url { - continue - } - if !inInfo { - // Remove from server pool. Keep current order. - copy(sp[i:], sp[i+1:]) - nc.srvPool = sp[:len(sp)-1] - sp = nc.srvPool - i-- - } - } - // Figure out if we should save off the current non-IP hostname if we encounter a bare IP. - saveTLS := nc.current != nil && !hostIsIP(nc.current.url) - - // If there are any left in the tmp map, these are new (or restarted) servers - // and need to be added to the pool. - for curl := range tmp { - // Before adding, check if this is a new (as in never seen) URL. - // This is used to figure out if we invoke the DiscoveredServersCB - if _, present := nc.urls[curl]; !present { - hasNew = true - } - nc.addURLToPool(fmt.Sprintf("%s://%s", nc.connScheme(), curl), true, saveTLS) - } - if hasNew { - // Randomize the pool if allowed but leave the first URL in place. - if !nc.Opts.NoRandomize { - nc.shufflePool(1) - } - if !nc.initc && nc.Opts.DiscoveredServersCB != nil { - nc.ach.push(func() { nc.Opts.DiscoveredServersCB(nc) }) - } - } - if !nc.initc && ncInfo.LameDuckMode && nc.Opts.LameDuckModeHandler != nil { - nc.ach.push(func() { nc.Opts.LameDuckModeHandler(nc) }) - } - return nil -} - -// processAsyncInfo does the same than processInfo, but is called -// from the parser. Calls processInfo under connection's lock -// protection. -func (nc *Conn) processAsyncInfo(info []byte) { - nc.mu.Lock() - // Ignore errors, we will simply not update the server pool... - nc.processInfo(string(info)) - nc.mu.Unlock() -} - -// LastError reports the last error encountered via the connection. -// It can be used reliably within ClosedCB in order to find out reason -// why connection was closed for example. -func (nc *Conn) LastError() error { - if nc == nil { - return ErrInvalidConnection - } - nc.mu.RLock() - err := nc.err - nc.mu.RUnlock() - return err -} - -// Check if the given error string is an auth error, and if so returns -// the corresponding ErrXXX error, nil otherwise -func checkAuthError(e string) error { - if strings.HasPrefix(e, AUTHORIZATION_ERR) { - return ErrAuthorization - } - if strings.HasPrefix(e, AUTHENTICATION_EXPIRED_ERR) { - return ErrAuthExpired - } - if strings.HasPrefix(e, AUTHENTICATION_REVOKED_ERR) { - return ErrAuthRevoked - } - if strings.HasPrefix(e, ACCOUNT_AUTHENTICATION_EXPIRED_ERR) { - return ErrAccountAuthExpired - } - return nil -} - -// processErr processes any error messages from the server and -// sets the connection's LastError. -func (nc *Conn) processErr(ie string) { - // Trim, remove quotes - ne := normalizeErr(ie) - // convert to lower case. - e := strings.ToLower(ne) - - close := false - - // FIXME(dlc) - process Slow Consumer signals special. - if e == STALE_CONNECTION { - nc.processOpErr(ErrStaleConnection) - } else if e == MAX_CONNECTIONS_ERR { - nc.processOpErr(ErrMaxConnectionsExceeded) - } else if strings.HasPrefix(e, PERMISSIONS_ERR) { - nc.processPermissionsViolation(ne) - } else if authErr := checkAuthError(e); authErr != nil { - nc.mu.Lock() - close = nc.processAuthError(authErr) - nc.mu.Unlock() - } else { - close = true - nc.mu.Lock() - nc.err = errors.New("nats: " + ne) - nc.mu.Unlock() - } - if close { - nc.close(CLOSED, true, nil) - } -} - -// kickFlusher will send a bool on a channel to kick the -// flush Go routine to flush data to the server. -func (nc *Conn) kickFlusher() { - if nc.bw != nil { - select { - case nc.fch <- struct{}{}: - default: - } - } -} - -// Publish publishes the data argument to the given subject. The data -// argument is left untouched and needs to be correctly interpreted on -// the receiver. -func (nc *Conn) Publish(subj string, data []byte) error { - return nc.publish(subj, _EMPTY_, nil, data) -} - -// Header represents the optional Header for a NATS message, -// based on the implementation of http.Header. -type Header map[string][]string - -// Add adds the key, value pair to the header. It is case-sensitive -// and appends to any existing values associated with key. -func (h Header) Add(key, value string) { - h[key] = append(h[key], value) -} - -// Set sets the header entries associated with key to the single -// element value. It is case-sensitive and replaces any existing -// values associated with key. -func (h Header) Set(key, value string) { - h[key] = []string{value} -} - -// Get gets the first value associated with the given key. -// It is case-sensitive. -func (h Header) Get(key string) string { - if h == nil { - return _EMPTY_ - } - if v := h[key]; v != nil { - return v[0] - } - return _EMPTY_ -} - -// Values returns all values associated with the given key. -// It is case-sensitive. -func (h Header) Values(key string) []string { - return h[key] -} - -// Del deletes the values associated with a key. -// It is case-sensitive. -func (h Header) Del(key string) { - delete(h, key) -} - -// NewMsg creates a message for publishing that will use headers. -func NewMsg(subject string) *Msg { - return &Msg{ - Subject: subject, - Header: make(Header), - } -} - -const ( - hdrLine = "NATS/1.0\r\n" - crlf = "\r\n" - hdrPreEnd = len(hdrLine) - len(crlf) - statusHdr = "Status" - descrHdr = "Description" - lastConsumerSeqHdr = "Nats-Last-Consumer" - lastStreamSeqHdr = "Nats-Last-Stream" - consumerStalledHdr = "Nats-Consumer-Stalled" - noResponders = "503" - noMessagesSts = "404" - reqTimeoutSts = "408" - jetStream409Sts = "409" - controlMsg = "100" - statusLen = 3 // e.g. 20x, 40x, 50x -) - -// DecodeHeadersMsg will decode and headers. -func DecodeHeadersMsg(data []byte) (Header, error) { - br := bufio.NewReaderSize(bytes.NewReader(data), 128) - tp := textproto.NewReader(br) - l, err := tp.ReadLine() - if err != nil || len(l) < hdrPreEnd || l[:hdrPreEnd] != hdrLine[:hdrPreEnd] { - return nil, ErrBadHeaderMsg - } - - mh, err := readMIMEHeader(tp) - if err != nil { - return nil, err - } - - // Check if we have an inlined status. - if len(l) > hdrPreEnd { - var description string - status := strings.TrimSpace(l[hdrPreEnd:]) - if len(status) != statusLen { - description = strings.TrimSpace(status[statusLen:]) - status = status[:statusLen] - } - mh.Add(statusHdr, status) - if len(description) > 0 { - mh.Add(descrHdr, description) - } - } - return Header(mh), nil -} - -// readMIMEHeader returns a MIMEHeader that preserves the -// original case of the MIME header, based on the implementation -// of textproto.ReadMIMEHeader. -// -// https://golang.org/pkg/net/textproto/#Reader.ReadMIMEHeader -func readMIMEHeader(tp *textproto.Reader) (textproto.MIMEHeader, error) { - m := make(textproto.MIMEHeader) - for { - kv, err := tp.ReadLine() - if len(kv) == 0 { - return m, err - } - - // Process key fetching original case. - i := bytes.IndexByte([]byte(kv), ':') - if i < 0 { - return nil, ErrBadHeaderMsg - } - key := kv[:i] - if key == "" { - // Skip empty keys. - continue - } - i++ - for i < len(kv) && (kv[i] == ' ' || kv[i] == '\t') { - i++ - } - value := string(kv[i:]) - m[key] = append(m[key], value) - if err != nil { - return m, err - } - } -} - -// PublishMsg publishes the Msg structure, which includes the -// Subject, an optional Reply and an optional Data field. -func (nc *Conn) PublishMsg(m *Msg) error { - if m == nil { - return ErrInvalidMsg - } - hdr, err := m.headerBytes() - if err != nil { - return err - } - return nc.publish(m.Subject, m.Reply, hdr, m.Data) -} - -// PublishRequest will perform a Publish() expecting a response on the -// reply subject. Use Request() for automatically waiting for a response -// inline. -func (nc *Conn) PublishRequest(subj, reply string, data []byte) error { - return nc.publish(subj, reply, nil, data) -} - -// Used for handrolled Itoa -const digits = "0123456789" - -// publish is the internal function to publish messages to a nats-server. -// Sends a protocol data message by queuing into the bufio writer -// and kicking the flush go routine. These writes should be protected. -func (nc *Conn) publish(subj, reply string, hdr, data []byte) error { - if nc == nil { - return ErrInvalidConnection - } - if subj == "" { - return ErrBadSubject - } - nc.mu.Lock() - - // Check if headers attempted to be sent to server that does not support them. - if len(hdr) > 0 && !nc.info.Headers { - nc.mu.Unlock() - return ErrHeadersNotSupported - } - - if nc.isClosed() { - nc.mu.Unlock() - return ErrConnectionClosed - } - - if nc.isDrainingPubs() { - nc.mu.Unlock() - return ErrConnectionDraining - } - - // Proactively reject payloads over the threshold set by server. - msgSize := int64(len(data) + len(hdr)) - // Skip this check if we are not yet connected (RetryOnFailedConnect) - if !nc.initc && msgSize > nc.info.MaxPayload { - nc.mu.Unlock() - return ErrMaxPayload - } - - // Check if we are reconnecting, and if so check if - // we have exceeded our reconnect outbound buffer limits. - if nc.bw.atLimitIfUsingPending() { - nc.mu.Unlock() - return ErrReconnectBufExceeded - } - - var mh []byte - if hdr != nil { - mh = nc.scratch[:len(_HPUB_P_)] - } else { - mh = nc.scratch[1:len(_HPUB_P_)] - } - mh = append(mh, subj...) - mh = append(mh, ' ') - if reply != "" { - mh = append(mh, reply...) - mh = append(mh, ' ') - } - - // We could be smarter here, but simple loop is ok, - // just avoid strconv in fast path. - // FIXME(dlc) - Find a better way here. - // msgh = strconv.AppendInt(msgh, int64(len(data)), 10) - // go 1.14 some values strconv faster, may be able to switch over. - - var b [12]byte - var i = len(b) - - if hdr != nil { - if len(hdr) > 0 { - for l := len(hdr); l > 0; l /= 10 { - i-- - b[i] = digits[l%10] - } - } else { - i-- - b[i] = digits[0] - } - mh = append(mh, b[i:]...) - mh = append(mh, ' ') - // reset for below. - i = len(b) - } - - if msgSize > 0 { - for l := msgSize; l > 0; l /= 10 { - i-- - b[i] = digits[l%10] - } - } else { - i-- - b[i] = digits[0] - } - - mh = append(mh, b[i:]...) - mh = append(mh, _CRLF_...) - - if err := nc.bw.appendBufs(mh, hdr, data, _CRLF_BYTES_); err != nil { - nc.mu.Unlock() - return err - } - - nc.OutMsgs++ - nc.OutBytes += uint64(len(data) + len(hdr)) - - if len(nc.fch) == 0 { - nc.kickFlusher() - } - nc.mu.Unlock() - return nil -} - -// respHandler is the global response handler. It will look up -// the appropriate channel based on the last token and place -// the message on the channel if possible. -func (nc *Conn) respHandler(m *Msg) { - nc.mu.Lock() - - // Just return if closed. - if nc.isClosed() { - nc.mu.Unlock() - return - } - - var mch chan *Msg - - // Grab mch - rt := nc.respToken(m.Subject) - if rt != _EMPTY_ { - mch = nc.respMap[rt] - // Delete the key regardless, one response only. - delete(nc.respMap, rt) - } else if len(nc.respMap) == 1 { - // If the server has rewritten the subject, the response token (rt) - // will not match (could be the case with JetStream). If that is the - // case and there is a single entry, use that. - for k, v := range nc.respMap { - mch = v - delete(nc.respMap, k) - break - } - } - nc.mu.Unlock() - - // Don't block, let Request timeout instead, mch is - // buffered and we should delete the key before a - // second response is processed. - select { - case mch <- m: - default: - return - } -} - -// Helper to setup and send new request style requests. Return the chan to receive the response. -func (nc *Conn) createNewRequestAndSend(subj string, hdr, data []byte) (chan *Msg, string, error) { - nc.mu.Lock() - // Do setup for the new style if needed. - if nc.respMap == nil { - nc.initNewResp() - } - // Create new literal Inbox and map to a chan msg. - mch := make(chan *Msg, RequestChanLen) - respInbox := nc.newRespInbox() - token := respInbox[nc.respSubLen:] - - nc.respMap[token] = mch - if nc.respMux == nil { - // Create the response subscription we will use for all new style responses. - // This will be on an _INBOX with an additional terminal token. The subscription - // will be on a wildcard. - s, err := nc.subscribeLocked(nc.respSub, _EMPTY_, nc.respHandler, nil, false, nil) - if err != nil { - nc.mu.Unlock() - return nil, token, err - } - nc.respScanf = strings.Replace(nc.respSub, "*", "%s", -1) - nc.respMux = s - } - nc.mu.Unlock() - - if err := nc.publish(subj, respInbox, hdr, data); err != nil { - return nil, token, err - } - - return mch, token, nil -} - -// RequestMsg will send a request payload including optional headers and deliver -// the response message, or an error, including a timeout if no message was received properly. -func (nc *Conn) RequestMsg(msg *Msg, timeout time.Duration) (*Msg, error) { - if msg == nil { - return nil, ErrInvalidMsg - } - hdr, err := msg.headerBytes() - if err != nil { - return nil, err - } - - return nc.request(msg.Subject, hdr, msg.Data, timeout) -} - -// Request will send a request payload and deliver the response message, -// or an error, including a timeout if no message was received properly. -func (nc *Conn) Request(subj string, data []byte, timeout time.Duration) (*Msg, error) { - return nc.request(subj, nil, data, timeout) -} - -func (nc *Conn) useOldRequestStyle() bool { - nc.mu.RLock() - r := nc.Opts.UseOldRequestStyle - nc.mu.RUnlock() - return r -} - -func (nc *Conn) request(subj string, hdr, data []byte, timeout time.Duration) (*Msg, error) { - if nc == nil { - return nil, ErrInvalidConnection - } - - var m *Msg - var err error - - if nc.useOldRequestStyle() { - m, err = nc.oldRequest(subj, hdr, data, timeout) - } else { - m, err = nc.newRequest(subj, hdr, data, timeout) - } - - // Check for no responder status. - if err == nil && len(m.Data) == 0 && m.Header.Get(statusHdr) == noResponders { - m, err = nil, ErrNoResponders - } - return m, err -} - -func (nc *Conn) newRequest(subj string, hdr, data []byte, timeout time.Duration) (*Msg, error) { - mch, token, err := nc.createNewRequestAndSend(subj, hdr, data) - if err != nil { - return nil, err - } - - t := globalTimerPool.Get(timeout) - defer globalTimerPool.Put(t) - - var ok bool - var msg *Msg - - select { - case msg, ok = <-mch: - if !ok { - return nil, ErrConnectionClosed - } - case <-t.C: - nc.mu.Lock() - delete(nc.respMap, token) - nc.mu.Unlock() - return nil, ErrTimeout - } - - return msg, nil -} - -// oldRequest will create an Inbox and perform a Request() call -// with the Inbox reply and return the first reply received. -// This is optimized for the case of multiple responses. -func (nc *Conn) oldRequest(subj string, hdr, data []byte, timeout time.Duration) (*Msg, error) { - inbox := nc.NewInbox() - ch := make(chan *Msg, RequestChanLen) - - s, err := nc.subscribe(inbox, _EMPTY_, nil, ch, true, nil) - if err != nil { - return nil, err - } - s.AutoUnsubscribe(1) - defer s.Unsubscribe() - - err = nc.publish(subj, inbox, hdr, data) - if err != nil { - return nil, err - } - - return s.NextMsg(timeout) -} - -// InboxPrefix is the prefix for all inbox subjects. -const ( - InboxPrefix = "_INBOX." - inboxPrefixLen = len(InboxPrefix) - replySuffixLen = 8 // Gives us 62^8 - rdigits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" - base = 62 -) - -// NewInbox will return an inbox string which can be used for directed replies from -// subscribers. These are guaranteed to be unique, but can be shared and subscribed -// to by others. -func NewInbox() string { - var b [inboxPrefixLen + nuidSize]byte - pres := b[:inboxPrefixLen] - copy(pres, InboxPrefix) - ns := b[inboxPrefixLen:] - copy(ns, nuid.Next()) - return string(b[:]) -} - -// Create a new inbox that is prefix aware. -func (nc *Conn) NewInbox() string { - if nc.Opts.InboxPrefix == _EMPTY_ { - return NewInbox() - } - - var sb strings.Builder - sb.WriteString(nc.Opts.InboxPrefix) - sb.WriteByte('.') - sb.WriteString(nuid.Next()) - return sb.String() -} - -// Function to init new response structures. -func (nc *Conn) initNewResp() { - nc.respSubPrefix = fmt.Sprintf("%s.", nc.NewInbox()) - nc.respSubLen = len(nc.respSubPrefix) - nc.respSub = fmt.Sprintf("%s*", nc.respSubPrefix) - nc.respMap = make(map[string]chan *Msg) - nc.respRand = rand.New(rand.NewSource(time.Now().UnixNano())) -} - -// newRespInbox creates a new literal response subject -// that will trigger the mux subscription handler. -// Lock should be held. -func (nc *Conn) newRespInbox() string { - if nc.respMap == nil { - nc.initNewResp() - } - - var sb strings.Builder - sb.WriteString(nc.respSubPrefix) - - rn := nc.respRand.Int63() - for i := 0; i < replySuffixLen; i++ { - sb.WriteByte(rdigits[rn%base]) - rn /= base - } - - return sb.String() -} - -// NewRespInbox is the new format used for _INBOX. -func (nc *Conn) NewRespInbox() string { - nc.mu.Lock() - s := nc.newRespInbox() - nc.mu.Unlock() - return s -} - -// respToken will return the last token of a literal response inbox -// which we use for the message channel lookup. This needs to do a -// scan to protect itself against the server changing the subject. -// Lock should be held. -func (nc *Conn) respToken(respInbox string) string { - var token string - n, err := fmt.Sscanf(respInbox, nc.respScanf, &token) - if err != nil || n != 1 { - return "" - } - return token -} - -// Subscribe will express interest in the given subject. The subject -// can have wildcards. -// There are two type of wildcards: * for partial, and > for full. -// A subscription on subject time.*.east would receive messages sent to time.us.east and time.eu.east. -// A subscription on subject time.us.> would receive messages sent to -// time.us.east and time.us.east.atlanta, while time.us.* would only match time.us.east -// since it can't match more than one token. -// Messages will be delivered to the associated MsgHandler. -func (nc *Conn) Subscribe(subj string, cb MsgHandler) (*Subscription, error) { - return nc.subscribe(subj, _EMPTY_, cb, nil, false, nil) -} - -// ChanSubscribe will express interest in the given subject and place -// all messages received on the channel. -// You should not close the channel until sub.Unsubscribe() has been called. -func (nc *Conn) ChanSubscribe(subj string, ch chan *Msg) (*Subscription, error) { - return nc.subscribe(subj, _EMPTY_, nil, ch, false, nil) -} - -// ChanQueueSubscribe will express interest in the given subject. -// All subscribers with the same queue name will form the queue group -// and only one member of the group will be selected to receive any given message, -// which will be placed on the channel. -// You should not close the channel until sub.Unsubscribe() has been called. -// Note: This is the same than QueueSubscribeSyncWithChan. -func (nc *Conn) ChanQueueSubscribe(subj, group string, ch chan *Msg) (*Subscription, error) { - return nc.subscribe(subj, group, nil, ch, false, nil) -} - -// SubscribeSync will express interest on the given subject. Messages will -// be received synchronously using Subscription.NextMsg(). -func (nc *Conn) SubscribeSync(subj string) (*Subscription, error) { - if nc == nil { - return nil, ErrInvalidConnection - } - mch := make(chan *Msg, nc.Opts.SubChanLen) - return nc.subscribe(subj, _EMPTY_, nil, mch, true, nil) -} - -// QueueSubscribe creates an asynchronous queue subscriber on the given subject. -// All subscribers with the same queue name will form the queue group and -// only one member of the group will be selected to receive any given -// message asynchronously. -func (nc *Conn) QueueSubscribe(subj, queue string, cb MsgHandler) (*Subscription, error) { - return nc.subscribe(subj, queue, cb, nil, false, nil) -} - -// QueueSubscribeSync creates a synchronous queue subscriber on the given -// subject. All subscribers with the same queue name will form the queue -// group and only one member of the group will be selected to receive any -// given message synchronously using Subscription.NextMsg(). -func (nc *Conn) QueueSubscribeSync(subj, queue string) (*Subscription, error) { - mch := make(chan *Msg, nc.Opts.SubChanLen) - return nc.subscribe(subj, queue, nil, mch, true, nil) -} - -// QueueSubscribeSyncWithChan will express interest in the given subject. -// All subscribers with the same queue name will form the queue group -// and only one member of the group will be selected to receive any given message, -// which will be placed on the channel. -// You should not close the channel until sub.Unsubscribe() has been called. -// Note: This is the same than ChanQueueSubscribe. -func (nc *Conn) QueueSubscribeSyncWithChan(subj, queue string, ch chan *Msg) (*Subscription, error) { - return nc.subscribe(subj, queue, nil, ch, false, nil) -} - -// badSubject will do quick test on whether a subject is acceptable. -// Spaces are not allowed and all tokens should be > 0 in len. -func badSubject(subj string) bool { - if strings.ContainsAny(subj, " \t\r\n") { - return true - } - tokens := strings.Split(subj, ".") - for _, t := range tokens { - if len(t) == 0 { - return true - } - } - return false -} - -// badQueue will check a queue name for whitespace. -func badQueue(qname string) bool { - return strings.ContainsAny(qname, " \t\r\n") -} - -// subscribe is the internal subscribe function that indicates interest in a subject. -func (nc *Conn) subscribe(subj, queue string, cb MsgHandler, ch chan *Msg, isSync bool, js *jsSub) (*Subscription, error) { - if nc == nil { - return nil, ErrInvalidConnection - } - nc.mu.Lock() - defer nc.mu.Unlock() - return nc.subscribeLocked(subj, queue, cb, ch, isSync, js) -} - -func (nc *Conn) subscribeLocked(subj, queue string, cb MsgHandler, ch chan *Msg, isSync bool, js *jsSub) (*Subscription, error) { - if nc == nil { - return nil, ErrInvalidConnection - } - if badSubject(subj) { - return nil, ErrBadSubject - } - if queue != _EMPTY_ && badQueue(queue) { - return nil, ErrBadQueueName - } - - // Check for some error conditions. - if nc.isClosed() { - return nil, ErrConnectionClosed - } - if nc.isDraining() { - return nil, ErrConnectionDraining - } - - if cb == nil && ch == nil { - return nil, ErrBadSubscription - } - - sub := &Subscription{ - Subject: subj, - Queue: queue, - mcb: cb, - conn: nc, - jsi: js, - } - // Set pending limits. - if ch != nil { - sub.pMsgsLimit = cap(ch) - } else { - sub.pMsgsLimit = DefaultSubPendingMsgsLimit - } - sub.pBytesLimit = DefaultSubPendingBytesLimit - - // If we have an async callback, start up a sub specific - // Go routine to deliver the messages. - var sr bool - if cb != nil { - sub.typ = AsyncSubscription - sub.pCond = sync.NewCond(&sub.mu) - sr = true - } else if !isSync { - sub.typ = ChanSubscription - sub.mch = ch - } else { // Sync Subscription - sub.typ = SyncSubscription - sub.mch = ch - } - - nc.subsMu.Lock() - nc.ssid++ - sub.sid = nc.ssid - nc.subs[sub.sid] = sub - nc.subsMu.Unlock() - - // Let's start the go routine now that it is fully setup and registered. - if sr { - go nc.waitForMsgs(sub) - } - - // We will send these for all subs when we reconnect - // so that we can suppress here if reconnecting. - if !nc.isReconnecting() { - nc.bw.appendString(fmt.Sprintf(subProto, subj, queue, sub.sid)) - nc.kickFlusher() - } - - return sub, nil -} - -// NumSubscriptions returns active number of subscriptions. -func (nc *Conn) NumSubscriptions() int { - nc.mu.RLock() - defer nc.mu.RUnlock() - return len(nc.subs) -} - -// Lock for nc should be held here upon entry -func (nc *Conn) removeSub(s *Subscription) { - nc.subsMu.Lock() - delete(nc.subs, s.sid) - nc.subsMu.Unlock() - s.mu.Lock() - defer s.mu.Unlock() - // Release callers on NextMsg for SyncSubscription only - if s.mch != nil && s.typ == SyncSubscription { - close(s.mch) - } - s.mch = nil - - // If JS subscription then stop HB timer. - if jsi := s.jsi; jsi != nil { - if jsi.hbc != nil { - jsi.hbc.Stop() - jsi.hbc = nil - } - if jsi.csfct != nil { - jsi.csfct.Stop() - jsi.csfct = nil - } - } - - if s.typ != AsyncSubscription { - done := s.pDone - if done != nil { - done(s.Subject) - } - } - // Mark as invalid - s.closed = true - if s.pCond != nil { - s.pCond.Broadcast() - } -} - -// SubscriptionType is the type of the Subscription. -type SubscriptionType int - -// The different types of subscription types. -const ( - AsyncSubscription = SubscriptionType(iota) - SyncSubscription - ChanSubscription - NilSubscription - PullSubscription -) - -// Type returns the type of Subscription. -func (s *Subscription) Type() SubscriptionType { - if s == nil { - return NilSubscription - } - s.mu.Lock() - defer s.mu.Unlock() - // Pull subscriptions are really a SyncSubscription and we want this - // type to be set internally for all delivered messages management, etc.. - // So check when to return PullSubscription to the user. - if s.jsi != nil && s.jsi.pull { - return PullSubscription - } - return s.typ -} - -// IsValid returns a boolean indicating whether the subscription -// is still active. This will return false if the subscription has -// already been closed. -func (s *Subscription) IsValid() bool { - if s == nil { - return false - } - s.mu.Lock() - defer s.mu.Unlock() - return s.conn != nil && !s.closed -} - -// Drain will remove interest but continue callbacks until all messages -// have been processed. -// -// For a JetStream subscription, if the library has created the JetStream -// consumer, the library will send a DeleteConsumer request to the server -// when the Drain operation completes. If a failure occurs when deleting -// the JetStream consumer, an error will be reported to the asynchronous -// error callback. -// If you do not wish the JetStream consumer to be automatically deleted, -// ensure that the consumer is not created by the library, which means -// create the consumer with AddConsumer and bind to this consumer. -func (s *Subscription) Drain() error { - if s == nil { - return ErrBadSubscription - } - s.mu.Lock() - conn := s.conn - s.mu.Unlock() - if conn == nil { - return ErrBadSubscription - } - return conn.unsubscribe(s, 0, true) -} - -// Unsubscribe will remove interest in the given subject. -// -// For a JetStream subscription, if the library has created the JetStream -// consumer, it will send a DeleteConsumer request to the server (if the -// unsubscribe itself was successful). If the delete operation fails, the -// error will be returned. -// If you do not wish the JetStream consumer to be automatically deleted, -// ensure that the consumer is not created by the library, which means -// create the consumer with AddConsumer and bind to this consumer (using -// the nats.Bind() option). -func (s *Subscription) Unsubscribe() error { - if s == nil { - return ErrBadSubscription - } - s.mu.Lock() - conn := s.conn - closed := s.closed - dc := s.jsi != nil && s.jsi.dc - s.mu.Unlock() - if conn == nil || conn.IsClosed() { - return ErrConnectionClosed - } - if closed { - return ErrBadSubscription - } - if conn.IsDraining() { - return ErrConnectionDraining - } - err := conn.unsubscribe(s, 0, false) - if err == nil && dc { - err = s.deleteConsumer() - } - return err -} - -// checkDrained will watch for a subscription to be fully drained -// and then remove it. -func (nc *Conn) checkDrained(sub *Subscription) { - if nc == nil || sub == nil { - return - } - - // This allows us to know that whatever we have in the client pending - // is correct and the server will not send additional information. - nc.Flush() - - sub.mu.Lock() - // For JS subscriptions, check if we are going to delete the - // JS consumer when drain completes. - dc := sub.jsi != nil && sub.jsi.dc - sub.mu.Unlock() - - // Once we are here we just wait for Pending to reach 0 or - // any other state to exit this go routine. - for { - // check connection is still valid. - if nc.IsClosed() { - return - } - - // Check subscription state - sub.mu.Lock() - conn := sub.conn - closed := sub.closed - pMsgs := sub.pMsgs - sub.mu.Unlock() - - if conn == nil || closed || pMsgs == 0 { - nc.mu.Lock() - nc.removeSub(sub) - nc.mu.Unlock() - if dc { - if err := sub.deleteConsumer(); err != nil { - nc.mu.Lock() - if errCB := nc.Opts.AsyncErrorCB; errCB != nil { - nc.ach.push(func() { errCB(nc, sub, err) }) - } - nc.mu.Unlock() - } - } - return - } - - time.Sleep(100 * time.Millisecond) - } -} - -// AutoUnsubscribe will issue an automatic Unsubscribe that is -// processed by the server when max messages have been received. -// This can be useful when sending a request to an unknown number -// of subscribers. -func (s *Subscription) AutoUnsubscribe(max int) error { - if s == nil { - return ErrBadSubscription - } - s.mu.Lock() - conn := s.conn - closed := s.closed - s.mu.Unlock() - if conn == nil || closed { - return ErrBadSubscription - } - return conn.unsubscribe(s, max, false) -} - -// SetClosedHandler will set the closed handler for when a subscription -// is closed (either unsubscribed or drained). -func (s *Subscription) SetClosedHandler(handler func(subject string)) { - s.mu.Lock() - s.pDone = handler - s.mu.Unlock() -} - -// unsubscribe performs the low level unsubscribe to the server. -// Use Subscription.Unsubscribe() -func (nc *Conn) unsubscribe(sub *Subscription, max int, drainMode bool) error { - var maxStr string - if max > 0 { - sub.mu.Lock() - sub.max = uint64(max) - if sub.delivered < sub.max { - maxStr = strconv.Itoa(max) - } - sub.mu.Unlock() - } - - nc.mu.Lock() - // ok here, but defer is expensive - defer nc.mu.Unlock() - - if nc.isClosed() { - return ErrConnectionClosed - } - - nc.subsMu.RLock() - s := nc.subs[sub.sid] - nc.subsMu.RUnlock() - // Already unsubscribed - if s == nil { - return nil - } - - if maxStr == _EMPTY_ && !drainMode { - nc.removeSub(s) - } - - if drainMode { - go nc.checkDrained(sub) - } - - // We will send these for all subs when we reconnect - // so that we can suppress here. - if !nc.isReconnecting() { - nc.bw.appendString(fmt.Sprintf(unsubProto, s.sid, maxStr)) - nc.kickFlusher() - } - - // For JetStream subscriptions cancel the attached context if there is any. - var cancel func() - sub.mu.Lock() - jsi := sub.jsi - if jsi != nil { - cancel = jsi.cancel - jsi.cancel = nil - } - sub.mu.Unlock() - if cancel != nil { - cancel() - } - - return nil -} - -// NextMsg will return the next message available to a synchronous subscriber -// or block until one is available. An error is returned if the subscription is invalid (ErrBadSubscription), -// the connection is closed (ErrConnectionClosed), the timeout is reached (ErrTimeout), -// or if there were no responders (ErrNoResponders) when used in the context of a request/reply. -func (s *Subscription) NextMsg(timeout time.Duration) (*Msg, error) { - if s == nil { - return nil, ErrBadSubscription - } - - s.mu.Lock() - err := s.validateNextMsgState(false) - if err != nil { - s.mu.Unlock() - return nil, err - } - - // snapshot - mch := s.mch - s.mu.Unlock() - - var ok bool - var msg *Msg - - // If something is available right away, let's optimize that case. - select { - case msg, ok = <-mch: - if !ok { - return nil, s.getNextMsgErr() - } - if err := s.processNextMsgDelivered(msg); err != nil { - return nil, err - } else { - return msg, nil - } - default: - } - - // If we are here a message was not immediately available, so lets loop - // with a timeout. - - t := globalTimerPool.Get(timeout) - defer globalTimerPool.Put(t) - - select { - case msg, ok = <-mch: - if !ok { - return nil, s.getNextMsgErr() - } - if err := s.processNextMsgDelivered(msg); err != nil { - return nil, err - } - case <-t.C: - return nil, ErrTimeout - } - - return msg, nil -} - -// validateNextMsgState checks whether the subscription is in a valid -// state to call NextMsg and be delivered another message synchronously. -// This should be called while holding the lock. -func (s *Subscription) validateNextMsgState(pullSubInternal bool) error { - if s.connClosed { - return ErrConnectionClosed - } - if s.mch == nil { - if s.max > 0 && s.delivered >= s.max { - return ErrMaxMessages - } else if s.closed { - return ErrBadSubscription - } - } - if s.mcb != nil { - return ErrSyncSubRequired - } - if s.sc { - s.sc = false - return ErrSlowConsumer - } - // Unless this is from an internal call, reject use of this API. - // Users should use Fetch() instead. - if !pullSubInternal && s.jsi != nil && s.jsi.pull { - return ErrTypeSubscription - } - return nil -} - -// This is called when the sync channel has been closed. -// The error returned will be either connection or subscription -// closed depending on what caused NextMsg() to fail. -func (s *Subscription) getNextMsgErr() error { - s.mu.Lock() - defer s.mu.Unlock() - if s.connClosed { - return ErrConnectionClosed - } - return ErrBadSubscription -} - -// processNextMsgDelivered takes a message and applies the needed -// accounting to the stats from the subscription, returning an -// error in case we have the maximum number of messages have been -// delivered already. It should not be called while holding the lock. -func (s *Subscription) processNextMsgDelivered(msg *Msg) error { - s.mu.Lock() - nc := s.conn - max := s.max - - var fcReply string - // Update some stats. - s.delivered++ - delivered := s.delivered - if s.jsi != nil { - fcReply = s.checkForFlowControlResponse() - } - - if s.typ == SyncSubscription { - s.pMsgs-- - s.pBytes -= len(msg.Data) - } - s.mu.Unlock() - - if fcReply != _EMPTY_ { - nc.Publish(fcReply, nil) - } - - if max > 0 { - if delivered > max { - return ErrMaxMessages - } - // Remove subscription if we have reached max. - if delivered == max { - nc.mu.Lock() - nc.removeSub(s) - nc.mu.Unlock() - } - } - if len(msg.Data) == 0 && msg.Header.Get(statusHdr) == noResponders { - return ErrNoResponders - } - - return nil -} - -// Queued returns the number of queued messages in the client for this subscription. -// DEPRECATED: Use Pending() -func (s *Subscription) QueuedMsgs() (int, error) { - m, _, err := s.Pending() - return int(m), err -} - -// Pending returns the number of queued messages and queued bytes in the client for this subscription. -func (s *Subscription) Pending() (int, int, error) { - if s == nil { - return -1, -1, ErrBadSubscription - } - s.mu.Lock() - defer s.mu.Unlock() - if s.conn == nil || s.closed { - return -1, -1, ErrBadSubscription - } - if s.typ == ChanSubscription { - return -1, -1, ErrTypeSubscription - } - return s.pMsgs, s.pBytes, nil -} - -// MaxPending returns the maximum number of queued messages and queued bytes seen so far. -func (s *Subscription) MaxPending() (int, int, error) { - if s == nil { - return -1, -1, ErrBadSubscription - } - s.mu.Lock() - defer s.mu.Unlock() - if s.conn == nil || s.closed { - return -1, -1, ErrBadSubscription - } - if s.typ == ChanSubscription { - return -1, -1, ErrTypeSubscription - } - return s.pMsgsMax, s.pBytesMax, nil -} - -// ClearMaxPending resets the maximums seen so far. -func (s *Subscription) ClearMaxPending() error { - if s == nil { - return ErrBadSubscription - } - s.mu.Lock() - defer s.mu.Unlock() - if s.conn == nil || s.closed { - return ErrBadSubscription - } - if s.typ == ChanSubscription { - return ErrTypeSubscription - } - s.pMsgsMax, s.pBytesMax = 0, 0 - return nil -} - -// Pending Limits -const ( - // DefaultSubPendingMsgsLimit will be 512k msgs. - DefaultSubPendingMsgsLimit = 512 * 1024 - // DefaultSubPendingBytesLimit is 64MB - DefaultSubPendingBytesLimit = 64 * 1024 * 1024 -) - -// PendingLimits returns the current limits for this subscription. -// If no error is returned, a negative value indicates that the -// given metric is not limited. -func (s *Subscription) PendingLimits() (int, int, error) { - if s == nil { - return -1, -1, ErrBadSubscription - } - s.mu.Lock() - defer s.mu.Unlock() - if s.conn == nil || s.closed { - return -1, -1, ErrBadSubscription - } - if s.typ == ChanSubscription { - return -1, -1, ErrTypeSubscription - } - return s.pMsgsLimit, s.pBytesLimit, nil -} - -// SetPendingLimits sets the limits for pending msgs and bytes for this subscription. -// Zero is not allowed. Any negative value means that the given metric is not limited. -func (s *Subscription) SetPendingLimits(msgLimit, bytesLimit int) error { - if s == nil { - return ErrBadSubscription - } - s.mu.Lock() - defer s.mu.Unlock() - if s.conn == nil || s.closed { - return ErrBadSubscription - } - if s.typ == ChanSubscription { - return ErrTypeSubscription - } - if msgLimit == 0 || bytesLimit == 0 { - return ErrInvalidArg - } - s.pMsgsLimit, s.pBytesLimit = msgLimit, bytesLimit - return nil -} - -// Delivered returns the number of delivered messages for this subscription. -func (s *Subscription) Delivered() (int64, error) { - if s == nil { - return -1, ErrBadSubscription - } - s.mu.Lock() - defer s.mu.Unlock() - if s.conn == nil || s.closed { - return -1, ErrBadSubscription - } - return int64(s.delivered), nil -} - -// Dropped returns the number of known dropped messages for this subscription. -// This will correspond to messages dropped by violations of PendingLimits. If -// the server declares the connection a SlowConsumer, this number may not be -// valid. -func (s *Subscription) Dropped() (int, error) { - if s == nil { - return -1, ErrBadSubscription - } - s.mu.Lock() - defer s.mu.Unlock() - if s.conn == nil || s.closed { - return -1, ErrBadSubscription - } - return s.dropped, nil -} - -// Respond allows a convenient way to respond to requests in service based subscriptions. -func (m *Msg) Respond(data []byte) error { - if m == nil || m.Sub == nil { - return ErrMsgNotBound - } - if m.Reply == "" { - return ErrMsgNoReply - } - m.Sub.mu.Lock() - nc := m.Sub.conn - m.Sub.mu.Unlock() - // No need to check the connection here since the call to publish will do all the checking. - return nc.Publish(m.Reply, data) -} - -// RespondMsg allows a convenient way to respond to requests in service based subscriptions that might include headers -func (m *Msg) RespondMsg(msg *Msg) error { - if m == nil || m.Sub == nil { - return ErrMsgNotBound - } - if m.Reply == "" { - return ErrMsgNoReply - } - msg.Subject = m.Reply - m.Sub.mu.Lock() - nc := m.Sub.conn - m.Sub.mu.Unlock() - // No need to check the connection here since the call to publish will do all the checking. - return nc.PublishMsg(msg) -} - -// FIXME: This is a hack -// removeFlushEntry is needed when we need to discard queued up responses -// for our pings as part of a flush call. This happens when we have a flush -// call outstanding and we call close. -func (nc *Conn) removeFlushEntry(ch chan struct{}) bool { - nc.mu.Lock() - defer nc.mu.Unlock() - if nc.pongs == nil { - return false - } - for i, c := range nc.pongs { - if c == ch { - nc.pongs[i] = nil - return true - } - } - return false -} - -// The lock must be held entering this function. -func (nc *Conn) sendPing(ch chan struct{}) { - nc.pongs = append(nc.pongs, ch) - nc.bw.appendString(pingProto) - // Flush in place. - nc.bw.flush() -} - -// This will fire periodically and send a client origin -// ping to the server. Will also check that we have received -// responses from the server. -func (nc *Conn) processPingTimer() { - nc.mu.Lock() - - if nc.status != CONNECTED { - nc.mu.Unlock() - return - } - - // Check for violation - nc.pout++ - if nc.pout > nc.Opts.MaxPingsOut { - nc.mu.Unlock() - nc.processOpErr(ErrStaleConnection) - return - } - - nc.sendPing(nil) - nc.ptmr.Reset(nc.Opts.PingInterval) - nc.mu.Unlock() -} - -// FlushTimeout allows a Flush operation to have an associated timeout. -func (nc *Conn) FlushTimeout(timeout time.Duration) (err error) { - if nc == nil { - return ErrInvalidConnection - } - if timeout <= 0 { - return ErrBadTimeout - } - - nc.mu.Lock() - if nc.isClosed() { - nc.mu.Unlock() - return ErrConnectionClosed - } - t := globalTimerPool.Get(timeout) - defer globalTimerPool.Put(t) - - // Create a buffered channel to prevent chan send to block - // in processPong() if this code here times out just when - // PONG was received. - ch := make(chan struct{}, 1) - nc.sendPing(ch) - nc.mu.Unlock() - - select { - case _, ok := <-ch: - if !ok { - err = ErrConnectionClosed - } else { - close(ch) - } - case <-t.C: - err = ErrTimeout - } - - if err != nil { - nc.removeFlushEntry(ch) - } - return -} - -// RTT calculates the round trip time between this client and the server. -func (nc *Conn) RTT() (time.Duration, error) { - if nc.IsClosed() { - return 0, ErrConnectionClosed - } - if nc.IsReconnecting() { - return 0, ErrDisconnected - } - start := time.Now() - if err := nc.FlushTimeout(10 * time.Second); err != nil { - return 0, err - } - return time.Since(start), nil -} - -// Flush will perform a round trip to the server and return when it -// receives the internal reply. -func (nc *Conn) Flush() error { - return nc.FlushTimeout(10 * time.Second) -} - -// Buffered will return the number of bytes buffered to be sent to the server. -// FIXME(dlc) take into account disconnected state. -func (nc *Conn) Buffered() (int, error) { - nc.mu.RLock() - defer nc.mu.RUnlock() - if nc.isClosed() || nc.bw == nil { - return -1, ErrConnectionClosed - } - return nc.bw.buffered(), nil -} - -// resendSubscriptions will send our subscription state back to the -// server. Used in reconnects -func (nc *Conn) resendSubscriptions() { - // Since we are going to send protocols to the server, we don't want to - // be holding the subsMu lock (which is used in processMsg). So copy - // the subscriptions in a temporary array. - nc.subsMu.RLock() - subs := make([]*Subscription, 0, len(nc.subs)) - for _, s := range nc.subs { - subs = append(subs, s) - } - nc.subsMu.RUnlock() - for _, s := range subs { - adjustedMax := uint64(0) - s.mu.Lock() - if s.max > 0 { - if s.delivered < s.max { - adjustedMax = s.max - s.delivered - } - // adjustedMax could be 0 here if the number of delivered msgs - // reached the max, if so unsubscribe. - if adjustedMax == 0 { - s.mu.Unlock() - nc.bw.writeDirect(fmt.Sprintf(unsubProto, s.sid, _EMPTY_)) - continue - } - } - subj, queue, sid := s.Subject, s.Queue, s.sid - s.mu.Unlock() - - nc.bw.writeDirect(fmt.Sprintf(subProto, subj, queue, sid)) - if adjustedMax > 0 { - maxStr := strconv.Itoa(int(adjustedMax)) - nc.bw.writeDirect(fmt.Sprintf(unsubProto, sid, maxStr)) - } - } -} - -// This will clear any pending flush calls and release pending calls. -// Lock is assumed to be held by the caller. -func (nc *Conn) clearPendingFlushCalls() { - // Clear any queued pongs, e.g. pending flush calls. - for _, ch := range nc.pongs { - if ch != nil { - close(ch) - } - } - nc.pongs = nil -} - -// This will clear any pending Request calls. -// Lock is assumed to be held by the caller. -func (nc *Conn) clearPendingRequestCalls() { - if nc.respMap == nil { - return - } - for key, ch := range nc.respMap { - if ch != nil { - close(ch) - delete(nc.respMap, key) - } - } -} - -// Low level close call that will do correct cleanup and set -// desired status. Also controls whether user defined callbacks -// will be triggered. The lock should not be held entering this -// function. This function will handle the locking manually. -func (nc *Conn) close(status Status, doCBs bool, err error) { - nc.mu.Lock() - if nc.isClosed() { - nc.status = status - nc.mu.Unlock() - return - } - nc.status = CLOSED - - // Kick the Go routines so they fall out. - nc.kickFlusher() - - // If the reconnect timer is waiting between a reconnect attempt, - // this will kick it out. - if nc.rqch != nil { - close(nc.rqch) - nc.rqch = nil - } - - // Clear any queued pongs, e.g. pending flush calls. - nc.clearPendingFlushCalls() - - // Clear any queued and blocking Requests. - nc.clearPendingRequestCalls() - - // Stop ping timer if set. - nc.stopPingTimer() - nc.ptmr = nil - - // Need to close and set TCP conn to nil if reconnect loop has stopped, - // otherwise we would incorrectly invoke Disconnect handler (if set) - // down below. - if nc.ar && nc.conn != nil { - nc.conn.Close() - nc.conn = nil - } else if nc.conn != nil { - // Go ahead and make sure we have flushed the outbound - nc.bw.flush() - defer nc.conn.Close() - } - - // Close sync subscriber channels and release any - // pending NextMsg() calls. - nc.subsMu.Lock() - for _, s := range nc.subs { - s.mu.Lock() - - // Release callers on NextMsg for SyncSubscription only - if s.mch != nil && s.typ == SyncSubscription { - close(s.mch) - } - s.mch = nil - // Mark as invalid, for signaling to waitForMsgs - s.closed = true - // Mark connection closed in subscription - s.connClosed = true - // If we have an async subscription, signals it to exit - if s.typ == AsyncSubscription && s.pCond != nil { - s.pCond.Signal() - } - - s.mu.Unlock() - } - nc.subs = nil - nc.subsMu.Unlock() - - nc.changeConnStatus(status) - - // Perform appropriate callback if needed for a disconnect. - if doCBs { - if nc.conn != nil { - if disconnectedErrCB := nc.Opts.DisconnectedErrCB; disconnectedErrCB != nil { - nc.ach.push(func() { disconnectedErrCB(nc, err) }) - } else if disconnectedCB := nc.Opts.DisconnectedCB; disconnectedCB != nil { - nc.ach.push(func() { disconnectedCB(nc) }) - } - } - if nc.Opts.ClosedCB != nil { - nc.ach.push(func() { nc.Opts.ClosedCB(nc) }) - } - } - // If this is terminal, then we have to notify the asyncCB handler that - // it can exit once all async callbacks have been dispatched. - if status == CLOSED { - nc.ach.close() - } - nc.mu.Unlock() -} - -// Close will close the connection to the server. This call will release -// all blocking calls, such as Flush() and NextMsg() -func (nc *Conn) Close() { - if nc != nil { - // This will be a no-op if the connection was not websocket. - // We do this here as opposed to inside close() because we want - // to do this only for the final user-driven close of the client. - // Otherwise, we would need to change close() to pass a boolean - // indicating that this is the case. - nc.wsClose() - nc.close(CLOSED, !nc.Opts.NoCallbacksAfterClientClose, nil) - } -} - -// IsClosed tests if a Conn has been closed. -func (nc *Conn) IsClosed() bool { - nc.mu.RLock() - defer nc.mu.RUnlock() - return nc.isClosed() -} - -// IsReconnecting tests if a Conn is reconnecting. -func (nc *Conn) IsReconnecting() bool { - nc.mu.RLock() - defer nc.mu.RUnlock() - return nc.isReconnecting() -} - -// IsConnected tests if a Conn is connected. -func (nc *Conn) IsConnected() bool { - nc.mu.RLock() - defer nc.mu.RUnlock() - return nc.isConnected() -} - -// drainConnection will run in a separate Go routine and will -// flush all publishes and drain all active subscriptions. -func (nc *Conn) drainConnection() { - // Snapshot subs list. - nc.mu.Lock() - - // Check again here if we are in a state to not process. - if nc.isClosed() { - nc.mu.Unlock() - return - } - if nc.isConnecting() || nc.isReconnecting() { - nc.mu.Unlock() - // Move to closed state. - nc.Close() - return - } - - subs := make([]*Subscription, 0, len(nc.subs)) - for _, s := range nc.subs { - if s == nc.respMux { - // Skip since might be in use while messages - // are being processed (can miss responses). - continue - } - subs = append(subs, s) - } - errCB := nc.Opts.AsyncErrorCB - drainWait := nc.Opts.DrainTimeout - respMux := nc.respMux - nc.mu.Unlock() - - // for pushing errors with context. - pushErr := func(err error) { - nc.mu.Lock() - nc.err = err - if errCB != nil { - nc.ach.push(func() { errCB(nc, nil, err) }) - } - nc.mu.Unlock() - } - - // Do subs first, skip request handler if present. - for _, s := range subs { - if err := s.Drain(); err != nil { - // We will notify about these but continue. - pushErr(err) - } - } - - // Wait for the subscriptions to drop to zero. - timeout := time.Now().Add(drainWait) - var min int - if respMux != nil { - min = 1 - } else { - min = 0 - } - for time.Now().Before(timeout) { - if nc.NumSubscriptions() == min { - break - } - time.Sleep(10 * time.Millisecond) - } - - // In case there was a request/response handler - // then need to call drain at the end. - if respMux != nil { - if err := respMux.Drain(); err != nil { - // We will notify about these but continue. - pushErr(err) - } - for time.Now().Before(timeout) { - if nc.NumSubscriptions() == 0 { - break - } - time.Sleep(10 * time.Millisecond) - } - } - - // Check if we timed out. - if nc.NumSubscriptions() != 0 { - pushErr(ErrDrainTimeout) - } - - // Flip State - nc.mu.Lock() - nc.changeConnStatus(DRAINING_PUBS) - nc.mu.Unlock() - - // Do publish drain via Flush() call. - err := nc.FlushTimeout(5 * time.Second) - if err != nil { - pushErr(err) - } - - // Move to closed state. - nc.Close() -} - -// Drain will put a connection into a drain state. All subscriptions will -// immediately be put into a drain state. Upon completion, the publishers -// will be drained and can not publish any additional messages. Upon draining -// of the publishers, the connection will be closed. Use the ClosedCB() -// option to know when the connection has moved from draining to closed. -// -// See note in Subscription.Drain for JetStream subscriptions. -func (nc *Conn) Drain() error { - nc.mu.Lock() - if nc.isClosed() { - nc.mu.Unlock() - return ErrConnectionClosed - } - if nc.isConnecting() || nc.isReconnecting() { - nc.mu.Unlock() - nc.Close() - return ErrConnectionReconnecting - } - if nc.isDraining() { - nc.mu.Unlock() - return nil - } - nc.changeConnStatus(DRAINING_SUBS) - go nc.drainConnection() - nc.mu.Unlock() - - return nil -} - -// IsDraining tests if a Conn is in the draining state. -func (nc *Conn) IsDraining() bool { - nc.mu.RLock() - defer nc.mu.RUnlock() - return nc.isDraining() -} - -// caller must lock -func (nc *Conn) getServers(implicitOnly bool) []string { - poolSize := len(nc.srvPool) - var servers = make([]string, 0) - for i := 0; i < poolSize; i++ { - if implicitOnly && !nc.srvPool[i].isImplicit { - continue - } - url := nc.srvPool[i].url - servers = append(servers, fmt.Sprintf("%s://%s", url.Scheme, url.Host)) - } - return servers -} - -// Servers returns the list of known server urls, including additional -// servers discovered after a connection has been established. If -// authentication is enabled, use UserInfo or Token when connecting with -// these urls. -func (nc *Conn) Servers() []string { - nc.mu.RLock() - defer nc.mu.RUnlock() - return nc.getServers(false) -} - -// DiscoveredServers returns only the server urls that have been discovered -// after a connection has been established. If authentication is enabled, -// use UserInfo or Token when connecting with these urls. -func (nc *Conn) DiscoveredServers() []string { - nc.mu.RLock() - defer nc.mu.RUnlock() - return nc.getServers(true) -} - -// Status returns the current state of the connection. -func (nc *Conn) Status() Status { - nc.mu.RLock() - defer nc.mu.RUnlock() - return nc.status -} - -// Test if Conn has been closed Lock is assumed held. -func (nc *Conn) isClosed() bool { - return nc.status == CLOSED -} - -// Test if Conn is in the process of connecting -func (nc *Conn) isConnecting() bool { - return nc.status == CONNECTING -} - -// Test if Conn is being reconnected. -func (nc *Conn) isReconnecting() bool { - return nc.status == RECONNECTING -} - -// Test if Conn is connected or connecting. -func (nc *Conn) isConnected() bool { - return nc.status == CONNECTED || nc.isDraining() -} - -// Test if Conn is in the draining state. -func (nc *Conn) isDraining() bool { - return nc.status == DRAINING_SUBS || nc.status == DRAINING_PUBS -} - -// Test if Conn is in the draining state for pubs. -func (nc *Conn) isDrainingPubs() bool { - return nc.status == DRAINING_PUBS -} - -// Stats will return a race safe copy of the Statistics section for the connection. -func (nc *Conn) Stats() Statistics { - // Stats are updated either under connection's mu or with atomic operations - // for inbound stats in processMsg(). - nc.mu.Lock() - stats := Statistics{ - InMsgs: atomic.LoadUint64(&nc.InMsgs), - InBytes: atomic.LoadUint64(&nc.InBytes), - OutMsgs: nc.OutMsgs, - OutBytes: nc.OutBytes, - Reconnects: nc.Reconnects, - } - nc.mu.Unlock() - return stats -} - -// MaxPayload returns the size limit that a message payload can have. -// This is set by the server configuration and delivered to the client -// upon connect. -func (nc *Conn) MaxPayload() int64 { - nc.mu.RLock() - defer nc.mu.RUnlock() - return nc.info.MaxPayload -} - -// HeadersSupported will return if the server supports headers -func (nc *Conn) HeadersSupported() bool { - nc.mu.RLock() - defer nc.mu.RUnlock() - return nc.info.Headers -} - -// AuthRequired will return if the connected server requires authorization. -func (nc *Conn) AuthRequired() bool { - nc.mu.RLock() - defer nc.mu.RUnlock() - return nc.info.AuthRequired -} - -// TLSRequired will return if the connected server requires TLS connections. -func (nc *Conn) TLSRequired() bool { - nc.mu.RLock() - defer nc.mu.RUnlock() - return nc.info.TLSRequired -} - -// Barrier schedules the given function `f` to all registered asynchronous -// subscriptions. -// Only the last subscription to see this barrier will invoke the function. -// If no subscription is registered at the time of this call, `f()` is invoked -// right away. -// ErrConnectionClosed is returned if the connection is closed prior to -// the call. -func (nc *Conn) Barrier(f func()) error { - nc.mu.Lock() - if nc.isClosed() { - nc.mu.Unlock() - return ErrConnectionClosed - } - nc.subsMu.Lock() - // Need to figure out how many non chan subscriptions there are - numSubs := 0 - for _, sub := range nc.subs { - if sub.typ == AsyncSubscription { - numSubs++ - } - } - if numSubs == 0 { - nc.subsMu.Unlock() - nc.mu.Unlock() - f() - return nil - } - barrier := &barrierInfo{refs: int64(numSubs), f: f} - for _, sub := range nc.subs { - sub.mu.Lock() - if sub.mch == nil { - msg := &Msg{barrier: barrier} - // Push onto the async pList - if sub.pTail != nil { - sub.pTail.next = msg - } else { - sub.pHead = msg - sub.pCond.Signal() - } - sub.pTail = msg - } - sub.mu.Unlock() - } - nc.subsMu.Unlock() - nc.mu.Unlock() - return nil -} - -// GetClientIP returns the client IP as known by the server. -// Supported as of server version 2.1.6. -func (nc *Conn) GetClientIP() (net.IP, error) { - nc.mu.RLock() - defer nc.mu.RUnlock() - if nc.isClosed() { - return nil, ErrConnectionClosed - } - if nc.info.ClientIP == "" { - return nil, ErrClientIPNotSupported - } - ip := net.ParseIP(nc.info.ClientIP) - return ip, nil -} - -// GetClientID returns the client ID assigned by the server to which -// the client is currently connected to. Note that the value may change if -// the client reconnects. -// This function returns ErrClientIDNotSupported if the server is of a -// version prior to 1.2.0. -func (nc *Conn) GetClientID() (uint64, error) { - nc.mu.RLock() - defer nc.mu.RUnlock() - if nc.isClosed() { - return 0, ErrConnectionClosed - } - if nc.info.CID == 0 { - return 0, ErrClientIDNotSupported - } - return nc.info.CID, nil -} - -// StatusChanged returns a channel on which given list of connection status changes will be reported. -// If no statuses are provided, defaults will be used: CONNECTED, RECONNECTING, DISCONNECTED, CLOSED. -func (nc *Conn) StatusChanged(statuses ...Status) chan Status { - if len(statuses) == 0 { - statuses = []Status{CONNECTED, RECONNECTING, DISCONNECTED, CLOSED} - } - ch := make(chan Status, 10) - for _, s := range statuses { - nc.registerStatusChangeListener(s, ch) - } - return ch -} - -// registerStatusChangeListener registers a channel waiting for a specific status change event. -// Status change events are non-blocking - if no receiver is waiting for the status change, -// it will not be sent on the channel. Closed channels are ignored. -func (nc *Conn) registerStatusChangeListener(status Status, ch chan Status) { - nc.mu.Lock() - defer nc.mu.Unlock() - if nc.statListeners == nil { - nc.statListeners = make(map[Status][]chan Status) - } - if _, ok := nc.statListeners[status]; !ok { - nc.statListeners[status] = make([]chan Status, 0) - } - nc.statListeners[status] = append(nc.statListeners[status], ch) -} - -// sendStatusEvent sends connection status event to all channels. -// If channel is closed, or there is no listener, sendStatusEvent -// will not block. Lock should be held entering. -func (nc *Conn) sendStatusEvent(s Status) { -Loop: - for i := 0; i < len(nc.statListeners[s]); i++ { - // make sure channel is not closed - select { - case <-nc.statListeners[s][i]: - // if chan is closed, remove it - nc.statListeners[s][i] = nc.statListeners[s][len(nc.statListeners[s])-1] - nc.statListeners[s] = nc.statListeners[s][:len(nc.statListeners[s])-1] - i-- - continue Loop - default: - } - // only send event if someone's listening - select { - case nc.statListeners[s][i] <- s: - default: - } - } -} - -// changeConnStatus changes connections status and sends events -// to all listeners. Lock should be held entering. -func (nc *Conn) changeConnStatus(status Status) { - if nc == nil { - return - } - nc.sendStatusEvent(status) - nc.status = status -} - -// NkeyOptionFromSeed will load an nkey pair from a seed file. -// It will return the NKey Option and will handle -// signing of nonce challenges from the server. It will take -// care to not hold keys in memory and to wipe memory. -func NkeyOptionFromSeed(seedFile string) (Option, error) { - kp, err := nkeyPairFromSeedFile(seedFile) - if err != nil { - return nil, err - } - // Wipe our key on exit. - defer kp.Wipe() - - pub, err := kp.PublicKey() - if err != nil { - return nil, err - } - if !nkeys.IsValidPublicUserKey(pub) { - return nil, fmt.Errorf("nats: Not a valid nkey user seed") - } - sigCB := func(nonce []byte) ([]byte, error) { - return sigHandler(nonce, seedFile) - } - return Nkey(string(pub), sigCB), nil -} - -// Just wipe slice with 'x', for clearing contents of creds or nkey seed file. -func wipeSlice(buf []byte) { - for i := range buf { - buf[i] = 'x' - } -} - -func userFromFile(userFile string) (string, error) { - path, err := expandPath(userFile) - if err != nil { - return _EMPTY_, fmt.Errorf("nats: %w", err) - } - - contents, err := os.ReadFile(path) - if err != nil { - return _EMPTY_, fmt.Errorf("nats: %w", err) - } - defer wipeSlice(contents) - return nkeys.ParseDecoratedJWT(contents) -} - -func homeDir() (string, error) { - if runtime.GOOS == "windows" { - homeDrive, homePath := os.Getenv("HOMEDRIVE"), os.Getenv("HOMEPATH") - userProfile := os.Getenv("USERPROFILE") - - var home string - if homeDrive == "" || homePath == "" { - if userProfile == "" { - return _EMPTY_, errors.New("nats: failed to get home dir, require %HOMEDRIVE% and %HOMEPATH% or %USERPROFILE%") - } - home = userProfile - } else { - home = filepath.Join(homeDrive, homePath) - } - - return home, nil - } - - home := os.Getenv("HOME") - if home == "" { - return _EMPTY_, errors.New("nats: failed to get home dir, require $HOME") - } - return home, nil -} - -func expandPath(p string) (string, error) { - p = os.ExpandEnv(p) - - if !strings.HasPrefix(p, "~") { - return p, nil - } - - home, err := homeDir() - if err != nil { - return _EMPTY_, err - } - - return filepath.Join(home, p[1:]), nil -} - -func nkeyPairFromSeedFile(seedFile string) (nkeys.KeyPair, error) { - contents, err := os.ReadFile(seedFile) - if err != nil { - return nil, fmt.Errorf("nats: %w", err) - } - defer wipeSlice(contents) - return nkeys.ParseDecoratedNKey(contents) -} - -// Sign authentication challenges from the server. -// Do not keep private seed in memory. -func sigHandler(nonce []byte, seedFile string) ([]byte, error) { - kp, err := nkeyPairFromSeedFile(seedFile) - if err != nil { - return nil, fmt.Errorf("unable to extract key pair from file %q: %w", seedFile, err) - } - // Wipe our key on exit. - defer kp.Wipe() - - sig, _ := kp.Sign(nonce) - return sig, nil -} - -type timeoutWriter struct { - timeout time.Duration - conn net.Conn - err error -} - -// Write implements the io.Writer interface. -func (tw *timeoutWriter) Write(p []byte) (int, error) { - if tw.err != nil { - return 0, tw.err - } - - var n int - tw.conn.SetWriteDeadline(time.Now().Add(tw.timeout)) - n, tw.err = tw.conn.Write(p) - tw.conn.SetWriteDeadline(time.Time{}) - return n, tw.err -} diff --git a/vendor/github.com/nats-io/nats.go/netchan.go b/vendor/github.com/nats-io/nats.go/netchan.go deleted file mode 100644 index 6b13690b4..000000000 --- a/vendor/github.com/nats-io/nats.go/netchan.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2013-2023 The NATS 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 nats - -import ( - "errors" - "reflect" -) - -// This allows the functionality for network channels by binding send and receive Go chans -// to subjects and optionally queue groups. -// Data will be encoded and decoded via the EncodedConn and its associated encoders. - -// BindSendChan binds a channel for send operations to NATS. -func (c *EncodedConn) BindSendChan(subject string, channel any) error { - chVal := reflect.ValueOf(channel) - if chVal.Kind() != reflect.Chan { - return ErrChanArg - } - go chPublish(c, chVal, subject) - return nil -} - -// Publish all values that arrive on the channel until it is closed or we -// encounter an error. -func chPublish(c *EncodedConn, chVal reflect.Value, subject string) { - for { - val, ok := chVal.Recv() - if !ok { - // Channel has most likely been closed. - return - } - if e := c.Publish(subject, val.Interface()); e != nil { - // Do this under lock. - c.Conn.mu.Lock() - defer c.Conn.mu.Unlock() - - if c.Conn.Opts.AsyncErrorCB != nil { - // FIXME(dlc) - Not sure this is the right thing to do. - // FIXME(ivan) - If the connection is not yet closed, try to schedule the callback - if c.Conn.isClosed() { - go c.Conn.Opts.AsyncErrorCB(c.Conn, nil, e) - } else { - c.Conn.ach.push(func() { c.Conn.Opts.AsyncErrorCB(c.Conn, nil, e) }) - } - } - return - } - } -} - -// BindRecvChan binds a channel for receive operations from NATS. -func (c *EncodedConn) BindRecvChan(subject string, channel any) (*Subscription, error) { - return c.bindRecvChan(subject, _EMPTY_, channel) -} - -// BindRecvQueueChan binds a channel for queue-based receive operations from NATS. -func (c *EncodedConn) BindRecvQueueChan(subject, queue string, channel any) (*Subscription, error) { - return c.bindRecvChan(subject, queue, channel) -} - -// Internal function to bind receive operations for a channel. -func (c *EncodedConn) bindRecvChan(subject, queue string, channel any) (*Subscription, error) { - chVal := reflect.ValueOf(channel) - if chVal.Kind() != reflect.Chan { - return nil, ErrChanArg - } - argType := chVal.Type().Elem() - - cb := func(m *Msg) { - var oPtr reflect.Value - if argType.Kind() != reflect.Ptr { - oPtr = reflect.New(argType) - } else { - oPtr = reflect.New(argType.Elem()) - } - if err := c.Enc.Decode(m.Subject, m.Data, oPtr.Interface()); err != nil { - c.Conn.err = errors.New("nats: Got an error trying to unmarshal: " + err.Error()) - if c.Conn.Opts.AsyncErrorCB != nil { - c.Conn.ach.push(func() { c.Conn.Opts.AsyncErrorCB(c.Conn, m.Sub, c.Conn.err) }) - } - return - } - if argType.Kind() != reflect.Ptr { - oPtr = reflect.Indirect(oPtr) - } - // This is a bit hacky, but in this instance we may be trying to send to a closed channel. - // and the user does not know when it is safe to close the channel. - defer func() { - // If we have panicked, recover and close the subscription. - if r := recover(); r != nil { - m.Sub.Unsubscribe() - } - }() - // Actually do the send to the channel. - chVal.Send(oPtr) - } - - return c.Conn.subscribe(subject, queue, cb, nil, false, nil) -} diff --git a/vendor/github.com/nats-io/nats.go/object.go b/vendor/github.com/nats-io/nats.go/object.go deleted file mode 100644 index f3f5d97ec..000000000 --- a/vendor/github.com/nats-io/nats.go/object.go +++ /dev/null @@ -1,1422 +0,0 @@ -// Copyright 2021-2023 The NATS 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 nats - -import ( - "bytes" - "context" - "crypto/sha256" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "hash" - "io" - "net" - "os" - "strings" - "sync" - "time" - - "github.com/nats-io/nats.go/internal/parser" - "github.com/nats-io/nuid" -) - -// ObjectStoreManager creates, loads and deletes Object Stores -type ObjectStoreManager interface { - // ObjectStore will look up and bind to an existing object store instance. - ObjectStore(bucket string) (ObjectStore, error) - // CreateObjectStore will create an object store. - CreateObjectStore(cfg *ObjectStoreConfig) (ObjectStore, error) - // DeleteObjectStore will delete the underlying stream for the named object. - DeleteObjectStore(bucket string) error - // ObjectStoreNames is used to retrieve a list of bucket names - ObjectStoreNames(opts ...ObjectOpt) <-chan string - // ObjectStores is used to retrieve a list of bucket statuses - ObjectStores(opts ...ObjectOpt) <-chan ObjectStoreStatus -} - -// ObjectStore is a blob store capable of storing large objects efficiently in -// JetStream streams -type ObjectStore interface { - // Put will place the contents from the reader into a new object. - Put(obj *ObjectMeta, reader io.Reader, opts ...ObjectOpt) (*ObjectInfo, error) - // Get will pull the named object from the object store. - Get(name string, opts ...GetObjectOpt) (ObjectResult, error) - - // PutBytes is convenience function to put a byte slice into this object store. - PutBytes(name string, data []byte, opts ...ObjectOpt) (*ObjectInfo, error) - // GetBytes is a convenience function to pull an object from this object store and return it as a byte slice. - GetBytes(name string, opts ...GetObjectOpt) ([]byte, error) - - // PutString is convenience function to put a string into this object store. - PutString(name string, data string, opts ...ObjectOpt) (*ObjectInfo, error) - // GetString is a convenience function to pull an object from this object store and return it as a string. - GetString(name string, opts ...GetObjectOpt) (string, error) - - // PutFile is convenience function to put a file into this object store. - PutFile(file string, opts ...ObjectOpt) (*ObjectInfo, error) - // GetFile is a convenience function to pull an object from this object store and place it in a file. - GetFile(name, file string, opts ...GetObjectOpt) error - - // GetInfo will retrieve the current information for the object. - GetInfo(name string, opts ...GetObjectInfoOpt) (*ObjectInfo, error) - // UpdateMeta will update the metadata for the object. - UpdateMeta(name string, meta *ObjectMeta) error - - // Delete will delete the named object. - Delete(name string) error - - // AddLink will add a link to another object. - AddLink(name string, obj *ObjectInfo) (*ObjectInfo, error) - - // AddBucketLink will add a link to another object store. - AddBucketLink(name string, bucket ObjectStore) (*ObjectInfo, error) - - // Seal will seal the object store, no further modifications will be allowed. - Seal() error - - // Watch for changes in the underlying store and receive meta information updates. - Watch(opts ...WatchOpt) (ObjectWatcher, error) - - // List will list all the objects in this store. - List(opts ...ListObjectsOpt) ([]*ObjectInfo, error) - - // Status retrieves run-time status about the backing store of the bucket. - Status() (ObjectStoreStatus, error) -} - -type ObjectOpt interface { - configureObject(opts *objOpts) error -} - -type objOpts struct { - ctx context.Context -} - -// For nats.Context() support. -func (ctx ContextOpt) configureObject(opts *objOpts) error { - opts.ctx = ctx - return nil -} - -// ObjectWatcher is what is returned when doing a watch. -type ObjectWatcher interface { - // Updates returns a channel to read any updates to entries. - Updates() <-chan *ObjectInfo - // Stop will stop this watcher. - Stop() error -} - -var ( - ErrObjectConfigRequired = errors.New("nats: object-store config required") - ErrBadObjectMeta = errors.New("nats: object-store meta information invalid") - ErrObjectNotFound = errors.New("nats: object not found") - ErrInvalidStoreName = errors.New("nats: invalid object-store name") - ErrDigestMismatch = errors.New("nats: received a corrupt object, digests do not match") - ErrInvalidDigestFormat = errors.New("nats: object digest hash has invalid format") - ErrNoObjectsFound = errors.New("nats: no objects found") - ErrObjectAlreadyExists = errors.New("nats: an object already exists with that name") - ErrNameRequired = errors.New("nats: name is required") - ErrNeeds262 = errors.New("nats: object-store requires at least server version 2.6.2") - ErrLinkNotAllowed = errors.New("nats: link cannot be set when putting the object in bucket") - ErrObjectRequired = errors.New("nats: object required") - ErrNoLinkToDeleted = errors.New("nats: not allowed to link to a deleted object") - ErrNoLinkToLink = errors.New("nats: not allowed to link to another link") - ErrCantGetBucket = errors.New("nats: invalid Get, object is a link to a bucket") - ErrBucketRequired = errors.New("nats: bucket required") - ErrBucketMalformed = errors.New("nats: bucket malformed") - ErrUpdateMetaDeleted = errors.New("nats: cannot update meta for a deleted object") -) - -// ObjectStoreConfig is the config for the object store. -type ObjectStoreConfig struct { - Bucket string `json:"bucket"` - Description string `json:"description,omitempty"` - TTL time.Duration `json:"max_age,omitempty"` - MaxBytes int64 `json:"max_bytes,omitempty"` - Storage StorageType `json:"storage,omitempty"` - Replicas int `json:"num_replicas,omitempty"` - Placement *Placement `json:"placement,omitempty"` - - // Bucket-specific metadata - // NOTE: Metadata requires nats-server v2.10.0+ - Metadata map[string]string `json:"metadata,omitempty"` - // Enable underlying stream compression. - // NOTE: Compression is supported for nats-server 2.10.0+ - Compression bool -} - -type ObjectStoreStatus interface { - // Bucket is the name of the bucket - Bucket() string - // Description is the description supplied when creating the bucket - Description() string - // TTL indicates how long objects are kept in the bucket - TTL() time.Duration - // Storage indicates the underlying JetStream storage technology used to store data - Storage() StorageType - // Replicas indicates how many storage replicas are kept for the data in the bucket - Replicas() int - // Sealed indicates the stream is sealed and cannot be modified in any way - Sealed() bool - // Size is the combined size of all data in the bucket including metadata, in bytes - Size() uint64 - // BackingStore provides details about the underlying storage - BackingStore() string - // Metadata is the user supplied metadata for the bucket - Metadata() map[string]string - // IsCompressed indicates if the data is compressed on disk - IsCompressed() bool -} - -// ObjectMetaOptions -type ObjectMetaOptions struct { - Link *ObjectLink `json:"link,omitempty"` - ChunkSize uint32 `json:"max_chunk_size,omitempty"` -} - -// ObjectMeta is high level information about an object. -type ObjectMeta struct { - Name string `json:"name"` - Description string `json:"description,omitempty"` - Headers Header `json:"headers,omitempty"` - Metadata map[string]string `json:"metadata,omitempty"` - - // Optional options. - Opts *ObjectMetaOptions `json:"options,omitempty"` -} - -// ObjectInfo is meta plus instance information. -type ObjectInfo struct { - ObjectMeta - Bucket string `json:"bucket"` - NUID string `json:"nuid"` - Size uint64 `json:"size"` - ModTime time.Time `json:"mtime"` - Chunks uint32 `json:"chunks"` - Digest string `json:"digest,omitempty"` - Deleted bool `json:"deleted,omitempty"` -} - -// ObjectLink is used to embed links to other buckets and objects. -type ObjectLink struct { - // Bucket is the name of the other object store. - Bucket string `json:"bucket"` - // Name can be used to link to a single object. - // If empty means this is a link to the whole store, like a directory. - Name string `json:"name,omitempty"` -} - -// ObjectResult will return the underlying stream info and also be an io.ReadCloser. -type ObjectResult interface { - io.ReadCloser - Info() (*ObjectInfo, error) - Error() error -} - -const ( - objNameTmpl = "OBJ_%s" // OBJ_ // stream name - objAllChunksPreTmpl = "$O.%s.C.>" // $O..C.> // chunk stream subject - objAllMetaPreTmpl = "$O.%s.M.>" // $O..M.> // meta stream subject - objChunksPreTmpl = "$O.%s.C.%s" // $O..C. // chunk message subject - objMetaPreTmpl = "$O.%s.M.%s" // $O..M. // meta message subject - objNoPending = "0" - objDefaultChunkSize = uint32(128 * 1024) // 128k - objDigestType = "SHA-256=" - objDigestTmpl = objDigestType + "%s" -) - -type obs struct { - name string - stream string - js *js -} - -// CreateObjectStore will create an object store. -func (js *js) CreateObjectStore(cfg *ObjectStoreConfig) (ObjectStore, error) { - if !js.nc.serverMinVersion(2, 6, 2) { - return nil, ErrNeeds262 - } - if cfg == nil { - return nil, ErrObjectConfigRequired - } - if !validBucketRe.MatchString(cfg.Bucket) { - return nil, ErrInvalidStoreName - } - - name := cfg.Bucket - chunks := fmt.Sprintf(objAllChunksPreTmpl, name) - meta := fmt.Sprintf(objAllMetaPreTmpl, name) - - // We will set explicitly some values so that we can do comparison - // if we get an "already in use" error and need to check if it is same. - // See kv - replicas := cfg.Replicas - if replicas == 0 { - replicas = 1 - } - maxBytes := cfg.MaxBytes - if maxBytes == 0 { - maxBytes = -1 - } - var compression StoreCompression - if cfg.Compression { - compression = S2Compression - } - scfg := &StreamConfig{ - Name: fmt.Sprintf(objNameTmpl, name), - Description: cfg.Description, - Subjects: []string{chunks, meta}, - MaxAge: cfg.TTL, - MaxBytes: maxBytes, - Storage: cfg.Storage, - Replicas: replicas, - Placement: cfg.Placement, - Discard: DiscardNew, - AllowRollup: true, - AllowDirect: true, - Metadata: cfg.Metadata, - Compression: compression, - } - - // Create our stream. - _, err := js.AddStream(scfg) - if err != nil { - return nil, err - } - - return &obs{name: name, stream: scfg.Name, js: js}, nil -} - -// ObjectStore will look up and bind to an existing object store instance. -func (js *js) ObjectStore(bucket string) (ObjectStore, error) { - if !validBucketRe.MatchString(bucket) { - return nil, ErrInvalidStoreName - } - if !js.nc.serverMinVersion(2, 6, 2) { - return nil, ErrNeeds262 - } - - stream := fmt.Sprintf(objNameTmpl, bucket) - si, err := js.StreamInfo(stream) - if err != nil { - return nil, err - } - return &obs{name: bucket, stream: si.Config.Name, js: js}, nil -} - -// DeleteObjectStore will delete the underlying stream for the named object. -func (js *js) DeleteObjectStore(bucket string) error { - stream := fmt.Sprintf(objNameTmpl, bucket) - return js.DeleteStream(stream) -} - -func encodeName(name string) string { - return base64.URLEncoding.EncodeToString([]byte(name)) -} - -// Put will place the contents from the reader into this object-store. -func (obs *obs) Put(meta *ObjectMeta, r io.Reader, opts ...ObjectOpt) (*ObjectInfo, error) { - if meta == nil || meta.Name == "" { - return nil, ErrBadObjectMeta - } - - if meta.Opts == nil { - meta.Opts = &ObjectMetaOptions{ChunkSize: objDefaultChunkSize} - } else if meta.Opts.Link != nil { - return nil, ErrLinkNotAllowed - } else if meta.Opts.ChunkSize == 0 { - meta.Opts.ChunkSize = objDefaultChunkSize - } - - var o objOpts - for _, opt := range opts { - if opt != nil { - if err := opt.configureObject(&o); err != nil { - return nil, err - } - } - } - ctx := o.ctx - - // Create the new nuid so chunks go on a new subject if the name is re-used - newnuid := nuid.Next() - - // These will be used in more than one place - chunkSubj := fmt.Sprintf(objChunksPreTmpl, obs.name, newnuid) - - // Grab existing meta info (einfo). Ok to be found or not found, any other error is a problem - // Chunks on the old nuid can be cleaned up at the end - einfo, err := obs.GetInfo(meta.Name, GetObjectInfoShowDeleted()) // GetInfo will encode the name - if err != nil && err != ErrObjectNotFound { - return nil, err - } - - // For async error handling - var perr error - var mu sync.Mutex - setErr := func(err error) { - mu.Lock() - defer mu.Unlock() - perr = err - } - getErr := func() error { - mu.Lock() - defer mu.Unlock() - return perr - } - - // Create our own JS context to handle errors etc. - jetStream, err := obs.js.nc.JetStream(PublishAsyncErrHandler(func(js JetStream, _ *Msg, err error) { setErr(err) })) - if err != nil { - return nil, err - } - - defer jetStream.(*js).cleanupReplySub() - - purgePartial := func() error { - // wait until all pubs are complete or up to default timeout before attempting purge - select { - case <-jetStream.PublishAsyncComplete(): - case <-time.After(obs.js.opts.wait): - } - if err := obs.js.purgeStream(obs.stream, &StreamPurgeRequest{Subject: chunkSubj}); err != nil { - return fmt.Errorf("could not cleanup bucket after erroneous put operation: %w", err) - } - return nil - } - - m, h := NewMsg(chunkSubj), sha256.New() - chunk, sent, total := make([]byte, meta.Opts.ChunkSize), 0, uint64(0) - - // set up the info object. The chunk upload sets the size and digest - info := &ObjectInfo{Bucket: obs.name, NUID: newnuid, ObjectMeta: *meta} - - for r != nil { - if ctx != nil { - select { - case <-ctx.Done(): - if ctx.Err() == context.Canceled { - err = ctx.Err() - } else { - err = ErrTimeout - } - default: - } - if err != nil { - if purgeErr := purgePartial(); purgeErr != nil { - return nil, errors.Join(err, purgeErr) - } - return nil, err - } - } - - // Actual read. - // TODO(dlc) - Deadline? - n, readErr := r.Read(chunk) - - // Handle all non EOF errors - if readErr != nil && readErr != io.EOF { - if purgeErr := purgePartial(); purgeErr != nil { - return nil, errors.Join(readErr, purgeErr) - } - return nil, readErr - } - - // Add chunk only if we received data - if n > 0 { - // Chunk processing. - m.Data = chunk[:n] - h.Write(m.Data) - - // Send msg itself. - if _, err := jetStream.PublishMsgAsync(m); err != nil { - if purgeErr := purgePartial(); purgeErr != nil { - return nil, errors.Join(err, purgeErr) - } - return nil, err - } - if err := getErr(); err != nil { - if purgeErr := purgePartial(); purgeErr != nil { - return nil, errors.Join(err, purgeErr) - } - return nil, err - } - // Update totals. - sent++ - total += uint64(n) - } - - // EOF Processing. - if readErr == io.EOF { - // Place meta info. - info.Size, info.Chunks = uint64(total), uint32(sent) - info.Digest = GetObjectDigestValue(h) - break - } - } - - // Prepare the meta message - metaSubj := fmt.Sprintf(objMetaPreTmpl, obs.name, encodeName(meta.Name)) - mm := NewMsg(metaSubj) - mm.Header.Set(MsgRollup, MsgRollupSubject) - mm.Data, err = json.Marshal(info) - if err != nil { - if r != nil { - if purgeErr := purgePartial(); purgeErr != nil { - return nil, errors.Join(err, purgeErr) - } - } - return nil, err - } - - // Publish the meta message. - _, err = jetStream.PublishMsgAsync(mm) - if err != nil { - if r != nil { - if purgeErr := purgePartial(); purgeErr != nil { - return nil, errors.Join(err, purgeErr) - } - } - return nil, err - } - - // Wait for all to be processed. - select { - case <-jetStream.PublishAsyncComplete(): - if err := getErr(); err != nil { - if r != nil { - if purgeErr := purgePartial(); purgeErr != nil { - return nil, errors.Join(err, purgeErr) - } - } - return nil, err - } - case <-time.After(obs.js.opts.wait): - return nil, ErrTimeout - } - - info.ModTime = time.Now().UTC() // This time is not actually the correct time - - // Delete any original chunks. - if einfo != nil && !einfo.Deleted { - echunkSubj := fmt.Sprintf(objChunksPreTmpl, obs.name, einfo.NUID) - if err := obs.js.purgeStream(obs.stream, &StreamPurgeRequest{Subject: echunkSubj}); err != nil { - return info, err - } - } - - // TODO would it be okay to do this to return the info with the correct time? - // With the understanding that it is an extra call to the server. - // Otherwise the time the user gets back is the client time, not the server time. - // return obs.GetInfo(info.Name) - - return info, nil -} - -// GetObjectDigestValue calculates the base64 value of hashed data -func GetObjectDigestValue(data hash.Hash) string { - sha := data.Sum(nil) - return fmt.Sprintf(objDigestTmpl, base64.URLEncoding.EncodeToString(sha[:])) -} - -// DecodeObjectDigest decodes base64 hash -func DecodeObjectDigest(data string) ([]byte, error) { - digest := strings.SplitN(data, "=", 2) - if len(digest) != 2 { - return nil, ErrInvalidDigestFormat - } - return base64.URLEncoding.DecodeString(digest[1]) -} - -// ObjectResult impl. -type objResult struct { - sync.Mutex - info *ObjectInfo - r io.ReadCloser - err error - ctx context.Context - digest hash.Hash - readTimeout time.Duration -} - -func (info *ObjectInfo) isLink() bool { - return info.ObjectMeta.Opts != nil && info.ObjectMeta.Opts.Link != nil -} - -type GetObjectOpt interface { - configureGetObject(opts *getObjectOpts) error -} -type getObjectOpts struct { - ctx context.Context - // Include deleted object in the result. - showDeleted bool -} - -type getObjectFn func(opts *getObjectOpts) error - -func (opt getObjectFn) configureGetObject(opts *getObjectOpts) error { - return opt(opts) -} - -// GetObjectShowDeleted makes Get() return object if it was marked as deleted. -func GetObjectShowDeleted() GetObjectOpt { - return getObjectFn(func(opts *getObjectOpts) error { - opts.showDeleted = true - return nil - }) -} - -// For nats.Context() support. -func (ctx ContextOpt) configureGetObject(opts *getObjectOpts) error { - opts.ctx = ctx - return nil -} - -// Get will pull the object from the underlying stream. -func (obs *obs) Get(name string, opts ...GetObjectOpt) (ObjectResult, error) { - var o getObjectOpts - for _, opt := range opts { - if opt != nil { - if err := opt.configureGetObject(&o); err != nil { - return nil, err - } - } - } - ctx := o.ctx - infoOpts := make([]GetObjectInfoOpt, 0) - if ctx != nil { - infoOpts = append(infoOpts, Context(ctx)) - } - if o.showDeleted { - infoOpts = append(infoOpts, GetObjectInfoShowDeleted()) - } - - // Grab meta info. - info, err := obs.GetInfo(name, infoOpts...) - if err != nil { - return nil, err - } - if info.NUID == _EMPTY_ { - return nil, ErrBadObjectMeta - } - - // Check for object links. If single objects we do a pass through. - if info.isLink() { - if info.ObjectMeta.Opts.Link.Name == _EMPTY_ { - return nil, ErrCantGetBucket - } - - // is the link in the same bucket? - lbuck := info.ObjectMeta.Opts.Link.Bucket - if lbuck == obs.name { - return obs.Get(info.ObjectMeta.Opts.Link.Name) - } - - // different bucket - lobs, err := obs.js.ObjectStore(lbuck) - if err != nil { - return nil, err - } - return lobs.Get(info.ObjectMeta.Opts.Link.Name) - } - - result := &objResult{info: info, ctx: ctx, readTimeout: obs.js.opts.wait} - if info.Size == 0 { - return result, nil - } - - pr, pw := net.Pipe() - result.r = pr - - gotErr := func(m *Msg, err error) { - pw.Close() - m.Sub.Unsubscribe() - result.setErr(err) - } - - // For calculating sum256 - result.digest = sha256.New() - - processChunk := func(m *Msg) { - var err error - if ctx != nil { - select { - case <-ctx.Done(): - if errors.Is(ctx.Err(), context.Canceled) { - err = ctx.Err() - } else { - err = ErrTimeout - } - default: - } - if err != nil { - gotErr(m, err) - return - } - } - - tokens, err := parser.GetMetadataFields(m.Reply) - if err != nil { - gotErr(m, err) - return - } - - // Write to our pipe. - for b := m.Data; len(b) > 0; { - n, err := pw.Write(b) - if err != nil { - gotErr(m, err) - return - } - b = b[n:] - } - // Update sha256 - result.digest.Write(m.Data) - - // Check if we are done. - if tokens[parser.AckNumPendingTokenPos] == objNoPending { - pw.Close() - m.Sub.Unsubscribe() - } - } - - chunkSubj := fmt.Sprintf(objChunksPreTmpl, obs.name, info.NUID) - _, err = obs.js.Subscribe(chunkSubj, processChunk, OrderedConsumer()) - if err != nil { - return nil, err - } - - return result, nil -} - -// Delete will delete the object. -func (obs *obs) Delete(name string) error { - // Grab meta info. - info, err := obs.GetInfo(name, GetObjectInfoShowDeleted()) - if err != nil { - return err - } - if info.NUID == _EMPTY_ { - return ErrBadObjectMeta - } - - // Place a rollup delete marker and publish the info - info.Deleted = true - info.Size, info.Chunks, info.Digest = 0, 0, _EMPTY_ - - if err = publishMeta(info, obs.js); err != nil { - return err - } - - // Purge chunks for the object. - chunkSubj := fmt.Sprintf(objChunksPreTmpl, obs.name, info.NUID) - return obs.js.purgeStream(obs.stream, &StreamPurgeRequest{Subject: chunkSubj}) -} - -func publishMeta(info *ObjectInfo, js JetStreamContext) error { - // marshal the object into json, don't store an actual time - info.ModTime = time.Time{} - data, err := json.Marshal(info) - if err != nil { - return err - } - - // Prepare and publish the message. - mm := NewMsg(fmt.Sprintf(objMetaPreTmpl, info.Bucket, encodeName(info.ObjectMeta.Name))) - mm.Header.Set(MsgRollup, MsgRollupSubject) - mm.Data = data - if _, err := js.PublishMsg(mm); err != nil { - return err - } - - // set the ModTime in case it's returned to the user, even though it's not the correct time. - info.ModTime = time.Now().UTC() - return nil -} - -// AddLink will add a link to another object if it's not deleted and not another link -// name is the name of this link object -// obj is what is being linked too -func (obs *obs) AddLink(name string, obj *ObjectInfo) (*ObjectInfo, error) { - if name == "" { - return nil, ErrNameRequired - } - - // TODO Handle stale info - - if obj == nil || obj.Name == "" { - return nil, ErrObjectRequired - } - if obj.Deleted { - return nil, ErrNoLinkToDeleted - } - if obj.isLink() { - return nil, ErrNoLinkToLink - } - - // If object with link's name is found, error. - // If link with link's name is found, that's okay to overwrite. - // If there was an error that was not ErrObjectNotFound, error. - einfo, err := obs.GetInfo(name, GetObjectInfoShowDeleted()) - if einfo != nil { - if !einfo.isLink() { - return nil, ErrObjectAlreadyExists - } - } else if err != ErrObjectNotFound { - return nil, err - } - - // create the meta for the link - meta := &ObjectMeta{ - Name: name, - Opts: &ObjectMetaOptions{Link: &ObjectLink{Bucket: obj.Bucket, Name: obj.Name}}, - } - info := &ObjectInfo{Bucket: obs.name, NUID: nuid.Next(), ModTime: time.Now().UTC(), ObjectMeta: *meta} - - // put the link object - if err = publishMeta(info, obs.js); err != nil { - return nil, err - } - - return info, nil -} - -// AddBucketLink will add a link to another object store. -func (ob *obs) AddBucketLink(name string, bucket ObjectStore) (*ObjectInfo, error) { - if name == "" { - return nil, ErrNameRequired - } - if bucket == nil { - return nil, ErrBucketRequired - } - bos, ok := bucket.(*obs) - if !ok { - return nil, ErrBucketMalformed - } - - // If object with link's name is found, error. - // If link with link's name is found, that's okay to overwrite. - // If there was an error that was not ErrObjectNotFound, error. - einfo, err := ob.GetInfo(name, GetObjectInfoShowDeleted()) - if einfo != nil { - if !einfo.isLink() { - return nil, ErrObjectAlreadyExists - } - } else if err != ErrObjectNotFound { - return nil, err - } - - // create the meta for the link - meta := &ObjectMeta{ - Name: name, - Opts: &ObjectMetaOptions{Link: &ObjectLink{Bucket: bos.name}}, - } - info := &ObjectInfo{Bucket: ob.name, NUID: nuid.Next(), ObjectMeta: *meta} - - // put the link object - err = publishMeta(info, ob.js) - if err != nil { - return nil, err - } - - return info, nil -} - -// PutBytes is convenience function to put a byte slice into this object store. -func (obs *obs) PutBytes(name string, data []byte, opts ...ObjectOpt) (*ObjectInfo, error) { - return obs.Put(&ObjectMeta{Name: name}, bytes.NewReader(data), opts...) -} - -// GetBytes is a convenience function to pull an object from this object store and return it as a byte slice. -func (obs *obs) GetBytes(name string, opts ...GetObjectOpt) ([]byte, error) { - result, err := obs.Get(name, opts...) - if err != nil { - return nil, err - } - defer result.Close() - - var b bytes.Buffer - if _, err := b.ReadFrom(result); err != nil { - return nil, err - } - return b.Bytes(), nil -} - -// PutString is convenience function to put a string into this object store. -func (obs *obs) PutString(name string, data string, opts ...ObjectOpt) (*ObjectInfo, error) { - return obs.Put(&ObjectMeta{Name: name}, strings.NewReader(data), opts...) -} - -// GetString is a convenience function to pull an object from this object store and return it as a string. -func (obs *obs) GetString(name string, opts ...GetObjectOpt) (string, error) { - result, err := obs.Get(name, opts...) - if err != nil { - return _EMPTY_, err - } - defer result.Close() - - var b bytes.Buffer - if _, err := b.ReadFrom(result); err != nil { - return _EMPTY_, err - } - return b.String(), nil -} - -// PutFile is convenience function to put a file into an object store. -func (obs *obs) PutFile(file string, opts ...ObjectOpt) (*ObjectInfo, error) { - f, err := os.Open(file) - if err != nil { - return nil, err - } - defer f.Close() - return obs.Put(&ObjectMeta{Name: file}, f, opts...) -} - -// GetFile is a convenience function to pull and object and place in a file. -func (obs *obs) GetFile(name, file string, opts ...GetObjectOpt) error { - // Expect file to be new. - f, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE, 0600) - if err != nil { - return err - } - defer f.Close() - - result, err := obs.Get(name, opts...) - if err != nil { - os.Remove(f.Name()) - return err - } - defer result.Close() - - // Stream copy to the file. - _, err = io.Copy(f, result) - return err -} - -type GetObjectInfoOpt interface { - configureGetInfo(opts *getObjectInfoOpts) error -} -type getObjectInfoOpts struct { - ctx context.Context - // Include deleted object in the result. - showDeleted bool -} - -type getObjectInfoFn func(opts *getObjectInfoOpts) error - -func (opt getObjectInfoFn) configureGetInfo(opts *getObjectInfoOpts) error { - return opt(opts) -} - -// GetObjectInfoShowDeleted makes GetInfo() return object if it was marked as deleted. -func GetObjectInfoShowDeleted() GetObjectInfoOpt { - return getObjectInfoFn(func(opts *getObjectInfoOpts) error { - opts.showDeleted = true - return nil - }) -} - -// For nats.Context() support. -func (ctx ContextOpt) configureGetInfo(opts *getObjectInfoOpts) error { - opts.ctx = ctx - return nil -} - -// GetInfo will retrieve the current information for the object. -func (obs *obs) GetInfo(name string, opts ...GetObjectInfoOpt) (*ObjectInfo, error) { - // Grab last meta value we have. - if name == "" { - return nil, ErrNameRequired - } - var o getObjectInfoOpts - for _, opt := range opts { - if opt != nil { - if err := opt.configureGetInfo(&o); err != nil { - return nil, err - } - } - } - - metaSubj := fmt.Sprintf(objMetaPreTmpl, obs.name, encodeName(name)) // used as data in a JS API call - stream := fmt.Sprintf(objNameTmpl, obs.name) - - m, err := obs.js.GetLastMsg(stream, metaSubj) - if err != nil { - if errors.Is(err, ErrMsgNotFound) { - err = ErrObjectNotFound - } - return nil, err - } - var info ObjectInfo - if err := json.Unmarshal(m.Data, &info); err != nil { - return nil, ErrBadObjectMeta - } - if !o.showDeleted && info.Deleted { - return nil, ErrObjectNotFound - } - info.ModTime = m.Time - return &info, nil -} - -// UpdateMeta will update the meta for the object. -func (obs *obs) UpdateMeta(name string, meta *ObjectMeta) error { - if meta == nil { - return ErrBadObjectMeta - } - - // Grab the current meta. - info, err := obs.GetInfo(name) - if err != nil { - if errors.Is(err, ErrObjectNotFound) { - return ErrUpdateMetaDeleted - } - return err - } - - // If the new name is different from the old, and it exists, error - // If there was an error that was not ErrObjectNotFound, error. - if name != meta.Name { - existingInfo, err := obs.GetInfo(meta.Name, GetObjectInfoShowDeleted()) - if err != nil && !errors.Is(err, ErrObjectNotFound) { - return err - } - if err == nil && !existingInfo.Deleted { - return ErrObjectAlreadyExists - } - } - - // Update Meta prevents update of ObjectMetaOptions (Link, ChunkSize) - // These should only be updated internally when appropriate. - info.Name = meta.Name - info.Description = meta.Description - info.Headers = meta.Headers - info.Metadata = meta.Metadata - - // Prepare the meta message - if err = publishMeta(info, obs.js); err != nil { - return err - } - - // did the name of this object change? We just stored the meta under the new name - // so delete the meta from the old name via purge stream for subject - if name != meta.Name { - metaSubj := fmt.Sprintf(objMetaPreTmpl, obs.name, encodeName(name)) - return obs.js.purgeStream(obs.stream, &StreamPurgeRequest{Subject: metaSubj}) - } - - return nil -} - -// Seal will seal the object store, no further modifications will be allowed. -func (obs *obs) Seal() error { - stream := fmt.Sprintf(objNameTmpl, obs.name) - si, err := obs.js.StreamInfo(stream) - if err != nil { - return err - } - // Seal the stream from being able to take on more messages. - cfg := si.Config - cfg.Sealed = true - _, err = obs.js.UpdateStream(&cfg) - return err -} - -// Implementation for Watch -type objWatcher struct { - updates chan *ObjectInfo - sub *Subscription -} - -// Updates returns the interior channel. -func (w *objWatcher) Updates() <-chan *ObjectInfo { - if w == nil { - return nil - } - return w.updates -} - -// Stop will unsubscribe from the watcher. -func (w *objWatcher) Stop() error { - if w == nil { - return nil - } - return w.sub.Unsubscribe() -} - -// Watch for changes in the underlying store and receive meta information updates. -func (obs *obs) Watch(opts ...WatchOpt) (ObjectWatcher, error) { - var o watchOpts - for _, opt := range opts { - if opt != nil { - if err := opt.configureWatcher(&o); err != nil { - return nil, err - } - } - } - - var initDoneMarker bool - - w := &objWatcher{updates: make(chan *ObjectInfo, 32)} - - update := func(m *Msg) { - var info ObjectInfo - if err := json.Unmarshal(m.Data, &info); err != nil { - return // TODO(dlc) - Communicate this upwards? - } - meta, err := m.Metadata() - if err != nil { - return - } - - if !o.ignoreDeletes || !info.Deleted { - info.ModTime = meta.Timestamp - w.updates <- &info - } - - // if UpdatesOnly is set, no not send nil to the channel - // as it would always be triggered after initializing the watcher - if !initDoneMarker && meta.NumPending == 0 { - initDoneMarker = true - w.updates <- nil - } - } - - allMeta := fmt.Sprintf(objAllMetaPreTmpl, obs.name) - _, err := obs.js.GetLastMsg(obs.stream, allMeta) - // if there are no messages on the stream and we are not watching - // updates only, send nil to the channel to indicate that the initial - // watch is done - if !o.updatesOnly { - if errors.Is(err, ErrMsgNotFound) { - initDoneMarker = true - w.updates <- nil - } - } else { - // if UpdatesOnly was used, mark initialization as complete - initDoneMarker = true - } - - // Used ordered consumer to deliver results. - subOpts := []SubOpt{OrderedConsumer()} - if !o.includeHistory { - subOpts = append(subOpts, DeliverLastPerSubject()) - } - if o.updatesOnly { - subOpts = append(subOpts, DeliverNew()) - } - sub, err := obs.js.Subscribe(allMeta, update, subOpts...) - if err != nil { - return nil, err - } - w.sub = sub - return w, nil -} - -type ListObjectsOpt interface { - configureListObjects(opts *listObjectOpts) error -} -type listObjectOpts struct { - ctx context.Context - // Include deleted objects in the result channel. - showDeleted bool -} - -type listObjectsFn func(opts *listObjectOpts) error - -func (opt listObjectsFn) configureListObjects(opts *listObjectOpts) error { - return opt(opts) -} - -// ListObjectsShowDeleted makes ListObjects() return deleted objects. -func ListObjectsShowDeleted() ListObjectsOpt { - return listObjectsFn(func(opts *listObjectOpts) error { - opts.showDeleted = true - return nil - }) -} - -// For nats.Context() support. -func (ctx ContextOpt) configureListObjects(opts *listObjectOpts) error { - opts.ctx = ctx - return nil -} - -// List will list all the objects in this store. -func (obs *obs) List(opts ...ListObjectsOpt) ([]*ObjectInfo, error) { - var o listObjectOpts - for _, opt := range opts { - if opt != nil { - if err := opt.configureListObjects(&o); err != nil { - return nil, err - } - } - } - watchOpts := make([]WatchOpt, 0) - if !o.showDeleted { - watchOpts = append(watchOpts, IgnoreDeletes()) - } - watcher, err := obs.Watch(watchOpts...) - if err != nil { - return nil, err - } - defer watcher.Stop() - if o.ctx == nil { - o.ctx = context.Background() - } - - var objs []*ObjectInfo - updates := watcher.Updates() -Updates: - for { - select { - case entry := <-updates: - if entry == nil { - break Updates - } - objs = append(objs, entry) - case <-o.ctx.Done(): - return nil, o.ctx.Err() - } - } - if len(objs) == 0 { - return nil, ErrNoObjectsFound - } - return objs, nil -} - -// ObjectBucketStatus represents status of a Bucket, implements ObjectStoreStatus -type ObjectBucketStatus struct { - nfo *StreamInfo - bucket string -} - -// Bucket is the name of the bucket -func (s *ObjectBucketStatus) Bucket() string { return s.bucket } - -// Description is the description supplied when creating the bucket -func (s *ObjectBucketStatus) Description() string { return s.nfo.Config.Description } - -// TTL indicates how long objects are kept in the bucket -func (s *ObjectBucketStatus) TTL() time.Duration { return s.nfo.Config.MaxAge } - -// Storage indicates the underlying JetStream storage technology used to store data -func (s *ObjectBucketStatus) Storage() StorageType { return s.nfo.Config.Storage } - -// Replicas indicates how many storage replicas are kept for the data in the bucket -func (s *ObjectBucketStatus) Replicas() int { return s.nfo.Config.Replicas } - -// Sealed indicates the stream is sealed and cannot be modified in any way -func (s *ObjectBucketStatus) Sealed() bool { return s.nfo.Config.Sealed } - -// Size is the combined size of all data in the bucket including metadata, in bytes -func (s *ObjectBucketStatus) Size() uint64 { return s.nfo.State.Bytes } - -// BackingStore indicates what technology is used for storage of the bucket -func (s *ObjectBucketStatus) BackingStore() string { return "JetStream" } - -// Metadata is the metadata supplied when creating the bucket -func (s *ObjectBucketStatus) Metadata() map[string]string { return s.nfo.Config.Metadata } - -// StreamInfo is the stream info retrieved to create the status -func (s *ObjectBucketStatus) StreamInfo() *StreamInfo { return s.nfo } - -// IsCompressed indicates if the data is compressed on disk -func (s *ObjectBucketStatus) IsCompressed() bool { return s.nfo.Config.Compression != NoCompression } - -// Status retrieves run-time status about a bucket -func (obs *obs) Status() (ObjectStoreStatus, error) { - nfo, err := obs.js.StreamInfo(obs.stream) - if err != nil { - return nil, err - } - - status := &ObjectBucketStatus{ - nfo: nfo, - bucket: obs.name, - } - - return status, nil -} - -// Read impl. -func (o *objResult) Read(p []byte) (n int, err error) { - o.Lock() - defer o.Unlock() - readDeadline := time.Now().Add(o.readTimeout) - if ctx := o.ctx; ctx != nil { - if deadline, ok := ctx.Deadline(); ok { - readDeadline = deadline - } - select { - case <-ctx.Done(): - if ctx.Err() == context.Canceled { - o.err = ctx.Err() - } else { - o.err = ErrTimeout - } - default: - } - } - if o.err != nil { - return 0, o.err - } - if o.r == nil { - return 0, io.EOF - } - - r := o.r.(net.Conn) - r.SetReadDeadline(readDeadline) - n, err = r.Read(p) - if err, ok := err.(net.Error); ok && err.Timeout() { - if ctx := o.ctx; ctx != nil { - select { - case <-ctx.Done(): - if ctx.Err() == context.Canceled { - return 0, ctx.Err() - } else { - return 0, ErrTimeout - } - default: - err = nil - } - } - } - if err == io.EOF { - // Make sure the digest matches. - sha := o.digest.Sum(nil) - rsha, decodeErr := DecodeObjectDigest(o.info.Digest) - if decodeErr != nil { - o.err = decodeErr - return 0, o.err - } - if !bytes.Equal(sha[:], rsha) { - o.err = ErrDigestMismatch - return 0, o.err - } - } - return n, err -} - -// Close impl. -func (o *objResult) Close() error { - o.Lock() - defer o.Unlock() - if o.r == nil { - return nil - } - return o.r.Close() -} - -func (o *objResult) setErr(err error) { - o.Lock() - defer o.Unlock() - o.err = err -} - -func (o *objResult) Info() (*ObjectInfo, error) { - o.Lock() - defer o.Unlock() - return o.info, o.err -} - -func (o *objResult) Error() error { - o.Lock() - defer o.Unlock() - return o.err -} - -// ObjectStoreNames is used to retrieve a list of bucket names -func (js *js) ObjectStoreNames(opts ...ObjectOpt) <-chan string { - var o objOpts - for _, opt := range opts { - if opt != nil { - if err := opt.configureObject(&o); err != nil { - return nil - } - } - } - ch := make(chan string) - var cancel context.CancelFunc - if o.ctx == nil { - o.ctx, cancel = context.WithTimeout(context.Background(), defaultRequestWait) - } - l := &streamLister{js: js} - l.js.opts.streamListSubject = fmt.Sprintf(objAllChunksPreTmpl, "*") - l.js.opts.ctx = o.ctx - go func() { - if cancel != nil { - defer cancel() - } - defer close(ch) - for l.Next() { - for _, info := range l.Page() { - if !strings.HasPrefix(info.Config.Name, "OBJ_") { - continue - } - select { - case ch <- info.Config.Name: - case <-o.ctx.Done(): - return - } - } - } - }() - - return ch -} - -// ObjectStores is used to retrieve a list of bucket statuses -func (js *js) ObjectStores(opts ...ObjectOpt) <-chan ObjectStoreStatus { - var o objOpts - for _, opt := range opts { - if opt != nil { - if err := opt.configureObject(&o); err != nil { - return nil - } - } - } - ch := make(chan ObjectStoreStatus) - var cancel context.CancelFunc - if o.ctx == nil { - o.ctx, cancel = context.WithTimeout(context.Background(), defaultRequestWait) - } - l := &streamLister{js: js} - l.js.opts.streamListSubject = fmt.Sprintf(objAllChunksPreTmpl, "*") - l.js.opts.ctx = o.ctx - go func() { - if cancel != nil { - defer cancel() - } - defer close(ch) - for l.Next() { - for _, info := range l.Page() { - if !strings.HasPrefix(info.Config.Name, "OBJ_") { - continue - } - select { - case ch <- &ObjectBucketStatus{ - nfo: info, - bucket: strings.TrimPrefix(info.Config.Name, "OBJ_"), - }: - case <-o.ctx.Done(): - return - } - } - } - }() - - return ch -} diff --git a/vendor/github.com/nats-io/nats.go/parser.go b/vendor/github.com/nats-io/nats.go/parser.go deleted file mode 100644 index 70204e60d..000000000 --- a/vendor/github.com/nats-io/nats.go/parser.go +++ /dev/null @@ -1,554 +0,0 @@ -// Copyright 2012-2023 The NATS 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 nats - -import ( - "fmt" -) - -type msgArg struct { - subject []byte - reply []byte - sid int64 - hdr int - size int -} - -const MAX_CONTROL_LINE_SIZE = 4096 - -type parseState struct { - state int - as int - drop int - hdr int - ma msgArg - argBuf []byte - msgBuf []byte - msgCopied bool - scratch [MAX_CONTROL_LINE_SIZE]byte -} - -const ( - OP_START = iota - OP_PLUS - OP_PLUS_O - OP_PLUS_OK - OP_MINUS - OP_MINUS_E - OP_MINUS_ER - OP_MINUS_ERR - OP_MINUS_ERR_SPC - MINUS_ERR_ARG - OP_M - OP_MS - OP_MSG - OP_MSG_SPC - MSG_ARG - MSG_PAYLOAD - MSG_END - OP_H - OP_P - OP_PI - OP_PIN - OP_PING - OP_PO - OP_PON - OP_PONG - OP_I - OP_IN - OP_INF - OP_INFO - OP_INFO_SPC - INFO_ARG -) - -// parse is the fast protocol parser engine. -func (nc *Conn) parse(buf []byte) error { - var i int - var b byte - - // Move to loop instead of range syntax to allow jumping of i - for i = 0; i < len(buf); i++ { - b = buf[i] - - switch nc.ps.state { - case OP_START: - switch b { - case 'M', 'm': - nc.ps.state = OP_M - nc.ps.hdr = -1 - nc.ps.ma.hdr = -1 - case 'H', 'h': - nc.ps.state = OP_H - nc.ps.hdr = 0 - nc.ps.ma.hdr = 0 - case 'P', 'p': - nc.ps.state = OP_P - case '+': - nc.ps.state = OP_PLUS - case '-': - nc.ps.state = OP_MINUS - case 'I', 'i': - nc.ps.state = OP_I - default: - goto parseErr - } - case OP_H: - switch b { - case 'M', 'm': - nc.ps.state = OP_M - default: - goto parseErr - } - case OP_M: - switch b { - case 'S', 's': - nc.ps.state = OP_MS - default: - goto parseErr - } - case OP_MS: - switch b { - case 'G', 'g': - nc.ps.state = OP_MSG - default: - goto parseErr - } - case OP_MSG: - switch b { - case ' ', '\t': - nc.ps.state = OP_MSG_SPC - default: - goto parseErr - } - case OP_MSG_SPC: - switch b { - case ' ', '\t': - continue - default: - nc.ps.state = MSG_ARG - nc.ps.as = i - } - case MSG_ARG: - switch b { - case '\r': - nc.ps.drop = 1 - case '\n': - var arg []byte - if nc.ps.argBuf != nil { - arg = nc.ps.argBuf - } else { - arg = buf[nc.ps.as : i-nc.ps.drop] - } - if err := nc.processMsgArgs(arg); err != nil { - return err - } - nc.ps.drop, nc.ps.as, nc.ps.state = 0, i+1, MSG_PAYLOAD - - // jump ahead with the index. If this overruns - // what is left we fall out and process a split buffer. - i = nc.ps.as + nc.ps.ma.size - 1 - default: - if nc.ps.argBuf != nil { - nc.ps.argBuf = append(nc.ps.argBuf, b) - } - } - case MSG_PAYLOAD: - if nc.ps.msgBuf != nil { - if len(nc.ps.msgBuf) >= nc.ps.ma.size { - nc.processMsg(nc.ps.msgBuf) - nc.ps.argBuf, nc.ps.msgBuf, nc.ps.msgCopied, nc.ps.state = nil, nil, false, MSG_END - } else { - // copy as much as we can to the buffer and skip ahead. - toCopy := nc.ps.ma.size - len(nc.ps.msgBuf) - avail := len(buf) - i - - if avail < toCopy { - toCopy = avail - } - - if toCopy > 0 { - start := len(nc.ps.msgBuf) - // This is needed for copy to work. - nc.ps.msgBuf = nc.ps.msgBuf[:start+toCopy] - copy(nc.ps.msgBuf[start:], buf[i:i+toCopy]) - // Update our index - i = (i + toCopy) - 1 - } else { - nc.ps.msgBuf = append(nc.ps.msgBuf, b) - } - } - } else if i-nc.ps.as >= nc.ps.ma.size { - nc.processMsg(buf[nc.ps.as:i]) - nc.ps.argBuf, nc.ps.msgBuf, nc.ps.msgCopied, nc.ps.state = nil, nil, false, MSG_END - } - case MSG_END: - switch b { - case '\n': - nc.ps.drop, nc.ps.as, nc.ps.state = 0, i+1, OP_START - default: - continue - } - case OP_PLUS: - switch b { - case 'O', 'o': - nc.ps.state = OP_PLUS_O - default: - goto parseErr - } - case OP_PLUS_O: - switch b { - case 'K', 'k': - nc.ps.state = OP_PLUS_OK - default: - goto parseErr - } - case OP_PLUS_OK: - switch b { - case '\n': - nc.processOK() - nc.ps.drop, nc.ps.state = 0, OP_START - } - case OP_MINUS: - switch b { - case 'E', 'e': - nc.ps.state = OP_MINUS_E - default: - goto parseErr - } - case OP_MINUS_E: - switch b { - case 'R', 'r': - nc.ps.state = OP_MINUS_ER - default: - goto parseErr - } - case OP_MINUS_ER: - switch b { - case 'R', 'r': - nc.ps.state = OP_MINUS_ERR - default: - goto parseErr - } - case OP_MINUS_ERR: - switch b { - case ' ', '\t': - nc.ps.state = OP_MINUS_ERR_SPC - default: - goto parseErr - } - case OP_MINUS_ERR_SPC: - switch b { - case ' ', '\t': - continue - default: - nc.ps.state = MINUS_ERR_ARG - nc.ps.as = i - } - case MINUS_ERR_ARG: - switch b { - case '\r': - nc.ps.drop = 1 - case '\n': - var arg []byte - if nc.ps.argBuf != nil { - arg = nc.ps.argBuf - nc.ps.argBuf = nil - } else { - arg = buf[nc.ps.as : i-nc.ps.drop] - } - nc.processErr(string(arg)) - nc.ps.drop, nc.ps.as, nc.ps.state = 0, i+1, OP_START - default: - if nc.ps.argBuf != nil { - nc.ps.argBuf = append(nc.ps.argBuf, b) - } - } - case OP_P: - switch b { - case 'I', 'i': - nc.ps.state = OP_PI - case 'O', 'o': - nc.ps.state = OP_PO - default: - goto parseErr - } - case OP_PO: - switch b { - case 'N', 'n': - nc.ps.state = OP_PON - default: - goto parseErr - } - case OP_PON: - switch b { - case 'G', 'g': - nc.ps.state = OP_PONG - default: - goto parseErr - } - case OP_PONG: - switch b { - case '\n': - nc.processPong() - nc.ps.drop, nc.ps.state = 0, OP_START - } - case OP_PI: - switch b { - case 'N', 'n': - nc.ps.state = OP_PIN - default: - goto parseErr - } - case OP_PIN: - switch b { - case 'G', 'g': - nc.ps.state = OP_PING - default: - goto parseErr - } - case OP_PING: - switch b { - case '\n': - nc.processPing() - nc.ps.drop, nc.ps.state = 0, OP_START - } - case OP_I: - switch b { - case 'N', 'n': - nc.ps.state = OP_IN - default: - goto parseErr - } - case OP_IN: - switch b { - case 'F', 'f': - nc.ps.state = OP_INF - default: - goto parseErr - } - case OP_INF: - switch b { - case 'O', 'o': - nc.ps.state = OP_INFO - default: - goto parseErr - } - case OP_INFO: - switch b { - case ' ', '\t': - nc.ps.state = OP_INFO_SPC - default: - goto parseErr - } - case OP_INFO_SPC: - switch b { - case ' ', '\t': - continue - default: - nc.ps.state = INFO_ARG - nc.ps.as = i - } - case INFO_ARG: - switch b { - case '\r': - nc.ps.drop = 1 - case '\n': - var arg []byte - if nc.ps.argBuf != nil { - arg = nc.ps.argBuf - nc.ps.argBuf = nil - } else { - arg = buf[nc.ps.as : i-nc.ps.drop] - } - nc.processAsyncInfo(arg) - nc.ps.drop, nc.ps.as, nc.ps.state = 0, i+1, OP_START - default: - if nc.ps.argBuf != nil { - nc.ps.argBuf = append(nc.ps.argBuf, b) - } - } - default: - goto parseErr - } - } - // Check for split buffer scenarios - if (nc.ps.state == MSG_ARG || nc.ps.state == MINUS_ERR_ARG || nc.ps.state == INFO_ARG) && nc.ps.argBuf == nil { - nc.ps.argBuf = nc.ps.scratch[:0] - nc.ps.argBuf = append(nc.ps.argBuf, buf[nc.ps.as:i-nc.ps.drop]...) - // FIXME, check max len - } - // Check for split msg - if nc.ps.state == MSG_PAYLOAD && nc.ps.msgBuf == nil { - // We need to clone the msgArg if it is still referencing the - // read buffer and we are not able to process the msg. - if nc.ps.argBuf == nil { - nc.cloneMsgArg() - } - - // If we will overflow the scratch buffer, just create a - // new buffer to hold the split message. - if nc.ps.ma.size > cap(nc.ps.scratch)-len(nc.ps.argBuf) { - lrem := len(buf[nc.ps.as:]) - - nc.ps.msgBuf = make([]byte, lrem, nc.ps.ma.size) - copy(nc.ps.msgBuf, buf[nc.ps.as:]) - nc.ps.msgCopied = true - } else { - nc.ps.msgBuf = nc.ps.scratch[len(nc.ps.argBuf):len(nc.ps.argBuf)] - nc.ps.msgBuf = append(nc.ps.msgBuf, (buf[nc.ps.as:])...) - } - } - - return nil - -parseErr: - return fmt.Errorf("nats: Parse Error [%d]: '%s'", nc.ps.state, buf[i:]) -} - -// cloneMsgArg is used when the split buffer scenario has the pubArg in the existing read buffer, but -// we need to hold onto it into the next read. -func (nc *Conn) cloneMsgArg() { - nc.ps.argBuf = nc.ps.scratch[:0] - nc.ps.argBuf = append(nc.ps.argBuf, nc.ps.ma.subject...) - nc.ps.argBuf = append(nc.ps.argBuf, nc.ps.ma.reply...) - nc.ps.ma.subject = nc.ps.argBuf[:len(nc.ps.ma.subject)] - if nc.ps.ma.reply != nil { - nc.ps.ma.reply = nc.ps.argBuf[len(nc.ps.ma.subject):] - } -} - -const argsLenMax = 4 - -func (nc *Conn) processMsgArgs(arg []byte) error { - // Use separate function for header based messages. - if nc.ps.hdr >= 0 { - return nc.processHeaderMsgArgs(arg) - } - - // Unroll splitArgs to avoid runtime/heap issues - a := [argsLenMax][]byte{} - args := a[:0] - start := -1 - for i, b := range arg { - switch b { - case ' ', '\t', '\r', '\n': - if start >= 0 { - args = append(args, arg[start:i]) - start = -1 - } - default: - if start < 0 { - start = i - } - } - } - if start >= 0 { - args = append(args, arg[start:]) - } - - switch len(args) { - case 3: - nc.ps.ma.subject = args[0] - nc.ps.ma.sid = parseInt64(args[1]) - nc.ps.ma.reply = nil - nc.ps.ma.size = int(parseInt64(args[2])) - case 4: - nc.ps.ma.subject = args[0] - nc.ps.ma.sid = parseInt64(args[1]) - nc.ps.ma.reply = args[2] - nc.ps.ma.size = int(parseInt64(args[3])) - default: - return fmt.Errorf("nats: processMsgArgs Parse Error: '%s'", arg) - } - if nc.ps.ma.sid < 0 { - return fmt.Errorf("nats: processMsgArgs Bad or Missing Sid: '%s'", arg) - } - if nc.ps.ma.size < 0 { - return fmt.Errorf("nats: processMsgArgs Bad or Missing Size: '%s'", arg) - } - return nil -} - -// processHeaderMsgArgs is for a header based message. -func (nc *Conn) processHeaderMsgArgs(arg []byte) error { - // Unroll splitArgs to avoid runtime/heap issues - a := [argsLenMax][]byte{} - args := a[:0] - start := -1 - for i, b := range arg { - switch b { - case ' ', '\t', '\r', '\n': - if start >= 0 { - args = append(args, arg[start:i]) - start = -1 - } - default: - if start < 0 { - start = i - } - } - } - if start >= 0 { - args = append(args, arg[start:]) - } - - switch len(args) { - case 4: - nc.ps.ma.subject = args[0] - nc.ps.ma.sid = parseInt64(args[1]) - nc.ps.ma.reply = nil - nc.ps.ma.hdr = int(parseInt64(args[2])) - nc.ps.ma.size = int(parseInt64(args[3])) - case 5: - nc.ps.ma.subject = args[0] - nc.ps.ma.sid = parseInt64(args[1]) - nc.ps.ma.reply = args[2] - nc.ps.ma.hdr = int(parseInt64(args[3])) - nc.ps.ma.size = int(parseInt64(args[4])) - default: - return fmt.Errorf("nats: processHeaderMsgArgs Parse Error: '%s'", arg) - } - if nc.ps.ma.sid < 0 { - return fmt.Errorf("nats: processHeaderMsgArgs Bad or Missing Sid: '%s'", arg) - } - if nc.ps.ma.hdr < 0 || nc.ps.ma.hdr > nc.ps.ma.size { - return fmt.Errorf("nats: processHeaderMsgArgs Bad or Missing Header Size: '%s'", arg) - } - if nc.ps.ma.size < 0 { - return fmt.Errorf("nats: processHeaderMsgArgs Bad or Missing Size: '%s'", arg) - } - return nil -} - -// ASCII numbers 0-9 -const ( - ascii_0 = 48 - ascii_9 = 57 -) - -// parseInt64 expects decimal positive numbers. We -// return -1 to signal error -func parseInt64(d []byte) (n int64) { - if len(d) == 0 { - return -1 - } - for _, dec := range d { - if dec < ascii_0 || dec > ascii_9 { - return -1 - } - n = n*10 + (int64(dec) - ascii_0) - } - return n -} diff --git a/vendor/github.com/nats-io/nats.go/rand.go b/vendor/github.com/nats-io/nats.go/rand.go deleted file mode 100644 index 0cdee0acd..000000000 --- a/vendor/github.com/nats-io/nats.go/rand.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2023 The NATS 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. - -//go:build !go1.20 -// +build !go1.20 - -// A Go client for the NATS messaging system (https://nats.io). -package nats - -import ( - "math/rand" - "time" -) - -func init() { - // This is not needed since Go 1.20 because now rand.Seed always happens - // by default (uses runtime.fastrand64 instead as source). - rand.Seed(time.Now().UnixNano()) -} diff --git a/vendor/github.com/nats-io/nats.go/testing_internal.go b/vendor/github.com/nats-io/nats.go/testing_internal.go deleted file mode 100644 index 18397026a..000000000 --- a/vendor/github.com/nats-io/nats.go/testing_internal.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2023 The NATS 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. - -//go:build internal_testing -// +build internal_testing - -// Functions in this file are only available when building nats.go with the -// internal_testing build tag. They are used by the nats.go test suite. -package nats - -// AddMsgFilter adds a message filter for the given subject -// to the connection. The filter will be called for each -// message received on the subject. If the filter returns -// nil, the message will be dropped. -func (nc *Conn) AddMsgFilter(subject string, filter msgFilter) { - nc.subsMu.Lock() - defer nc.subsMu.Unlock() - - if nc.filters == nil { - nc.filters = make(map[string]msgFilter) - } - nc.filters[subject] = filter -} - -// RemoveMsgFilter removes a message filter for the given subject. -func (nc *Conn) RemoveMsgFilter(subject string) { - nc.subsMu.Lock() - defer nc.subsMu.Unlock() - - if nc.filters != nil { - delete(nc.filters, subject) - if len(nc.filters) == 0 { - nc.filters = nil - } - } -} - -// IsJSControlMessage returns true if the message is a JetStream control message. -func IsJSControlMessage(msg *Msg) (bool, int) { - return isJSControlMessage(msg) -} - -// CloseTCPConn closes the underlying TCP connection. -// It can be used to simulate a disconnect. -func (nc *Conn) CloseTCPConn() { - nc.mu.Lock() - defer nc.mu.Unlock() - nc.conn.Close() -} diff --git a/vendor/github.com/nats-io/nats.go/timer.go b/vendor/github.com/nats-io/nats.go/timer.go deleted file mode 100644 index 6edeb4cf8..000000000 --- a/vendor/github.com/nats-io/nats.go/timer.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2017-2022 The NATS 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 nats - -import ( - "sync" - "time" -) - -// global pool of *time.Timer's. can be used by multiple goroutines concurrently. -var globalTimerPool timerPool - -// timerPool provides GC-able pooling of *time.Timer's. -// can be used by multiple goroutines concurrently. -type timerPool struct { - p sync.Pool -} - -// Get returns a timer that completes after the given duration. -func (tp *timerPool) Get(d time.Duration) *time.Timer { - if t, ok := tp.p.Get().(*time.Timer); ok && t != nil { - t.Reset(d) - return t - } - - return time.NewTimer(d) -} - -// Put pools the given timer. -// -// There is no need to call t.Stop() before calling Put. -// -// Put will try to stop the timer before pooling. If the -// given timer already expired, Put will read the unreceived -// value if there is one. -func (tp *timerPool) Put(t *time.Timer) { - if !t.Stop() { - select { - case <-t.C: - default: - } - } - - tp.p.Put(t) -} diff --git a/vendor/github.com/nats-io/nats.go/util/tls.go b/vendor/github.com/nats-io/nats.go/util/tls.go deleted file mode 100644 index af9f51f05..000000000 --- a/vendor/github.com/nats-io/nats.go/util/tls.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2017-2022 The NATS 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. - -//go:build go1.8 -// +build go1.8 - -package util - -import "crypto/tls" - -// CloneTLSConfig returns a copy of c. -func CloneTLSConfig(c *tls.Config) *tls.Config { - if c == nil { - return &tls.Config{} - } - - return c.Clone() -} diff --git a/vendor/github.com/nats-io/nats.go/util/tls_go17.go b/vendor/github.com/nats-io/nats.go/util/tls_go17.go deleted file mode 100644 index 44d46b42d..000000000 --- a/vendor/github.com/nats-io/nats.go/util/tls_go17.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2016-2022 The NATS 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. - -//go:build go1.7 && !go1.8 -// +build go1.7,!go1.8 - -package util - -import ( - "crypto/tls" -) - -// CloneTLSConfig returns a copy of c. Only the exported fields are copied. -// This is temporary, until this is provided by the language. -// https://go-review.googlesource.com/#/c/28075/ -func CloneTLSConfig(c *tls.Config) *tls.Config { - return &tls.Config{ - Rand: c.Rand, - Time: c.Time, - Certificates: c.Certificates, - NameToCertificate: c.NameToCertificate, - GetCertificate: c.GetCertificate, - RootCAs: c.RootCAs, - NextProtos: c.NextProtos, - ServerName: c.ServerName, - ClientAuth: c.ClientAuth, - ClientCAs: c.ClientCAs, - InsecureSkipVerify: c.InsecureSkipVerify, - CipherSuites: c.CipherSuites, - PreferServerCipherSuites: c.PreferServerCipherSuites, - SessionTicketsDisabled: c.SessionTicketsDisabled, - SessionTicketKey: c.SessionTicketKey, - ClientSessionCache: c.ClientSessionCache, - MinVersion: c.MinVersion, - MaxVersion: c.MaxVersion, - CurvePreferences: c.CurvePreferences, - DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled, - Renegotiation: c.Renegotiation, - } -} diff --git a/vendor/github.com/nats-io/nats.go/ws.go b/vendor/github.com/nats-io/nats.go/ws.go deleted file mode 100644 index 2c2d421a8..000000000 --- a/vendor/github.com/nats-io/nats.go/ws.go +++ /dev/null @@ -1,780 +0,0 @@ -// Copyright 2021-2023 The NATS 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 nats - -import ( - "bufio" - "bytes" - "crypto/rand" - "crypto/sha1" - "encoding/base64" - "encoding/binary" - "errors" - "fmt" - "io" - mrand "math/rand" - "net/http" - "net/url" - "strings" - "time" - "unicode/utf8" - - "github.com/klauspost/compress/flate" -) - -type wsOpCode int - -const ( - // From https://tools.ietf.org/html/rfc6455#section-5.2 - wsTextMessage = wsOpCode(1) - wsBinaryMessage = wsOpCode(2) - wsCloseMessage = wsOpCode(8) - wsPingMessage = wsOpCode(9) - wsPongMessage = wsOpCode(10) - - wsFinalBit = 1 << 7 - wsRsv1Bit = 1 << 6 // Used for compression, from https://tools.ietf.org/html/rfc7692#section-6 - wsRsv2Bit = 1 << 5 - wsRsv3Bit = 1 << 4 - - wsMaskBit = 1 << 7 - - wsContinuationFrame = 0 - wsMaxFrameHeaderSize = 14 - wsMaxControlPayloadSize = 125 - wsCloseSatusSize = 2 - - // From https://tools.ietf.org/html/rfc6455#section-11.7 - wsCloseStatusNormalClosure = 1000 - wsCloseStatusNoStatusReceived = 1005 - wsCloseStatusAbnormalClosure = 1006 - wsCloseStatusInvalidPayloadData = 1007 - - wsScheme = "ws" - wsSchemeTLS = "wss" - - wsPMCExtension = "permessage-deflate" // per-message compression - wsPMCSrvNoCtx = "server_no_context_takeover" - wsPMCCliNoCtx = "client_no_context_takeover" - wsPMCReqHeaderValue = wsPMCExtension + "; " + wsPMCSrvNoCtx + "; " + wsPMCCliNoCtx -) - -// From https://tools.ietf.org/html/rfc6455#section-1.3 -var wsGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11") - -var compressFinalBlock = []byte{0x00, 0x00, 0xff, 0xff, 0x01, 0x00, 0x00, 0xff, 0xff} - -type websocketReader struct { - r io.Reader - pending [][]byte - ib []byte - ff bool - fc bool - nl bool - dc *wsDecompressor - nc *Conn -} - -type wsDecompressor struct { - flate io.ReadCloser - bufs [][]byte - off int -} - -type websocketWriter struct { - w io.Writer - compress bool - compressor *flate.Writer - ctrlFrames [][]byte // pending frames that should be sent at the next Write() - cm []byte // close message that needs to be sent when everything else has been sent - cmDone bool // a close message has been added or sent (never going back to false) - noMoreSend bool // if true, even if there is a Write() call, we should not send anything -} - -func (d *wsDecompressor) Read(dst []byte) (int, error) { - if len(dst) == 0 { - return 0, nil - } - if len(d.bufs) == 0 { - return 0, io.EOF - } - copied := 0 - rem := len(dst) - for buf := d.bufs[0]; buf != nil && rem > 0; { - n := len(buf[d.off:]) - if n > rem { - n = rem - } - copy(dst[copied:], buf[d.off:d.off+n]) - copied += n - rem -= n - d.off += n - buf = d.nextBuf() - } - return copied, nil -} - -func (d *wsDecompressor) nextBuf() []byte { - // We still have remaining data in the first buffer - if d.off != len(d.bufs[0]) { - return d.bufs[0] - } - // We read the full first buffer. Reset offset. - d.off = 0 - // We were at the last buffer, so we are done. - if len(d.bufs) == 1 { - d.bufs = nil - return nil - } - // Here we move to the next buffer. - d.bufs = d.bufs[1:] - return d.bufs[0] -} - -func (d *wsDecompressor) ReadByte() (byte, error) { - if len(d.bufs) == 0 { - return 0, io.EOF - } - b := d.bufs[0][d.off] - d.off++ - d.nextBuf() - return b, nil -} - -func (d *wsDecompressor) addBuf(b []byte) { - d.bufs = append(d.bufs, b) -} - -func (d *wsDecompressor) decompress() ([]byte, error) { - d.off = 0 - // As per https://tools.ietf.org/html/rfc7692#section-7.2.2 - // add 0x00, 0x00, 0xff, 0xff and then a final block so that flate reader - // does not report unexpected EOF. - d.bufs = append(d.bufs, compressFinalBlock) - // Create or reset the decompressor with his object (wsDecompressor) - // that provides Read() and ReadByte() APIs that will consume from - // the compressed buffers (d.bufs). - if d.flate == nil { - d.flate = flate.NewReader(d) - } else { - d.flate.(flate.Resetter).Reset(d, nil) - } - b, err := io.ReadAll(d.flate) - // Now reset the compressed buffers list - d.bufs = nil - return b, err -} - -func wsNewReader(r io.Reader) *websocketReader { - return &websocketReader{r: r, ff: true} -} - -// From now on, reads will be from the readLoop and we will need to -// acquire the connection lock should we have to send/write a control -// message from handleControlFrame. -// -// Note: this runs under the connection lock. -func (r *websocketReader) doneWithConnect() { - r.nl = true -} - -func (r *websocketReader) Read(p []byte) (int, error) { - var err error - var buf []byte - - if l := len(r.ib); l > 0 { - buf = r.ib - r.ib = nil - } else { - if len(r.pending) > 0 { - return r.drainPending(p), nil - } - - // Get some data from the underlying reader. - n, err := r.r.Read(p) - if err != nil { - return 0, err - } - buf = p[:n] - } - - // Now parse this and decode frames. We will possibly read more to - // ensure that we get a full frame. - var ( - tmpBuf []byte - pos int - max = len(buf) - rem = 0 - ) - for pos < max { - b0 := buf[pos] - frameType := wsOpCode(b0 & 0xF) - final := b0&wsFinalBit != 0 - compressed := b0&wsRsv1Bit != 0 - pos++ - - tmpBuf, pos, err = wsGet(r.r, buf, pos, 1) - if err != nil { - return 0, err - } - b1 := tmpBuf[0] - - // Store size in case it is < 125 - rem = int(b1 & 0x7F) - - switch frameType { - case wsPingMessage, wsPongMessage, wsCloseMessage: - if rem > wsMaxControlPayloadSize { - return 0, fmt.Errorf( - fmt.Sprintf("control frame length bigger than maximum allowed of %v bytes", - wsMaxControlPayloadSize)) - } - if compressed { - return 0, errors.New("control frame should not be compressed") - } - if !final { - return 0, errors.New("control frame does not have final bit set") - } - case wsTextMessage, wsBinaryMessage: - if !r.ff { - return 0, errors.New("new message started before final frame for previous message was received") - } - r.ff = final - r.fc = compressed - case wsContinuationFrame: - // Compressed bit must be only set in the first frame - if r.ff || compressed { - return 0, errors.New("invalid continuation frame") - } - r.ff = final - default: - return 0, fmt.Errorf("unknown opcode %v", frameType) - } - - // If the encoded size is <= 125, then `rem` is simply the remainder size of the - // frame. If it is 126, then the actual size is encoded as a uint16. For larger - // frames, `rem` will initially be 127 and the actual size is encoded as a uint64. - switch rem { - case 126: - tmpBuf, pos, err = wsGet(r.r, buf, pos, 2) - if err != nil { - return 0, err - } - rem = int(binary.BigEndian.Uint16(tmpBuf)) - case 127: - tmpBuf, pos, err = wsGet(r.r, buf, pos, 8) - if err != nil { - return 0, err - } - rem = int(binary.BigEndian.Uint64(tmpBuf)) - } - - // Handle control messages in place... - if wsIsControlFrame(frameType) { - pos, err = r.handleControlFrame(frameType, buf, pos, rem) - if err != nil { - return 0, err - } - rem = 0 - continue - } - - var b []byte - // This ensures that we get the full payload for this frame. - b, pos, err = wsGet(r.r, buf, pos, rem) - if err != nil { - return 0, err - } - // We read the full frame. - rem = 0 - addToPending := true - if r.fc { - // Don't add to pending if we are not dealing with the final frame. - addToPending = r.ff - // Add the compressed payload buffer to the list. - r.addCBuf(b) - // Decompress only when this is the final frame. - if r.ff { - b, err = r.dc.decompress() - if err != nil { - return 0, err - } - r.fc = false - } - } - // Add to the pending list if dealing with uncompressed frames or - // after we have received the full compressed message and decompressed it. - if addToPending { - r.pending = append(r.pending, b) - } - } - // In case of compression, there may be nothing to drain - if len(r.pending) > 0 { - return r.drainPending(p), nil - } - return 0, nil -} - -func (r *websocketReader) addCBuf(b []byte) { - if r.dc == nil { - r.dc = &wsDecompressor{} - } - // Add a copy of the incoming buffer to the list of compressed buffers. - r.dc.addBuf(append([]byte(nil), b...)) -} - -func (r *websocketReader) drainPending(p []byte) int { - var n int - var max = len(p) - - for i, buf := range r.pending { - if n+len(buf) <= max { - copy(p[n:], buf) - n += len(buf) - } else { - // Is there room left? - if n < max { - // Write the partial and update this slice. - rem := max - n - copy(p[n:], buf[:rem]) - n += rem - r.pending[i] = buf[rem:] - } - // These are the remaining slices that will need to be used at - // the next Read() call. - r.pending = r.pending[i:] - return n - } - } - r.pending = r.pending[:0] - return n -} - -func wsGet(r io.Reader, buf []byte, pos, needed int) ([]byte, int, error) { - avail := len(buf) - pos - if avail >= needed { - return buf[pos : pos+needed], pos + needed, nil - } - b := make([]byte, needed) - start := copy(b, buf[pos:]) - for start != needed { - n, err := r.Read(b[start:cap(b)]) - start += n - if err != nil { - return b, start, err - } - } - return b, pos + avail, nil -} - -func (r *websocketReader) handleControlFrame(frameType wsOpCode, buf []byte, pos, rem int) (int, error) { - var payload []byte - var err error - - if rem > 0 { - payload, pos, err = wsGet(r.r, buf, pos, rem) - if err != nil { - return pos, err - } - } - switch frameType { - case wsCloseMessage: - status := wsCloseStatusNoStatusReceived - var body string - lp := len(payload) - // If there is a payload, the status is represented as a 2-byte - // unsigned integer (in network byte order). Then, there may be an - // optional body. - hasStatus, hasBody := lp >= wsCloseSatusSize, lp > wsCloseSatusSize - if hasStatus { - // Decode the status - status = int(binary.BigEndian.Uint16(payload[:wsCloseSatusSize])) - // Now if there is a body, capture it and make sure this is a valid UTF-8. - if hasBody { - body = string(payload[wsCloseSatusSize:]) - if !utf8.ValidString(body) { - // https://tools.ietf.org/html/rfc6455#section-5.5.1 - // If body is present, it must be a valid utf8 - status = wsCloseStatusInvalidPayloadData - body = "invalid utf8 body in close frame" - } - } - } - r.nc.wsEnqueueCloseMsg(r.nl, status, body) - // Return io.EOF so that readLoop will close the connection as client closed - // after processing pending buffers. - return pos, io.EOF - case wsPingMessage: - r.nc.wsEnqueueControlMsg(r.nl, wsPongMessage, payload) - case wsPongMessage: - // Nothing to do.. - } - return pos, nil -} - -func (w *websocketWriter) Write(p []byte) (int, error) { - if w.noMoreSend { - return 0, nil - } - var total int - var n int - var err error - // If there are control frames, they can be sent now. Actually spec says - // that they should be sent ASAP, so we will send before any application data. - if len(w.ctrlFrames) > 0 { - n, err = w.writeCtrlFrames() - if err != nil { - return n, err - } - total += n - } - // Do the following only if there is something to send. - // We will end with checking for need to send close message. - if len(p) > 0 { - if w.compress { - buf := &bytes.Buffer{} - if w.compressor == nil { - w.compressor, _ = flate.NewWriter(buf, flate.BestSpeed) - } else { - w.compressor.Reset(buf) - } - if n, err = w.compressor.Write(p); err != nil { - return n, err - } - if err = w.compressor.Flush(); err != nil { - return n, err - } - b := buf.Bytes() - p = b[:len(b)-4] - } - fh, key := wsCreateFrameHeader(w.compress, wsBinaryMessage, len(p)) - wsMaskBuf(key, p) - n, err = w.w.Write(fh) - total += n - if err == nil { - n, err = w.w.Write(p) - total += n - } - } - if err == nil && w.cm != nil { - n, err = w.writeCloseMsg() - total += n - } - return total, err -} - -func (w *websocketWriter) writeCtrlFrames() (int, error) { - var ( - n int - total int - i int - err error - ) - for ; i < len(w.ctrlFrames); i++ { - buf := w.ctrlFrames[i] - n, err = w.w.Write(buf) - total += n - if err != nil { - break - } - } - if i != len(w.ctrlFrames) { - w.ctrlFrames = w.ctrlFrames[i+1:] - } else { - w.ctrlFrames = w.ctrlFrames[:0] - } - return total, err -} - -func (w *websocketWriter) writeCloseMsg() (int, error) { - n, err := w.w.Write(w.cm) - w.cm, w.noMoreSend = nil, true - return n, err -} - -func wsMaskBuf(key, buf []byte) { - for i := 0; i < len(buf); i++ { - buf[i] ^= key[i&3] - } -} - -// Create the frame header. -// Encodes the frame type and optional compression flag, and the size of the payload. -func wsCreateFrameHeader(compressed bool, frameType wsOpCode, l int) ([]byte, []byte) { - fh := make([]byte, wsMaxFrameHeaderSize) - n, key := wsFillFrameHeader(fh, compressed, frameType, l) - return fh[:n], key -} - -func wsFillFrameHeader(fh []byte, compressed bool, frameType wsOpCode, l int) (int, []byte) { - var n int - b := byte(frameType) - b |= wsFinalBit - if compressed { - b |= wsRsv1Bit - } - b1 := byte(wsMaskBit) - switch { - case l <= 125: - n = 2 - fh[0] = b - fh[1] = b1 | byte(l) - case l < 65536: - n = 4 - fh[0] = b - fh[1] = b1 | 126 - binary.BigEndian.PutUint16(fh[2:], uint16(l)) - default: - n = 10 - fh[0] = b - fh[1] = b1 | 127 - binary.BigEndian.PutUint64(fh[2:], uint64(l)) - } - var key []byte - var keyBuf [4]byte - if _, err := io.ReadFull(rand.Reader, keyBuf[:4]); err != nil { - kv := mrand.Int31() - binary.LittleEndian.PutUint32(keyBuf[:4], uint32(kv)) - } - copy(fh[n:], keyBuf[:4]) - key = fh[n : n+4] - n += 4 - return n, key -} - -func (nc *Conn) wsInitHandshake(u *url.URL) error { - compress := nc.Opts.Compression - tlsRequired := u.Scheme == wsSchemeTLS || nc.Opts.Secure || nc.Opts.TLSConfig != nil || nc.Opts.TLSCertCB != nil || nc.Opts.RootCAsCB != nil - // Do TLS here as needed. - if tlsRequired { - if err := nc.makeTLSConn(); err != nil { - return err - } - } else { - nc.bindToNewConn() - } - - var err error - - // For http request, we need the passed URL to contain either http or https scheme. - scheme := "http" - if tlsRequired { - scheme = "https" - } - ustr := fmt.Sprintf("%s://%s", scheme, u.Host) - - if nc.Opts.ProxyPath != "" { - proxyPath := nc.Opts.ProxyPath - if !strings.HasPrefix(proxyPath, "/") { - proxyPath = "/" + proxyPath - } - ustr += proxyPath - } - - u, err = url.Parse(ustr) - if err != nil { - return err - } - req := &http.Request{ - Method: "GET", - URL: u, - Proto: "HTTP/1.1", - ProtoMajor: 1, - ProtoMinor: 1, - Header: make(http.Header), - Host: u.Host, - } - wsKey, err := wsMakeChallengeKey() - if err != nil { - return err - } - - req.Header["Upgrade"] = []string{"websocket"} - req.Header["Connection"] = []string{"Upgrade"} - req.Header["Sec-WebSocket-Key"] = []string{wsKey} - req.Header["Sec-WebSocket-Version"] = []string{"13"} - if compress { - req.Header.Add("Sec-WebSocket-Extensions", wsPMCReqHeaderValue) - } - if err := req.Write(nc.conn); err != nil { - return err - } - - var resp *http.Response - - br := bufio.NewReaderSize(nc.conn, 4096) - nc.conn.SetReadDeadline(time.Now().Add(nc.Opts.Timeout)) - resp, err = http.ReadResponse(br, req) - if err == nil && - (resp.StatusCode != 101 || - !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") || - !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") || - resp.Header.Get("Sec-Websocket-Accept") != wsAcceptKey(wsKey)) { - - err = fmt.Errorf("invalid websocket connection") - } - // Check compression extension... - if err == nil && compress { - // Check that not only permessage-deflate extension is present, but that - // we also have server and client no context take over. - srvCompress, noCtxTakeover := wsPMCExtensionSupport(resp.Header) - - // If server does not support compression, then simply disable it in our side. - if !srvCompress { - compress = false - } else if !noCtxTakeover { - err = fmt.Errorf("compression negotiation error") - } - } - if resp != nil { - resp.Body.Close() - } - nc.conn.SetReadDeadline(time.Time{}) - if err != nil { - return err - } - - wsr := wsNewReader(nc.br.r) - wsr.nc = nc - // We have to slurp whatever is in the bufio reader and copy to br.r - if n := br.Buffered(); n != 0 { - wsr.ib, _ = br.Peek(n) - } - nc.br.r = wsr - nc.bw.w = &websocketWriter{w: nc.bw.w, compress: compress} - nc.ws = true - return nil -} - -func (nc *Conn) wsClose() { - nc.mu.Lock() - defer nc.mu.Unlock() - if !nc.ws { - return - } - nc.wsEnqueueCloseMsgLocked(wsCloseStatusNormalClosure, _EMPTY_) -} - -func (nc *Conn) wsEnqueueCloseMsg(needsLock bool, status int, payload string) { - // In some low-level unit tests it will happen... - if nc == nil { - return - } - if needsLock { - nc.mu.Lock() - defer nc.mu.Unlock() - } - nc.wsEnqueueCloseMsgLocked(status, payload) -} - -func (nc *Conn) wsEnqueueCloseMsgLocked(status int, payload string) { - wr, ok := nc.bw.w.(*websocketWriter) - if !ok || wr.cmDone { - return - } - statusAndPayloadLen := 2 + len(payload) - frame := make([]byte, 2+4+statusAndPayloadLen) - n, key := wsFillFrameHeader(frame, false, wsCloseMessage, statusAndPayloadLen) - // Set the status - binary.BigEndian.PutUint16(frame[n:], uint16(status)) - // If there is a payload, copy - if len(payload) > 0 { - copy(frame[n+2:], payload) - } - // Mask status + payload - wsMaskBuf(key, frame[n:n+statusAndPayloadLen]) - wr.cm = frame - wr.cmDone = true - nc.bw.flush() - if c := wr.compressor; c != nil { - c.Close() - } -} - -func (nc *Conn) wsEnqueueControlMsg(needsLock bool, frameType wsOpCode, payload []byte) { - // In some low-level unit tests it will happen... - if nc == nil { - return - } - if needsLock { - nc.mu.Lock() - defer nc.mu.Unlock() - } - wr, ok := nc.bw.w.(*websocketWriter) - if !ok { - return - } - fh, key := wsCreateFrameHeader(false, frameType, len(payload)) - wr.ctrlFrames = append(wr.ctrlFrames, fh) - if len(payload) > 0 { - wsMaskBuf(key, payload) - wr.ctrlFrames = append(wr.ctrlFrames, payload) - } - nc.bw.flush() -} - -func wsPMCExtensionSupport(header http.Header) (bool, bool) { - for _, extensionList := range header["Sec-Websocket-Extensions"] { - extensions := strings.Split(extensionList, ",") - for _, extension := range extensions { - extension = strings.Trim(extension, " \t") - params := strings.Split(extension, ";") - for i, p := range params { - p = strings.Trim(p, " \t") - if strings.EqualFold(p, wsPMCExtension) { - var snc bool - var cnc bool - for j := i + 1; j < len(params); j++ { - p = params[j] - p = strings.Trim(p, " \t") - if strings.EqualFold(p, wsPMCSrvNoCtx) { - snc = true - } else if strings.EqualFold(p, wsPMCCliNoCtx) { - cnc = true - } - if snc && cnc { - return true, true - } - } - return true, false - } - } - } - } - return false, false -} - -func wsMakeChallengeKey() (string, error) { - p := make([]byte, 16) - if _, err := io.ReadFull(rand.Reader, p); err != nil { - return "", err - } - return base64.StdEncoding.EncodeToString(p), nil -} - -func wsAcceptKey(key string) string { - h := sha1.New() - h.Write([]byte(key)) - h.Write(wsGUID) - return base64.StdEncoding.EncodeToString(h.Sum(nil)) -} - -// Returns true if the op code corresponds to a control frame. -func wsIsControlFrame(frameType wsOpCode) bool { - return frameType >= wsCloseMessage -} - -func isWebsocketScheme(u *url.URL) bool { - return u.Scheme == wsScheme || u.Scheme == wsSchemeTLS -} diff --git a/vendor/github.com/nats-io/nkeys/.gitignore b/vendor/github.com/nats-io/nkeys/.gitignore deleted file mode 100644 index d23676d2d..000000000 --- a/vendor/github.com/nats-io/nkeys/.gitignore +++ /dev/null @@ -1,16 +0,0 @@ -# Binaries for programs and plugins -*.exe -*.dll -*.so -*.dylib -build/ - -# Test binary, build with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 -.glide/ -.idea/ diff --git a/vendor/github.com/nats-io/nkeys/.goreleaser.yml b/vendor/github.com/nats-io/nkeys/.goreleaser.yml deleted file mode 100644 index e5c4f154a..000000000 --- a/vendor/github.com/nats-io/nkeys/.goreleaser.yml +++ /dev/null @@ -1,63 +0,0 @@ -project_name: nkeys -release: - github: - owner: nats-io - name: nkeys - name_template: '{{.Tag}}' - draft: true -builds: - - id: nk - main: ./nk/main.go - ldflags: "-X main.Version={{.Tag}}_{{.Commit}}" - binary: nk - goos: - - darwin - - linux - - windows - - freebsd - goarch: - - amd64 - - arm - - arm64 - - 386 - - mips64le - - s390x - goarm: - - 6 - - 7 - ignore: - - goos: darwin - goarch: 386 - - goos: freebsd - goarch: arm - - goos: freebsd - goarch: arm64 - - goos: freebsd - goarch: 386 - -dist: build - -archives: - - name_template: '{{ .ProjectName }}-v{{ .Version }}-{{ .Os }}-{{ .Arch }}{{ if .Arm - }}v{{ .Arm }}{{ end }}' - wrap_in_directory: true - format: zip - files: - - README.md - - LICENSE - -checksum: - name_template: '{{ .ProjectName }}-v{{ .Version }}-checksums.txt' - -snapshot: - name_template: 'dev' - -nfpms: - - file_name_template: '{{ .ProjectName }}-v{{ .Version }}-{{ .Arch }}{{ if .Arm - }}v{{ .Arm }}{{ end }}' - maintainer: nats.io - description: NKeys utility cli program - vendor: nats-io - bindir: /usr/local/bin - formats: - - deb \ No newline at end of file diff --git a/vendor/github.com/nats-io/nkeys/GOVERNANCE.md b/vendor/github.com/nats-io/nkeys/GOVERNANCE.md deleted file mode 100644 index 744d3bc2b..000000000 --- a/vendor/github.com/nats-io/nkeys/GOVERNANCE.md +++ /dev/null @@ -1,3 +0,0 @@ -# NATS NKEYS Governance - -NATS NKEYS is part of the NATS project and is subject to the [NATS Governance](https://github.com/nats-io/nats-general/blob/master/GOVERNANCE.md). \ No newline at end of file diff --git a/vendor/github.com/nats-io/nkeys/LICENSE b/vendor/github.com/nats-io/nkeys/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/vendor/github.com/nats-io/nkeys/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - 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 "[]" - 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 - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/nats-io/nkeys/MAINTAINERS.md b/vendor/github.com/nats-io/nkeys/MAINTAINERS.md deleted file mode 100644 index 232146550..000000000 --- a/vendor/github.com/nats-io/nkeys/MAINTAINERS.md +++ /dev/null @@ -1,8 +0,0 @@ -# Maintainers - -Maintainership is on a per project basis. - -### Maintainers - - Derek Collison [@derekcollison](https://github.com/derekcollison) - - Ivan Kozlovic [@kozlovic](https://github.com/kozlovic) - - Waldemar Quevedo [@wallyqs](https://github.com/wallyqs) diff --git a/vendor/github.com/nats-io/nkeys/README.md b/vendor/github.com/nats-io/nkeys/README.md deleted file mode 100644 index 17e3a8e3a..000000000 --- a/vendor/github.com/nats-io/nkeys/README.md +++ /dev/null @@ -1,68 +0,0 @@ -# NKEYS - -[![License Apache 2](https://img.shields.io/badge/License-Apache2-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0) -[![Go Report Card](https://goreportcard.com/badge/github.com/nats-io/nkeys)](https://goreportcard.com/report/github.com/nats-io/nkeys) -[![Build Status](https://github.com/nats-io/nkeys/actions/workflows/release.yaml/badge.svg)](https://github.com/nats-io/nkeys/actions/workflows/release.yaml/badge.svg) -[![GoDoc](https://godoc.org/github.com/nats-io/nkeys?status.svg)](https://godoc.org/github.com/nats-io/nkeys) -[![Coverage Status](https://coveralls.io/repos/github/nats-io/nkeys/badge.svg?branch=main&service=github)](https://coveralls.io/github/nats-io/nkeys?branch=main) - -A public-key signature system based on [Ed25519](https://ed25519.cr.yp.to/) for the NATS ecosystem. - -## About - -The NATS ecosystem will be moving to [Ed25519](https://ed25519.cr.yp.to/) keys for identity, authentication and authorization for entities such as Accounts, Users, Servers and Clusters. - -Ed25519 is fast and resistant to side channel attacks. Generation of a seed key is all that is needed to be stored and kept safe, as the seed can generate both the public and private keys. - -The NATS system will utilize Ed25519 keys, meaning that NATS systems will never store or even have access to any private keys. Authentication will utilize a random challenge response mechanism. - -Dealing with 32 byte and 64 byte raw keys can be challenging. NKEYS is designed to formulate keys in a much friendlier fashion and references work done in cryptocurrencies, specifically [Stellar](https://www.stellar.org/). Bitcoin and others used a form of Base58 (or Base58Check) to encode raw keys. Stellar utilized a more traditional Base32 with a CRC16 and a version or prefix byte. NKEYS utilizes a similar format where the prefix will be 1 byte for public and private keys and will be 2 bytes for seeds. The base32 encoding of these prefixes will yield friendly human readable prefixes, e.g. '**N**' = server, '**C**' = cluster, '**O**' = operator, '**A**' = account, and '**U**' = user. '**P**' is used for private keys. For seeds, the first encoded prefix is '**S**', and the second character will be the type for the public key, e.g. "**SU**" is a seed for a user key pair, "**SA**" is a seed for an account key pair. - -## Installation - -Use the `go` command: - - $ go get github.com/nats-io/nkeys - -## nk - Command Line Utility - -Located under the nk [directory](https://github.com/nats-io/nkeys/tree/master/nk). - -## Basic API Usage -```go - -// Create a new User KeyPair -user, _ := nkeys.CreateUser() - -// Sign some data with a full key pair user. -data := []byte("Hello World") -sig, _ := user.Sign(data) - -// Verify the signature. -err = user.Verify(data, sig) - -// Access the seed, the only thing that needs to be stored and kept safe. -// seed = "SUAKYRHVIOREXV7EUZTBHUHL7NUMHPMAS7QMDU3GTIUWEI5LDNOXD43IZY" -seed, _ := user.Seed() - -// Access the public key which can be shared. -// publicKey = "UD466L6EBCM3YY5HEGHJANNTN4LSKTSUXTH7RILHCKEQMQHTBNLHJJXT" -publicKey, _ := user.PublicKey() - -// Create a full User who can sign and verify from a private seed. -user, _ = nkeys.FromSeed(seed) - -// Create a User who can only verify signatures via a public key. -user, _ = nkeys.FromPublicKey(publicKey) - -// Create a User KeyPair with our own random data. -var rawSeed [32]byte -_, err := io.ReadFull(rand.Reader, rawSeed[:]) // Or some other random source. -user2, _ := nkeys.FromRawSeed(PrefixByteUser, rawSeed) - -``` - -## License - -Unless otherwise noted, the NATS source files are distributed -under the Apache Version 2.0 license found in the LICENSE file. diff --git a/vendor/github.com/nats-io/nkeys/TODO.md b/vendor/github.com/nats-io/nkeys/TODO.md deleted file mode 100644 index 2649c9e59..000000000 --- a/vendor/github.com/nats-io/nkeys/TODO.md +++ /dev/null @@ -1,5 +0,0 @@ - -# General - -- [ ] Child key derivation -- [ ] Hardware support, e.g. YubiHSM diff --git a/vendor/github.com/nats-io/nkeys/crc16.go b/vendor/github.com/nats-io/nkeys/crc16.go deleted file mode 100644 index fbe38fbce..000000000 --- a/vendor/github.com/nats-io/nkeys/crc16.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2018 The NATS 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 nkeys - -// An implementation of crc16 according to CCITT standards for XMODEM. - -var crc16tab = [256]uint16{ - 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, - 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, - 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, - 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, - 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, - 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, - 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, - 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, - 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, - 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, - 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, - 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, - 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, - 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, - 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, - 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, - 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, - 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, - 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, - 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, - 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, - 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, - 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, - 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, - 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, - 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, - 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, - 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, - 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, - 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0, -} - -// crc16 returns the 2-byte crc for the data provided. -func crc16(data []byte) uint16 { - var crc uint16 - for _, b := range data { - crc = ((crc << 8) & 0xffff) ^ crc16tab[((crc>>8)^uint16(b))&0x00FF] - } - return crc -} - -// validate will check the calculated crc16 checksum for data against the expected. -func validate(data []byte, expected uint16) error { - if crc16(data) != expected { - return ErrInvalidChecksum - } - return nil -} diff --git a/vendor/github.com/nats-io/nkeys/creds_utils.go b/vendor/github.com/nats-io/nkeys/creds_utils.go deleted file mode 100644 index ecd946318..000000000 --- a/vendor/github.com/nats-io/nkeys/creds_utils.go +++ /dev/null @@ -1,78 +0,0 @@ -package nkeys - -import ( - "bytes" - "regexp" - "strings" -) - -var userConfigRE = regexp.MustCompile(`\s*(?:(?:[-]{3,}.*[-]{3,}\r?\n)([\w\-.=]+)(?:\r?\n[-]{3,}.*[-]{3,}\r?\n))`) - -// ParseDecoratedJWT takes a creds file and returns the JWT portion. -func ParseDecoratedJWT(contents []byte) (string, error) { - items := userConfigRE.FindAllSubmatch(contents, -1) - if len(items) == 0 { - return string(contents), nil - } - // First result should be the user JWT. - // We copy here so that if the file contained a seed file too we wipe appropriately. - raw := items[0][1] - tmp := make([]byte, len(raw)) - copy(tmp, raw) - return strings.TrimSpace(string(tmp)), nil -} - -// ParseDecoratedNKey takes a creds file, finds the NKey portion and creates a -// key pair from it. -func ParseDecoratedNKey(contents []byte) (KeyPair, error) { - var seed []byte - - items := userConfigRE.FindAllSubmatch(contents, -1) - if len(items) > 1 { - seed = items[1][1] - } else { - lines := bytes.Split(contents, []byte("\n")) - for _, line := range lines { - if bytes.HasPrefix(bytes.TrimSpace(line), []byte("SO")) || - bytes.HasPrefix(bytes.TrimSpace(line), []byte("SA")) || - bytes.HasPrefix(bytes.TrimSpace(line), []byte("SU")) { - seed = line - break - } - } - } - if seed == nil { - return nil, ErrNoSeedFound - } - if !bytes.HasPrefix(seed, []byte("SO")) && - !bytes.HasPrefix(seed, []byte("SA")) && - !bytes.HasPrefix(seed, []byte("SU")) { - return nil, ErrInvalidNkeySeed - } - kp, err := FromSeed(seed) - if err != nil { - return nil, err - } - return kp, nil -} - -// ParseDecoratedUserNKey takes a creds file, finds the NKey portion and creates a -// key pair from it. Similar to ParseDecoratedNKey but fails for non-user keys. -func ParseDecoratedUserNKey(contents []byte) (KeyPair, error) { - nk, err := ParseDecoratedNKey(contents) - if err != nil { - return nil, err - } - seed, err := nk.Seed() - if err != nil { - return nil, err - } - if !bytes.HasPrefix(seed, []byte("SU")) { - return nil, ErrInvalidUserSeed - } - kp, err := FromSeed(seed) - if err != nil { - return nil, err - } - return kp, nil -} diff --git a/vendor/github.com/nats-io/nkeys/dependencies.md b/vendor/github.com/nats-io/nkeys/dependencies.md deleted file mode 100644 index 370184aa5..000000000 --- a/vendor/github.com/nats-io/nkeys/dependencies.md +++ /dev/null @@ -1,12 +0,0 @@ -# External Dependencies - -This file lists the dependencies used in this repository. - -| Dependency | License | -|-|-| -| Go | BSD 3-Clause "New" or "Revised" License | -| golang.org/x/crypto v0.3.0 | BSD 3-Clause "New" or "Revised" License | -| golang.org/x/net v0.2.0 | BSD 3-Clause "New" or "Revised" License | -| golang.org/x/sys v0.2.0 | BSD 3-Clause "New" or "Revised" License | -| golang.org/x/term v0.2.0 | BSD 3-Clause "New" or "Revised" License | -| golang.org/x/text v0.4.0 | BSD 3-Clause "New" or "Revised" License | diff --git a/vendor/github.com/nats-io/nkeys/errors.go b/vendor/github.com/nats-io/nkeys/errors.go deleted file mode 100644 index a30bb96e1..000000000 --- a/vendor/github.com/nats-io/nkeys/errors.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2022 The NATS 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 nkeys - -// Errors -const ( - ErrInvalidPrefixByte = nkeysError("nkeys: invalid prefix byte") - ErrInvalidKey = nkeysError("nkeys: invalid key") - ErrInvalidPublicKey = nkeysError("nkeys: invalid public key") - ErrInvalidPrivateKey = nkeysError("nkeys: invalid private key") - ErrInvalidSeedLen = nkeysError("nkeys: invalid seed length") - ErrInvalidSeed = nkeysError("nkeys: invalid seed") - ErrInvalidEncoding = nkeysError("nkeys: invalid encoded key") - ErrInvalidSignature = nkeysError("nkeys: signature verification failed") - ErrCannotSign = nkeysError("nkeys: can not sign, no private key available") - ErrPublicKeyOnly = nkeysError("nkeys: no seed or private key available") - ErrIncompatibleKey = nkeysError("nkeys: incompatible key") - ErrInvalidChecksum = nkeysError("nkeys: invalid checksum") - ErrNoSeedFound = nkeysError("nkeys: no nkey seed found") - ErrInvalidNkeySeed = nkeysError("nkeys: doesn't contain a seed nkey") - ErrInvalidUserSeed = nkeysError("nkeys: doesn't contain an user seed nkey") - ErrInvalidRecipient = nkeysError("nkeys: not a valid recipient public curve key") - ErrInvalidSender = nkeysError("nkeys: not a valid sender public curve key") - ErrInvalidCurveKey = nkeysError("nkeys: not a valid curve key") - ErrInvalidCurveSeed = nkeysError("nkeys: not a valid curve seed") - ErrInvalidEncrypted = nkeysError("nkeys: encrypted input is not valid") - ErrInvalidEncVersion = nkeysError("nkeys: encrypted input wrong version") - ErrCouldNotDecrypt = nkeysError("nkeys: could not decrypt input") - ErrInvalidCurveKeyOperation = nkeysError("nkeys: curve key is not valid for sign/verify") - ErrInvalidNKeyOperation = nkeysError("nkeys: only curve key can seal/open") - ErrCannotOpen = nkeysError("nkeys: cannot open no private curve key available") - ErrCannotSeal = nkeysError("nkeys: cannot seal no private curve key available") -) - -type nkeysError string - -func (e nkeysError) Error() string { - return string(e) -} diff --git a/vendor/github.com/nats-io/nkeys/keypair.go b/vendor/github.com/nats-io/nkeys/keypair.go deleted file mode 100644 index 9d0551806..000000000 --- a/vendor/github.com/nats-io/nkeys/keypair.go +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2018-2022 The NATS 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 nkeys - -import ( - "bytes" - "crypto/rand" - "io" - - "golang.org/x/crypto/ed25519" -) - -// kp is the internal struct for a kepypair using seed. -type kp struct { - seed []byte -} - -// All seeds are 32 bytes long. -const seedLen = 32 - -// CreatePair will create a KeyPair based on the rand entropy and a type/prefix byte. -func CreatePair(prefix PrefixByte) (KeyPair, error) { - return CreatePairWithRand(prefix, rand.Reader) -} - -// CreatePair will create a KeyPair based on the rand reader and a type/prefix byte. rand can be nil. -func CreatePairWithRand(prefix PrefixByte, rr io.Reader) (KeyPair, error) { - if prefix == PrefixByteCurve { - return CreateCurveKeysWithRand(rr) - } - if rr == nil { - rr = rand.Reader - } - var rawSeed [seedLen]byte - - _, err := io.ReadFull(rr, rawSeed[:]) - if err != nil { - return nil, err - } - - seed, err := EncodeSeed(prefix, rawSeed[:]) - if err != nil { - return nil, err - } - return &kp{seed}, nil -} - -// rawSeed will return the raw, decoded 64 byte seed. -func (pair *kp) rawSeed() ([]byte, error) { - _, raw, err := DecodeSeed(pair.seed) - return raw, err -} - -// keys will return a 32 byte public key and a 64 byte private key utilizing the seed. -func (pair *kp) keys() (ed25519.PublicKey, ed25519.PrivateKey, error) { - raw, err := pair.rawSeed() - if err != nil { - return nil, nil, err - } - return ed25519.GenerateKey(bytes.NewReader(raw)) -} - -// Wipe will randomize the contents of the seed key -func (pair *kp) Wipe() { - io.ReadFull(rand.Reader, pair.seed) - pair.seed = nil -} - -// Seed will return the encoded seed. -func (pair *kp) Seed() ([]byte, error) { - return pair.seed, nil -} - -// PublicKey will return the encoded public key associated with the KeyPair. -// All KeyPairs have a public key. -func (pair *kp) PublicKey() (string, error) { - public, raw, err := DecodeSeed(pair.seed) - if err != nil { - return "", err - } - pub, _, err := ed25519.GenerateKey(bytes.NewReader(raw)) - if err != nil { - return "", err - } - pk, err := Encode(public, pub) - if err != nil { - return "", err - } - return string(pk), nil -} - -// PrivateKey will return the encoded private key for KeyPair. -func (pair *kp) PrivateKey() ([]byte, error) { - _, priv, err := pair.keys() - if err != nil { - return nil, err - } - return Encode(PrefixBytePrivate, priv) -} - -// Sign will sign the input with KeyPair's private key. -func (pair *kp) Sign(input []byte) ([]byte, error) { - _, priv, err := pair.keys() - if err != nil { - return nil, err - } - return ed25519.Sign(priv, input), nil -} - -// Verify will verify the input against a signature utilizing the public key. -func (pair *kp) Verify(input []byte, sig []byte) error { - pub, _, err := pair.keys() - if err != nil { - return err - } - if !ed25519.Verify(pub, input, sig) { - return ErrInvalidSignature - } - return nil -} - -// Seal is only supported on CurveKeyPair -func (pair *kp) Seal(input []byte, recipient string) ([]byte, error) { - return nil, ErrInvalidNKeyOperation -} - -// SealWithRand is only supported on CurveKeyPair -func (pair *kp) SealWithRand(input []byte, recipient string, rr io.Reader) ([]byte, error) { - return nil, ErrInvalidNKeyOperation -} - -// Open is only supported on CurveKey -func (pair *kp) Open(input []byte, sender string) ([]byte, error) { - return nil, ErrInvalidNKeyOperation -} diff --git a/vendor/github.com/nats-io/nkeys/nkeys.go b/vendor/github.com/nats-io/nkeys/nkeys.go deleted file mode 100644 index 6f1ba2050..000000000 --- a/vendor/github.com/nats-io/nkeys/nkeys.go +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2018-2019 The NATS 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 nkeys is an Ed25519 based public-key signature system that simplifies keys and seeds -// and performs signing and verification. -// It also supports encryption via x25519 keys and is compatible with https://pkg.go.dev/golang.org/x/crypto/nacl/box. -package nkeys - -import "io" - -// Version is our current version -const Version = "0.4.7" - -// KeyPair provides the central interface to nkeys. -type KeyPair interface { - Seed() ([]byte, error) - PublicKey() (string, error) - PrivateKey() ([]byte, error) - // Sign is only supported on Non CurveKeyPairs - Sign(input []byte) ([]byte, error) - // Verify is only supported on Non CurveKeyPairs - Verify(input []byte, sig []byte) error - Wipe() - // Seal is only supported on CurveKeyPair - Seal(input []byte, recipient string) ([]byte, error) - // SealWithRand is only supported on CurveKeyPair - SealWithRand(input []byte, recipient string, rr io.Reader) ([]byte, error) - // Open is only supported on CurveKey - Open(input []byte, sender string) ([]byte, error) -} - -// CreateUser will create a User typed KeyPair. -func CreateUser() (KeyPair, error) { - return CreatePair(PrefixByteUser) -} - -// CreateAccount will create an Account typed KeyPair. -func CreateAccount() (KeyPair, error) { - return CreatePair(PrefixByteAccount) -} - -// CreateServer will create a Server typed KeyPair. -func CreateServer() (KeyPair, error) { - return CreatePair(PrefixByteServer) -} - -// CreateCluster will create a Cluster typed KeyPair. -func CreateCluster() (KeyPair, error) { - return CreatePair(PrefixByteCluster) -} - -// CreateOperator will create an Operator typed KeyPair. -func CreateOperator() (KeyPair, error) { - return CreatePair(PrefixByteOperator) -} - -// FromPublicKey will create a KeyPair capable of verifying signatures. -func FromPublicKey(public string) (KeyPair, error) { - raw, err := decode([]byte(public)) - if err != nil { - return nil, err - } - pre := PrefixByte(raw[0]) - if err := checkValidPublicPrefixByte(pre); err != nil { - return nil, ErrInvalidPublicKey - } - return &pub{pre, raw[1:]}, nil -} - -// FromSeed will create a KeyPair capable of signing and verifying signatures. -func FromSeed(seed []byte) (KeyPair, error) { - prefix, _, err := DecodeSeed(seed) - if err != nil { - return nil, err - } - if prefix == PrefixByteCurve { - return FromCurveSeed(seed) - } - copy := append([]byte{}, seed...) - return &kp{copy}, nil -} - -// FromRawSeed will create a KeyPair from the raw 32 byte seed for a given type. -func FromRawSeed(prefix PrefixByte, rawSeed []byte) (KeyPair, error) { - seed, err := EncodeSeed(prefix, rawSeed) - if err != nil { - return nil, err - } - return &kp{seed}, nil -} diff --git a/vendor/github.com/nats-io/nkeys/public.go b/vendor/github.com/nats-io/nkeys/public.go deleted file mode 100644 index c3cd21edb..000000000 --- a/vendor/github.com/nats-io/nkeys/public.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2018 The NATS 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 nkeys - -import ( - "crypto/rand" - "io" - - "golang.org/x/crypto/ed25519" -) - -// A KeyPair from a public key capable of verifying only. -type pub struct { - pre PrefixByte - pub ed25519.PublicKey -} - -// PublicKey will return the encoded public key associated with the KeyPair. -// All KeyPairs have a public key. -func (p *pub) PublicKey() (string, error) { - pk, err := Encode(p.pre, p.pub) - if err != nil { - return "", err - } - return string(pk), nil -} - -// Seed will return an error since this is not available for public key only KeyPairs. -func (p *pub) Seed() ([]byte, error) { - return nil, ErrPublicKeyOnly -} - -// PrivateKey will return an error since this is not available for public key only KeyPairs. -func (p *pub) PrivateKey() ([]byte, error) { - return nil, ErrPublicKeyOnly -} - -// Sign will return an error since this is not available for public key only KeyPairs. -func (p *pub) Sign(input []byte) ([]byte, error) { - return nil, ErrCannotSign -} - -// Verify will verify the input against a signature utilizing the public key. -func (p *pub) Verify(input []byte, sig []byte) error { - if !ed25519.Verify(p.pub, input, sig) { - return ErrInvalidSignature - } - return nil -} - -// Wipe will randomize the public key and erase the pre byte. -func (p *pub) Wipe() { - p.pre = '0' - io.ReadFull(rand.Reader, p.pub) -} - -func (p *pub) Seal(input []byte, recipient string) ([]byte, error) { - if p.pre == PrefixByteCurve { - return nil, ErrCannotSeal - } - return nil, ErrInvalidNKeyOperation -} -func (p *pub) SealWithRand(input []byte, _recipient string, rr io.Reader) ([]byte, error) { - if p.pre == PrefixByteCurve { - return nil, ErrCannotSeal - } - return nil, ErrInvalidNKeyOperation -} - -func (p *pub) Open(input []byte, sender string) ([]byte, error) { - if p.pre == PrefixByteCurve { - return nil, ErrCannotOpen - } - return nil, ErrInvalidNKeyOperation -} diff --git a/vendor/github.com/nats-io/nkeys/strkey.go b/vendor/github.com/nats-io/nkeys/strkey.go deleted file mode 100644 index 8ae33116c..000000000 --- a/vendor/github.com/nats-io/nkeys/strkey.go +++ /dev/null @@ -1,314 +0,0 @@ -// Copyright 2018-2023 The NATS 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 nkeys - -import ( - "bytes" - "encoding/base32" - "encoding/binary" -) - -// PrefixByte is a lead byte representing the type. -type PrefixByte byte - -const ( - // PrefixByteSeed is the version byte used for encoded NATS Seeds - PrefixByteSeed PrefixByte = 18 << 3 // Base32-encodes to 'S...' - - // PrefixBytePrivate is the version byte used for encoded NATS Private keys - PrefixBytePrivate PrefixByte = 15 << 3 // Base32-encodes to 'P...' - - // PrefixByteServer is the version byte used for encoded NATS Servers - PrefixByteServer PrefixByte = 13 << 3 // Base32-encodes to 'N...' - - // PrefixByteCluster is the version byte used for encoded NATS Clusters - PrefixByteCluster PrefixByte = 2 << 3 // Base32-encodes to 'C...' - - // PrefixByteOperator is the version byte used for encoded NATS Operators - PrefixByteOperator PrefixByte = 14 << 3 // Base32-encodes to 'O...' - - // PrefixByteAccount is the version byte used for encoded NATS Accounts - PrefixByteAccount PrefixByte = 0 // Base32-encodes to 'A...' - - // PrefixByteUser is the version byte used for encoded NATS Users - PrefixByteUser PrefixByte = 20 << 3 // Base32-encodes to 'U...' - - // PrefixByteCurve is the version byte used for encoded CurveKeys (X25519) - PrefixByteCurve PrefixByte = 23 << 3 // Base32-encodes to 'X...' - - // PrefixByteUnknown is for unknown prefixes. - PrefixByteUnknown PrefixByte = 25 << 3 // Base32-encodes to 'Z...' -) - -// Set our encoding to not include padding '==' -var b32Enc = base32.StdEncoding.WithPadding(base32.NoPadding) - -// Encode will encode a raw key or seed with the prefix and crc16 and then base32 encoded. -func Encode(prefix PrefixByte, src []byte) ([]byte, error) { - if err := checkValidPrefixByte(prefix); err != nil { - return nil, err - } - - var raw bytes.Buffer - - // write prefix byte - if err := raw.WriteByte(byte(prefix)); err != nil { - return nil, err - } - - // write payload - if _, err := raw.Write(src); err != nil { - return nil, err - } - - // Calculate and write crc16 checksum - err := binary.Write(&raw, binary.LittleEndian, crc16(raw.Bytes())) - if err != nil { - return nil, err - } - - data := raw.Bytes() - buf := make([]byte, b32Enc.EncodedLen(len(data))) - b32Enc.Encode(buf, data) - return buf[:], nil -} - -// EncodeSeed will encode a raw key with the prefix and then seed prefix and crc16 and then base32 encoded. -// `src` must be 32 bytes long (ed25519.SeedSize). -func EncodeSeed(public PrefixByte, src []byte) ([]byte, error) { - if err := checkValidPublicPrefixByte(public); err != nil { - return nil, err - } - - if len(src) != seedLen { - return nil, ErrInvalidSeedLen - } - - // In order to make this human printable for both bytes, we need to do a little - // bit manipulation to setup for base32 encoding which takes 5 bits at a time. - b1 := byte(PrefixByteSeed) | (byte(public) >> 5) - b2 := (byte(public) & 31) << 3 // 31 = 00011111 - - var raw bytes.Buffer - - raw.WriteByte(b1) - raw.WriteByte(b2) - - // write payload - if _, err := raw.Write(src); err != nil { - return nil, err - } - - // Calculate and write crc16 checksum - err := binary.Write(&raw, binary.LittleEndian, crc16(raw.Bytes())) - if err != nil { - return nil, err - } - - data := raw.Bytes() - buf := make([]byte, b32Enc.EncodedLen(len(data))) - b32Enc.Encode(buf, data) - return buf, nil -} - -// IsValidEncoding will tell you if the encoding is a valid key. -func IsValidEncoding(src []byte) bool { - _, err := decode(src) - return err == nil -} - -// decode will decode the base32 and check crc16 and the prefix for validity. -func decode(src []byte) ([]byte, error) { - raw := make([]byte, b32Enc.DecodedLen(len(src))) - n, err := b32Enc.Decode(raw, src) - if err != nil { - return nil, err - } - raw = raw[:n] - - if n < 4 { - return nil, ErrInvalidEncoding - } - - crc := binary.LittleEndian.Uint16(raw[n-2:]) - - // ensure checksum is valid - if err := validate(raw[0:n-2], crc); err != nil { - return nil, err - } - - return raw[:n-2], nil -} - -// Decode will decode the base32 string and check crc16 and enforce the prefix is what is expected. -func Decode(expectedPrefix PrefixByte, src []byte) ([]byte, error) { - if err := checkValidPrefixByte(expectedPrefix); err != nil { - return nil, err - } - raw, err := decode(src) - if err != nil { - return nil, err - } - b1 := raw[0] & 248 // 248 = 11111000 - if prefix := PrefixByte(b1); prefix != expectedPrefix { - return nil, ErrInvalidPrefixByte - } - return raw[1:], nil -} - -// DecodeSeed will decode the base32 string and check crc16 and enforce the prefix is a seed -// and the subsequent type is a valid type. -func DecodeSeed(src []byte) (PrefixByte, []byte, error) { - raw, err := decode(src) - if err != nil { - return PrefixByteSeed, nil, err - } - // Need to do the reverse here to get back to internal representation. - b1 := raw[0] & 248 // 248 = 11111000 - b2 := (raw[0]&7)<<5 | ((raw[1] & 248) >> 3) // 7 = 00000111 - - if PrefixByte(b1) != PrefixByteSeed { - return PrefixByteSeed, nil, ErrInvalidSeed - } - if checkValidPublicPrefixByte(PrefixByte(b2)) != nil { - return PrefixByteSeed, nil, ErrInvalidSeed - } - return PrefixByte(b2), raw[2:], nil -} - -// Prefix returns PrefixBytes of its input -func Prefix(src string) PrefixByte { - b, err := decode([]byte(src)) - if err != nil { - return PrefixByteUnknown - } - prefix := PrefixByte(b[0]) - err = checkValidPrefixByte(prefix) - if err == nil { - return prefix - } - // Might be a seed. - b1 := b[0] & 248 - if PrefixByte(b1) == PrefixByteSeed { - return PrefixByteSeed - } - return PrefixByteUnknown -} - -// IsValidPublicKey will decode and verify that the string is a valid encoded public key. -func IsValidPublicKey(src string) bool { - b, err := decode([]byte(src)) - if err != nil { - return false - } - if prefix := PrefixByte(b[0]); checkValidPublicPrefixByte(prefix) != nil { - return false - } - return true -} - -// IsValidPublicUserKey will decode and verify the string is a valid encoded Public User Key. -func IsValidPublicUserKey(src string) bool { - _, err := Decode(PrefixByteUser, []byte(src)) - return err == nil -} - -// IsValidPublicAccountKey will decode and verify the string is a valid encoded Public Account Key. -func IsValidPublicAccountKey(src string) bool { - _, err := Decode(PrefixByteAccount, []byte(src)) - return err == nil -} - -// IsValidPublicServerKey will decode and verify the string is a valid encoded Public Server Key. -func IsValidPublicServerKey(src string) bool { - _, err := Decode(PrefixByteServer, []byte(src)) - return err == nil -} - -// IsValidPublicClusterKey will decode and verify the string is a valid encoded Public Cluster Key. -func IsValidPublicClusterKey(src string) bool { - _, err := Decode(PrefixByteCluster, []byte(src)) - return err == nil -} - -// IsValidPublicOperatorKey will decode and verify the string is a valid encoded Public Operator Key. -func IsValidPublicOperatorKey(src string) bool { - _, err := Decode(PrefixByteOperator, []byte(src)) - return err == nil -} - -// IsValidPublicCurveKey will decode and verify the string is a valid encoded Public Curve Key. -func IsValidPublicCurveKey(src string) bool { - _, err := Decode(PrefixByteCurve, []byte(src)) - return err == nil -} - -// checkValidPrefixByte returns an error if the provided value -// is not one of the defined valid prefix byte constants. -func checkValidPrefixByte(prefix PrefixByte) error { - switch prefix { - case PrefixByteOperator, PrefixByteServer, PrefixByteCluster, - PrefixByteAccount, PrefixByteUser, PrefixByteSeed, PrefixBytePrivate, PrefixByteCurve: - return nil - } - return ErrInvalidPrefixByte -} - -// checkValidPublicPrefixByte returns an error if the provided value -// is not one of the public defined valid prefix byte constants. -func checkValidPublicPrefixByte(prefix PrefixByte) error { - switch prefix { - case PrefixByteOperator, PrefixByteServer, PrefixByteCluster, PrefixByteAccount, PrefixByteUser, PrefixByteCurve: - return nil - } - return ErrInvalidPrefixByte -} - -func (p PrefixByte) String() string { - switch p { - case PrefixByteOperator: - return "operator" - case PrefixByteServer: - return "server" - case PrefixByteCluster: - return "cluster" - case PrefixByteAccount: - return "account" - case PrefixByteUser: - return "user" - case PrefixByteSeed: - return "seed" - case PrefixBytePrivate: - return "private" - case PrefixByteCurve: - return "x25519" - } - return "unknown" -} - -// CompatibleKeyPair returns an error if the KeyPair doesn't match expected PrefixByte(s) -func CompatibleKeyPair(kp KeyPair, expected ...PrefixByte) error { - pk, err := kp.PublicKey() - if err != nil { - return err - } - pkType := Prefix(pk) - for _, k := range expected { - if pkType == k { - return nil - } - } - - return ErrIncompatibleKey -} diff --git a/vendor/github.com/nats-io/nkeys/xkeys.go b/vendor/github.com/nats-io/nkeys/xkeys.go deleted file mode 100644 index 78f8b99e1..000000000 --- a/vendor/github.com/nats-io/nkeys/xkeys.go +++ /dev/null @@ -1,185 +0,0 @@ -// Copyright 2022-2023 The NATS 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 nkeys - -import ( - "bytes" - "crypto/rand" - "encoding/binary" - "io" - - "golang.org/x/crypto/curve25519" - "golang.org/x/crypto/nacl/box" -) - -// This package will support safe use of X25519 keys for asymmetric encryption. -// We will be compatible with nacl.Box, but generate random nonces automatically. -// We may add more advanced options in the future for group recipients and better -// end to end algorithms. - -const ( - curveKeyLen = 32 - curveDecodeLen = 35 - curveNonceLen = 24 -) - -type ckp struct { - seed [curveKeyLen]byte // Private raw key. -} - -// CreateCurveKeys will create a Curve typed KeyPair. -func CreateCurveKeys() (KeyPair, error) { - return CreateCurveKeysWithRand(rand.Reader) -} - -// CreateCurveKeysWithRand will create a Curve typed KeyPair -// with specified rand source. -func CreateCurveKeysWithRand(rr io.Reader) (KeyPair, error) { - var kp ckp - _, err := io.ReadFull(rr, kp.seed[:]) - if err != nil { - return nil, err - } - return &kp, nil -} - -// Will create a curve key pair from seed. -func FromCurveSeed(seed []byte) (KeyPair, error) { - pb, raw, err := DecodeSeed(seed) - if err != nil { - return nil, err - } - if pb != PrefixByteCurve || len(raw) != curveKeyLen { - return nil, ErrInvalidCurveSeed - } - var kp ckp - copy(kp.seed[:], raw) - return &kp, nil -} - -// Seed will return the encoded seed. -func (pair *ckp) Seed() ([]byte, error) { - return EncodeSeed(PrefixByteCurve, pair.seed[:]) -} - -// PublicKey will return the encoded public key. -func (pair *ckp) PublicKey() (string, error) { - var pub [curveKeyLen]byte - curve25519.ScalarBaseMult(&pub, &pair.seed) - key, err := Encode(PrefixByteCurve, pub[:]) - return string(key), err -} - -// PrivateKey will return the encoded private key. -func (pair *ckp) PrivateKey() ([]byte, error) { - return Encode(PrefixBytePrivate, pair.seed[:]) -} - -func decodePubCurveKey(src string, dest []byte) error { - var raw [curveDecodeLen]byte // should always be 35 - n, err := b32Enc.Decode(raw[:], []byte(src)) - if err != nil { - return err - } - if n != curveDecodeLen { - return ErrInvalidCurveKey - } - // Make sure it is what we expected. - if prefix := PrefixByte(raw[0]); prefix != PrefixByteCurve { - return ErrInvalidPublicKey - } - var crc uint16 - end := n - 2 - sum := raw[end:n] - checksum := bytes.NewReader(sum) - if err := binary.Read(checksum, binary.LittleEndian, &crc); err != nil { - return err - } - - // ensure checksum is valid - if err := validate(raw[:end], crc); err != nil { - return err - } - - // Copy over, ignore prefix byte. - copy(dest, raw[1:end]) - return nil -} - -// Only version for now, but could add in X3DH in the future, etc. -const XKeyVersionV1 = "xkv1" -const vlen = len(XKeyVersionV1) - -// Seal is compatible with nacl.Box.Seal() and can be used in similar situations for small messages. -// We generate the nonce from crypto rand by default. -func (pair *ckp) Seal(input []byte, recipient string) ([]byte, error) { - return pair.SealWithRand(input, recipient, rand.Reader) -} - -func (pair *ckp) SealWithRand(input []byte, recipient string, rr io.Reader) ([]byte, error) { - var ( - rpub [curveKeyLen]byte - nonce [curveNonceLen]byte - out [vlen + curveNonceLen]byte - err error - ) - - if err = decodePubCurveKey(recipient, rpub[:]); err != nil { - return nil, ErrInvalidRecipient - } - if _, err := io.ReadFull(rr, nonce[:]); err != nil { - return nil, err - } - copy(out[:vlen], []byte(XKeyVersionV1)) - copy(out[vlen:], nonce[:]) - return box.Seal(out[:], input, &nonce, &rpub, &pair.seed), nil -} - -func (pair *ckp) Open(input []byte, sender string) ([]byte, error) { - if len(input) <= vlen+curveNonceLen { - return nil, ErrInvalidEncrypted - } - var ( - spub [curveKeyLen]byte - nonce [curveNonceLen]byte - err error - ) - if !bytes.Equal(input[:vlen], []byte(XKeyVersionV1)) { - return nil, ErrInvalidEncVersion - } - copy(nonce[:], input[vlen:vlen+curveNonceLen]) - - if err = decodePubCurveKey(sender, spub[:]); err != nil { - return nil, ErrInvalidSender - } - - decrypted, ok := box.Open(nil, input[vlen+curveNonceLen:], &nonce, &spub, &pair.seed) - if !ok { - return nil, ErrCouldNotDecrypt - } - return decrypted, nil -} - -// Wipe will randomize the contents of the secret key -func (pair *ckp) Wipe() { - io.ReadFull(rand.Reader, pair.seed[:]) -} - -func (pair *ckp) Sign(_ []byte) ([]byte, error) { - return nil, ErrInvalidCurveKeyOperation -} - -func (pair *ckp) Verify(_ []byte, _ []byte) error { - return ErrInvalidCurveKeyOperation -} diff --git a/vendor/github.com/nats-io/nuid/.gitignore b/vendor/github.com/nats-io/nuid/.gitignore deleted file mode 100644 index daf913b1b..000000000 --- a/vendor/github.com/nats-io/nuid/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof diff --git a/vendor/github.com/nats-io/nuid/.travis.yml b/vendor/github.com/nats-io/nuid/.travis.yml deleted file mode 100644 index 52be72657..000000000 --- a/vendor/github.com/nats-io/nuid/.travis.yml +++ /dev/null @@ -1,17 +0,0 @@ -language: go -sudo: false -go: -- 1.9.x -- 1.10.x - -install: -- go get -t ./... -- go get github.com/mattn/goveralls - -script: -- go fmt ./... -- go vet ./... -- go test -v -- go test -v --race -- go test -v -covermode=count -coverprofile=coverage.out -- $HOME/gopath/bin/goveralls -coverprofile coverage.out -service travis-ci diff --git a/vendor/github.com/nats-io/nuid/GOVERNANCE.md b/vendor/github.com/nats-io/nuid/GOVERNANCE.md deleted file mode 100644 index 01aee70d4..000000000 --- a/vendor/github.com/nats-io/nuid/GOVERNANCE.md +++ /dev/null @@ -1,3 +0,0 @@ -# NATS NUID Governance - -NATS NUID is part of the NATS project and is subject to the [NATS Governance](https://github.com/nats-io/nats-general/blob/master/GOVERNANCE.md). \ No newline at end of file diff --git a/vendor/github.com/nats-io/nuid/LICENSE b/vendor/github.com/nats-io/nuid/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/vendor/github.com/nats-io/nuid/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - 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 "[]" - 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 - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/nats-io/nuid/MAINTAINERS.md b/vendor/github.com/nats-io/nuid/MAINTAINERS.md deleted file mode 100644 index 6d0ed3e31..000000000 --- a/vendor/github.com/nats-io/nuid/MAINTAINERS.md +++ /dev/null @@ -1,6 +0,0 @@ -# Maintainers - -Maintainership is on a per project basis. - -### Core-maintainers - - Derek Collison [@derekcollison](https://github.com/derekcollison) \ No newline at end of file diff --git a/vendor/github.com/nats-io/nuid/README.md b/vendor/github.com/nats-io/nuid/README.md deleted file mode 100644 index 16e539485..000000000 --- a/vendor/github.com/nats-io/nuid/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# NUID - -[![License Apache 2](https://img.shields.io/badge/License-Apache2-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0) -[![ReportCard](http://goreportcard.com/badge/nats-io/nuid)](http://goreportcard.com/report/nats-io/nuid) -[![Build Status](https://travis-ci.org/nats-io/nuid.svg?branch=master)](http://travis-ci.org/nats-io/nuid) -[![Release](https://img.shields.io/badge/release-v1.0.1-1eb0fc.svg)](https://github.com/nats-io/nuid/releases/tag/v1.0.1) -[![GoDoc](http://godoc.org/github.com/nats-io/nuid?status.png)](http://godoc.org/github.com/nats-io/nuid) -[![Coverage Status](https://coveralls.io/repos/github/nats-io/nuid/badge.svg?branch=master)](https://coveralls.io/github/nats-io/nuid?branch=master) - -A highly performant unique identifier generator. - -## Installation - -Use the `go` command: - - $ go get github.com/nats-io/nuid - -## Basic Usage -```go - -// Utilize the global locked instance -nuid := nuid.Next() - -// Create an instance, these are not locked. -n := nuid.New() -nuid = n.Next() - -// Generate a new crypto/rand seeded prefix. -// Generally not needed, happens automatically. -n.RandomizePrefix() -``` - -## Performance -NUID needs to be very fast to generate and be truly unique, all while being entropy pool friendly. -NUID uses 12 bytes of crypto generated data (entropy draining), and 10 bytes of pseudo-random -sequential data that increments with a pseudo-random increment. - -Total length of a NUID string is 22 bytes of base 62 ascii text, so 62^22 or -2707803647802660400290261537185326956544 possibilities. - -NUID can generate identifiers as fast as 60ns, or ~16 million per second. There is an associated -benchmark you can use to test performance on your own hardware. - -## License - -Unless otherwise noted, the NATS source files are distributed -under the Apache Version 2.0 license found in the LICENSE file. diff --git a/vendor/github.com/nats-io/nuid/nuid.go b/vendor/github.com/nats-io/nuid/nuid.go deleted file mode 100644 index 8134c7646..000000000 --- a/vendor/github.com/nats-io/nuid/nuid.go +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright 2016-2019 The NATS 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. - -// A unique identifier generator that is high performance, very fast, and tries to be entropy pool friendly. -package nuid - -import ( - "crypto/rand" - "fmt" - "math" - "math/big" - "sync" - "time" - - prand "math/rand" -) - -// NUID needs to be very fast to generate and truly unique, all while being entropy pool friendly. -// We will use 12 bytes of crypto generated data (entropy draining), and 10 bytes of sequential data -// that is started at a pseudo random number and increments with a pseudo-random increment. -// Total is 22 bytes of base 62 ascii text :) - -// Version of the library -const Version = "1.0.1" - -const ( - digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" - base = 62 - preLen = 12 - seqLen = 10 - maxSeq = int64(839299365868340224) // base^seqLen == 62^10 - minInc = int64(33) - maxInc = int64(333) - totalLen = preLen + seqLen -) - -type NUID struct { - pre []byte - seq int64 - inc int64 -} - -type lockedNUID struct { - sync.Mutex - *NUID -} - -// Global NUID -var globalNUID *lockedNUID - -// Seed sequential random with crypto or math/random and current time -// and generate crypto prefix. -func init() { - r, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64)) - if err != nil { - prand.Seed(time.Now().UnixNano()) - } else { - prand.Seed(r.Int64()) - } - globalNUID = &lockedNUID{NUID: New()} - globalNUID.RandomizePrefix() -} - -// New will generate a new NUID and properly initialize the prefix, sequential start, and sequential increment. -func New() *NUID { - n := &NUID{ - seq: prand.Int63n(maxSeq), - inc: minInc + prand.Int63n(maxInc-minInc), - pre: make([]byte, preLen), - } - n.RandomizePrefix() - return n -} - -// Generate the next NUID string from the global locked NUID instance. -func Next() string { - globalNUID.Lock() - nuid := globalNUID.Next() - globalNUID.Unlock() - return nuid -} - -// Generate the next NUID string. -func (n *NUID) Next() string { - // Increment and capture. - n.seq += n.inc - if n.seq >= maxSeq { - n.RandomizePrefix() - n.resetSequential() - } - seq := n.seq - - // Copy prefix - var b [totalLen]byte - bs := b[:preLen] - copy(bs, n.pre) - - // copy in the seq in base62. - for i, l := len(b), seq; i > preLen; l /= base { - i -= 1 - b[i] = digits[l%base] - } - return string(b[:]) -} - -// Resets the sequential portion of the NUID. -func (n *NUID) resetSequential() { - n.seq = prand.Int63n(maxSeq) - n.inc = minInc + prand.Int63n(maxInc-minInc) -} - -// Generate a new prefix from crypto/rand. -// This call *can* drain entropy and will be called automatically when we exhaust the sequential range. -// Will panic if it gets an error from rand.Int() -func (n *NUID) RandomizePrefix() { - var cb [preLen]byte - cbs := cb[:] - if nb, err := rand.Read(cbs); nb != preLen || err != nil { - panic(fmt.Sprintf("nuid: failed generating crypto random number: %v\n", err)) - } - - for i := 0; i < preLen; i++ { - n.pre[i] = digits[int(cbs[i])%base] - } -} diff --git a/vendor/github.com/opencontainers/image-spec/LICENSE b/vendor/github.com/opencontainers/image-spec/LICENSE deleted file mode 100644 index 9fdc20fdb..000000000 --- a/vendor/github.com/opencontainers/image-spec/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2016 The Linux Foundation. - - 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. diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/v1/annotations.go b/vendor/github.com/opencontainers/image-spec/specs-go/v1/annotations.go deleted file mode 100644 index e62892046..000000000 --- a/vendor/github.com/opencontainers/image-spec/specs-go/v1/annotations.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2016 The Linux Foundation -// -// 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 v1 - -const ( - // AnnotationCreated is the annotation key for the date and time on which the image was built (date-time string as defined by RFC 3339). - AnnotationCreated = "org.opencontainers.image.created" - - // AnnotationAuthors is the annotation key for the contact details of the people or organization responsible for the image (freeform string). - AnnotationAuthors = "org.opencontainers.image.authors" - - // AnnotationURL is the annotation key for the URL to find more information on the image. - AnnotationURL = "org.opencontainers.image.url" - - // AnnotationDocumentation is the annotation key for the URL to get documentation on the image. - AnnotationDocumentation = "org.opencontainers.image.documentation" - - // AnnotationSource is the annotation key for the URL to get source code for building the image. - AnnotationSource = "org.opencontainers.image.source" - - // AnnotationVersion is the annotation key for the version of the packaged software. - // The version MAY match a label or tag in the source code repository. - // The version MAY be Semantic versioning-compatible. - AnnotationVersion = "org.opencontainers.image.version" - - // AnnotationRevision is the annotation key for the source control revision identifier for the packaged software. - AnnotationRevision = "org.opencontainers.image.revision" - - // AnnotationVendor is the annotation key for the name of the distributing entity, organization or individual. - AnnotationVendor = "org.opencontainers.image.vendor" - - // AnnotationLicenses is the annotation key for the license(s) under which contained software is distributed as an SPDX License Expression. - AnnotationLicenses = "org.opencontainers.image.licenses" - - // AnnotationRefName is the annotation key for the name of the reference for a target. - // SHOULD only be considered valid when on descriptors on `index.json` within image layout. - AnnotationRefName = "org.opencontainers.image.ref.name" - - // AnnotationTitle is the annotation key for the human-readable title of the image. - AnnotationTitle = "org.opencontainers.image.title" - - // AnnotationDescription is the annotation key for the human-readable description of the software packaged in the image. - AnnotationDescription = "org.opencontainers.image.description" - - // AnnotationBaseImageDigest is the annotation key for the digest of the image's base image. - AnnotationBaseImageDigest = "org.opencontainers.image.base.digest" - - // AnnotationBaseImageName is the annotation key for the image reference of the image's base image. - AnnotationBaseImageName = "org.opencontainers.image.base.name" - - // AnnotationArtifactCreated is the annotation key for the date and time on which the artifact was built, conforming to RFC 3339. - AnnotationArtifactCreated = "org.opencontainers.artifact.created" - - // AnnotationArtifactDescription is the annotation key for the human readable description for the artifact. - AnnotationArtifactDescription = "org.opencontainers.artifact.description" -) diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/v1/config.go b/vendor/github.com/opencontainers/image-spec/specs-go/v1/config.go deleted file mode 100644 index 36b0aeb8f..000000000 --- a/vendor/github.com/opencontainers/image-spec/specs-go/v1/config.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2016 The Linux Foundation -// -// 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 v1 - -import ( - "time" - - digest "github.com/opencontainers/go-digest" -) - -// ImageConfig defines the execution parameters which should be used as a base when running a container using an image. -type ImageConfig struct { - // User defines the username or UID which the process in the container should run as. - User string `json:"User,omitempty"` - - // ExposedPorts a set of ports to expose from a container running this image. - ExposedPorts map[string]struct{} `json:"ExposedPorts,omitempty"` - - // Env is a list of environment variables to be used in a container. - Env []string `json:"Env,omitempty"` - - // Entrypoint defines a list of arguments to use as the command to execute when the container starts. - Entrypoint []string `json:"Entrypoint,omitempty"` - - // Cmd defines the default arguments to the entrypoint of the container. - Cmd []string `json:"Cmd,omitempty"` - - // Volumes is a set of directories describing where the process is likely write data specific to a container instance. - Volumes map[string]struct{} `json:"Volumes,omitempty"` - - // WorkingDir sets the current working directory of the entrypoint process in the container. - WorkingDir string `json:"WorkingDir,omitempty"` - - // Labels contains arbitrary metadata for the container. - Labels map[string]string `json:"Labels,omitempty"` - - // StopSignal contains the system call signal that will be sent to the container to exit. - StopSignal string `json:"StopSignal,omitempty"` - - // ArgsEscaped - // - // Deprecated: This field is present only for legacy compatibility with - // Docker and should not be used by new image builders. It is used by Docker - // for Windows images to indicate that the `Entrypoint` or `Cmd` or both, - // contains only a single element array, that is a pre-escaped, and combined - // into a single string `CommandLine`. If `true` the value in `Entrypoint` or - // `Cmd` should be used as-is to avoid double escaping. - // https://github.com/opencontainers/image-spec/pull/892 - ArgsEscaped bool `json:"ArgsEscaped,omitempty"` -} - -// RootFS describes a layer content addresses -type RootFS struct { - // Type is the type of the rootfs. - Type string `json:"type"` - - // DiffIDs is an array of layer content hashes (DiffIDs), in order from bottom-most to top-most. - DiffIDs []digest.Digest `json:"diff_ids"` -} - -// History describes the history of a layer. -type History struct { - // Created is the combined date and time at which the layer was created, formatted as defined by RFC 3339, section 5.6. - Created *time.Time `json:"created,omitempty"` - - // CreatedBy is the command which created the layer. - CreatedBy string `json:"created_by,omitempty"` - - // Author is the author of the build point. - Author string `json:"author,omitempty"` - - // Comment is a custom message set when creating the layer. - Comment string `json:"comment,omitempty"` - - // EmptyLayer is used to mark if the history item created a filesystem diff. - EmptyLayer bool `json:"empty_layer,omitempty"` -} - -// Image is the JSON structure which describes some basic information about the image. -// This provides the `application/vnd.oci.image.config.v1+json` mediatype when marshalled to JSON. -type Image struct { - // Created is the combined date and time at which the image was created, formatted as defined by RFC 3339, section 5.6. - Created *time.Time `json:"created,omitempty"` - - // Author defines the name and/or email address of the person or entity which created and is responsible for maintaining the image. - Author string `json:"author,omitempty"` - - // Platform describes the platform which the image in the manifest runs on. - Platform - - // Config defines the execution parameters which should be used as a base when running a container using the image. - Config ImageConfig `json:"config,omitempty"` - - // RootFS references the layer content addresses used by the image. - RootFS RootFS `json:"rootfs"` - - // History describes the history of each layer. - History []History `json:"history,omitempty"` -} diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/v1/descriptor.go b/vendor/github.com/opencontainers/image-spec/specs-go/v1/descriptor.go deleted file mode 100644 index 9654aa5af..000000000 --- a/vendor/github.com/opencontainers/image-spec/specs-go/v1/descriptor.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2016-2022 The Linux Foundation -// -// 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 v1 - -import digest "github.com/opencontainers/go-digest" - -// Descriptor describes the disposition of targeted content. -// This structure provides `application/vnd.oci.descriptor.v1+json` mediatype -// when marshalled to JSON. -type Descriptor struct { - // MediaType is the media type of the object this schema refers to. - MediaType string `json:"mediaType,omitempty"` - - // Digest is the digest of the targeted content. - Digest digest.Digest `json:"digest"` - - // Size specifies the size in bytes of the blob. - Size int64 `json:"size"` - - // URLs specifies a list of URLs from which this object MAY be downloaded - URLs []string `json:"urls,omitempty"` - - // Annotations contains arbitrary metadata relating to the targeted content. - Annotations map[string]string `json:"annotations,omitempty"` - - // Data is an embedding of the targeted content. This is encoded as a base64 - // string when marshalled to JSON (automatically, by encoding/json). If - // present, Data can be used directly to avoid fetching the targeted content. - Data []byte `json:"data,omitempty"` - - // Platform describes the platform which the image in the manifest runs on. - // - // This should only be used when referring to a manifest. - Platform *Platform `json:"platform,omitempty"` - - // ArtifactType is the IANA media type of this artifact. - ArtifactType string `json:"artifactType,omitempty"` -} - -// Platform describes the platform which the image in the manifest runs on. -type Platform struct { - // Architecture field specifies the CPU architecture, for example - // `amd64` or `ppc64`. - Architecture string `json:"architecture"` - - // OS specifies the operating system, for example `linux` or `windows`. - OS string `json:"os"` - - // OSVersion is an optional field specifying the operating system - // version, for example on Windows `10.0.14393.1066`. - OSVersion string `json:"os.version,omitempty"` - - // OSFeatures is an optional field specifying an array of strings, - // each listing a required OS feature (for example on Windows `win32k`). - OSFeatures []string `json:"os.features,omitempty"` - - // Variant is an optional field specifying a variant of the CPU, for - // example `v7` to specify ARMv7 when architecture is `arm`. - Variant string `json:"variant,omitempty"` -} diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/v1/index.go b/vendor/github.com/opencontainers/image-spec/specs-go/v1/index.go deleted file mode 100644 index ed4a56e59..000000000 --- a/vendor/github.com/opencontainers/image-spec/specs-go/v1/index.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2016 The Linux Foundation -// -// 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 v1 - -import "github.com/opencontainers/image-spec/specs-go" - -// Index references manifests for various platforms. -// This structure provides `application/vnd.oci.image.index.v1+json` mediatype when marshalled to JSON. -type Index struct { - specs.Versioned - - // MediaType specifies the type of this document data structure e.g. `application/vnd.oci.image.index.v1+json` - MediaType string `json:"mediaType,omitempty"` - - // Manifests references platform specific manifests. - Manifests []Descriptor `json:"manifests"` - - // Annotations contains arbitrary metadata for the image index. - Annotations map[string]string `json:"annotations,omitempty"` -} diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/v1/layout.go b/vendor/github.com/opencontainers/image-spec/specs-go/v1/layout.go deleted file mode 100644 index fc79e9e0d..000000000 --- a/vendor/github.com/opencontainers/image-spec/specs-go/v1/layout.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2016 The Linux Foundation -// -// 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 v1 - -const ( - // ImageLayoutFile is the file name of oci image layout file - ImageLayoutFile = "oci-layout" - // ImageLayoutVersion is the version of ImageLayout - ImageLayoutVersion = "1.0.0" -) - -// ImageLayout is the structure in the "oci-layout" file, found in the root -// of an OCI Image-layout directory. -type ImageLayout struct { - Version string `json:"imageLayoutVersion"` -} diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/v1/manifest.go b/vendor/github.com/opencontainers/image-spec/specs-go/v1/manifest.go deleted file mode 100644 index 4ce7b54cc..000000000 --- a/vendor/github.com/opencontainers/image-spec/specs-go/v1/manifest.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2016-2022 The Linux Foundation -// -// 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 v1 - -import "github.com/opencontainers/image-spec/specs-go" - -// Manifest provides `application/vnd.oci.image.manifest.v1+json` mediatype structure when marshalled to JSON. -type Manifest struct { - specs.Versioned - - // MediaType specifies the type of this document data structure e.g. `application/vnd.oci.image.manifest.v1+json` - MediaType string `json:"mediaType,omitempty"` - - // ArtifactType specifies the IANA media type of artifact when the manifest is used for an artifact. - ArtifactType string `json:"artifactType,omitempty"` - - // Config references a configuration object for a container, by digest. - // The referenced configuration object is a JSON blob that the runtime uses to set up the container. - Config Descriptor `json:"config"` - - // Layers is an indexed list of layers referenced by the manifest. - Layers []Descriptor `json:"layers"` - - // Subject is an optional link from the image manifest to another manifest forming an association between the image manifest and the other manifest. - Subject *Descriptor `json:"subject,omitempty"` - - // Annotations contains arbitrary metadata for the image manifest. - Annotations map[string]string `json:"annotations,omitempty"` -} - -// ScratchDescriptor is the descriptor of a blob with content of `{}`. -var ScratchDescriptor = Descriptor{ - MediaType: MediaTypeScratch, - Digest: `sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a`, - Size: 2, - Data: []byte(`{}`), -} diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/v1/mediatype.go b/vendor/github.com/opencontainers/image-spec/specs-go/v1/mediatype.go deleted file mode 100644 index 5dd31255e..000000000 --- a/vendor/github.com/opencontainers/image-spec/specs-go/v1/mediatype.go +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright 2016 The Linux Foundation -// -// 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 v1 - -const ( - // MediaTypeDescriptor specifies the media type for a content descriptor. - MediaTypeDescriptor = "application/vnd.oci.descriptor.v1+json" - - // MediaTypeLayoutHeader specifies the media type for the oci-layout. - MediaTypeLayoutHeader = "application/vnd.oci.layout.header.v1+json" - - // MediaTypeImageManifest specifies the media type for an image manifest. - MediaTypeImageManifest = "application/vnd.oci.image.manifest.v1+json" - - // MediaTypeImageIndex specifies the media type for an image index. - MediaTypeImageIndex = "application/vnd.oci.image.index.v1+json" - - // MediaTypeImageLayer is the media type used for layers referenced by the manifest. - MediaTypeImageLayer = "application/vnd.oci.image.layer.v1.tar" - - // MediaTypeImageLayerGzip is the media type used for gzipped layers - // referenced by the manifest. - MediaTypeImageLayerGzip = "application/vnd.oci.image.layer.v1.tar+gzip" - - // MediaTypeImageLayerZstd is the media type used for zstd compressed - // layers referenced by the manifest. - MediaTypeImageLayerZstd = "application/vnd.oci.image.layer.v1.tar+zstd" - - // MediaTypeImageLayerNonDistributable is the media type for layers referenced by - // the manifest but with distribution restrictions. - // - // Deprecated: Non-distributable layers are deprecated, and not recommended - // for future use. Implementations SHOULD NOT produce new non-distributable - // layers. - // https://github.com/opencontainers/image-spec/pull/965 - MediaTypeImageLayerNonDistributable = "application/vnd.oci.image.layer.nondistributable.v1.tar" - - // MediaTypeImageLayerNonDistributableGzip is the media type for - // gzipped layers referenced by the manifest but with distribution - // restrictions. - // - // Deprecated: Non-distributable layers are deprecated, and not recommended - // for future use. Implementations SHOULD NOT produce new non-distributable - // layers. - // https://github.com/opencontainers/image-spec/pull/965 - MediaTypeImageLayerNonDistributableGzip = "application/vnd.oci.image.layer.nondistributable.v1.tar+gzip" - - // MediaTypeImageLayerNonDistributableZstd is the media type for zstd - // compressed layers referenced by the manifest but with distribution - // restrictions. - // - // Deprecated: Non-distributable layers are deprecated, and not recommended - // for future use. Implementations SHOULD NOT produce new non-distributable - // layers. - // https://github.com/opencontainers/image-spec/pull/965 - MediaTypeImageLayerNonDistributableZstd = "application/vnd.oci.image.layer.nondistributable.v1.tar+zstd" - - // MediaTypeImageConfig specifies the media type for the image configuration. - MediaTypeImageConfig = "application/vnd.oci.image.config.v1+json" - - // MediaTypeScratch specifies the media type for an unused blob containing the value `{}` - MediaTypeScratch = "application/vnd.oci.scratch.v1+json" -) diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/version.go b/vendor/github.com/opencontainers/image-spec/specs-go/version.go deleted file mode 100644 index 3d4119b44..000000000 --- a/vendor/github.com/opencontainers/image-spec/specs-go/version.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2016 The Linux Foundation -// -// 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 specs - -import "fmt" - -const ( - // VersionMajor is for an API incompatible changes - VersionMajor = 1 - // VersionMinor is for functionality in a backwards-compatible manner - VersionMinor = 1 - // VersionPatch is for backwards-compatible bug fixes - VersionPatch = 0 - - // VersionDev indicates development branch. Releases will be empty string. - VersionDev = "-rc.3" -) - -// Version is the specification version that the package types support. -var Version = fmt.Sprintf("%d.%d.%d%s", VersionMajor, VersionMinor, VersionPatch, VersionDev) diff --git a/vendor/github.com/opencontainers/image-spec/specs-go/versioned.go b/vendor/github.com/opencontainers/image-spec/specs-go/versioned.go deleted file mode 100644 index 58a1510f3..000000000 --- a/vendor/github.com/opencontainers/image-spec/specs-go/versioned.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2016 The Linux Foundation -// -// 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 specs - -// Versioned provides a struct with the manifest schemaVersion and mediaType. -// Incoming content with unknown schema version can be decoded against this -// struct to check the version. -type Versioned struct { - // SchemaVersion is the image manifest schema that this image follows - SchemaVersion int `json:"schemaVersion"` -} diff --git a/vendor/github.com/sirupsen/logrus/.gitignore b/vendor/github.com/sirupsen/logrus/.gitignore deleted file mode 100644 index 1fb13abeb..000000000 --- a/vendor/github.com/sirupsen/logrus/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -logrus -vendor - -.idea/ diff --git a/vendor/github.com/sirupsen/logrus/.golangci.yml b/vendor/github.com/sirupsen/logrus/.golangci.yml deleted file mode 100644 index 65dc28503..000000000 --- a/vendor/github.com/sirupsen/logrus/.golangci.yml +++ /dev/null @@ -1,40 +0,0 @@ -run: - # do not run on test files yet - tests: false - -# all available settings of specific linters -linters-settings: - errcheck: - # report about not checking of errors in type assetions: `a := b.(MyStruct)`; - # default is false: such cases aren't reported by default. - check-type-assertions: false - - # report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`; - # default is false: such cases aren't reported by default. - check-blank: false - - lll: - line-length: 100 - tab-width: 4 - - prealloc: - simple: false - range-loops: false - for-loops: false - - whitespace: - multi-if: false # Enforces newlines (or comments) after every multi-line if statement - multi-func: false # Enforces newlines (or comments) after every multi-line function signature - -linters: - enable: - - megacheck - - govet - disable: - - maligned - - prealloc - disable-all: false - presets: - - bugs - - unused - fast: false diff --git a/vendor/github.com/sirupsen/logrus/.travis.yml b/vendor/github.com/sirupsen/logrus/.travis.yml deleted file mode 100644 index c1dbd5a3a..000000000 --- a/vendor/github.com/sirupsen/logrus/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -language: go -go_import_path: github.com/sirupsen/logrus -git: - depth: 1 -env: - - GO111MODULE=on -go: 1.15.x -os: linux -install: - - ./travis/install.sh -script: - - cd ci - - go run mage.go -v -w ../ crossBuild - - go run mage.go -v -w ../ lint - - go run mage.go -v -w ../ test diff --git a/vendor/github.com/sirupsen/logrus/CHANGELOG.md b/vendor/github.com/sirupsen/logrus/CHANGELOG.md deleted file mode 100644 index 7567f6128..000000000 --- a/vendor/github.com/sirupsen/logrus/CHANGELOG.md +++ /dev/null @@ -1,259 +0,0 @@ -# 1.8.1 -Code quality: - * move magefile in its own subdir/submodule to remove magefile dependency on logrus consumer - * improve timestamp format documentation - -Fixes: - * fix race condition on logger hooks - - -# 1.8.0 - -Correct versioning number replacing v1.7.1. - -# 1.7.1 - -Beware this release has introduced a new public API and its semver is therefore incorrect. - -Code quality: - * use go 1.15 in travis - * use magefile as task runner - -Fixes: - * small fixes about new go 1.13 error formatting system - * Fix for long time race condiction with mutating data hooks - -Features: - * build support for zos - -# 1.7.0 -Fixes: - * the dependency toward a windows terminal library has been removed - -Features: - * a new buffer pool management API has been added - * a set of `Fn()` functions have been added - -# 1.6.0 -Fixes: - * end of line cleanup - * revert the entry concurrency bug fix whic leads to deadlock under some circumstances - * update dependency on go-windows-terminal-sequences to fix a crash with go 1.14 - -Features: - * add an option to the `TextFormatter` to completely disable fields quoting - -# 1.5.0 -Code quality: - * add golangci linter run on travis - -Fixes: - * add mutex for hooks concurrent access on `Entry` data - * caller function field for go1.14 - * fix build issue for gopherjs target - -Feature: - * add an hooks/writer sub-package whose goal is to split output on different stream depending on the trace level - * add a `DisableHTMLEscape` option in the `JSONFormatter` - * add `ForceQuote` and `PadLevelText` options in the `TextFormatter` - -# 1.4.2 - * Fixes build break for plan9, nacl, solaris -# 1.4.1 -This new release introduces: - * Enhance TextFormatter to not print caller information when they are empty (#944) - * Remove dependency on golang.org/x/crypto (#932, #943) - -Fixes: - * Fix Entry.WithContext method to return a copy of the initial entry (#941) - -# 1.4.0 -This new release introduces: - * Add `DeferExitHandler`, similar to `RegisterExitHandler` but prepending the handler to the list of handlers (semantically like `defer`) (#848). - * Add `CallerPrettyfier` to `JSONFormatter` and `TextFormatter` (#909, #911) - * Add `Entry.WithContext()` and `Entry.Context`, to set a context on entries to be used e.g. in hooks (#919). - -Fixes: - * Fix wrong method calls `Logger.Print` and `Logger.Warningln` (#893). - * Update `Entry.Logf` to not do string formatting unless the log level is enabled (#903) - * Fix infinite recursion on unknown `Level.String()` (#907) - * Fix race condition in `getCaller` (#916). - - -# 1.3.0 -This new release introduces: - * Log, Logf, Logln functions for Logger and Entry that take a Level - -Fixes: - * Building prometheus node_exporter on AIX (#840) - * Race condition in TextFormatter (#468) - * Travis CI import path (#868) - * Remove coloured output on Windows (#862) - * Pointer to func as field in JSONFormatter (#870) - * Properly marshal Levels (#873) - -# 1.2.0 -This new release introduces: - * A new method `SetReportCaller` in the `Logger` to enable the file, line and calling function from which the trace has been issued - * A new trace level named `Trace` whose level is below `Debug` - * A configurable exit function to be called upon a Fatal trace - * The `Level` object now implements `encoding.TextUnmarshaler` interface - -# 1.1.1 -This is a bug fix release. - * fix the build break on Solaris - * don't drop a whole trace in JSONFormatter when a field param is a function pointer which can not be serialized - -# 1.1.0 -This new release introduces: - * several fixes: - * a fix for a race condition on entry formatting - * proper cleanup of previously used entries before putting them back in the pool - * the extra new line at the end of message in text formatter has been removed - * a new global public API to check if a level is activated: IsLevelEnabled - * the following methods have been added to the Logger object - * IsLevelEnabled - * SetFormatter - * SetOutput - * ReplaceHooks - * introduction of go module - * an indent configuration for the json formatter - * output colour support for windows - * the field sort function is now configurable for text formatter - * the CLICOLOR and CLICOLOR\_FORCE environment variable support in text formater - -# 1.0.6 - -This new release introduces: - * a new api WithTime which allows to easily force the time of the log entry - which is mostly useful for logger wrapper - * a fix reverting the immutability of the entry given as parameter to the hooks - a new configuration field of the json formatter in order to put all the fields - in a nested dictionnary - * a new SetOutput method in the Logger - * a new configuration of the textformatter to configure the name of the default keys - * a new configuration of the text formatter to disable the level truncation - -# 1.0.5 - -* Fix hooks race (#707) -* Fix panic deadlock (#695) - -# 1.0.4 - -* Fix race when adding hooks (#612) -* Fix terminal check in AppEngine (#635) - -# 1.0.3 - -* Replace example files with testable examples - -# 1.0.2 - -* bug: quote non-string values in text formatter (#583) -* Make (*Logger) SetLevel a public method - -# 1.0.1 - -* bug: fix escaping in text formatter (#575) - -# 1.0.0 - -* Officially changed name to lower-case -* bug: colors on Windows 10 (#541) -* bug: fix race in accessing level (#512) - -# 0.11.5 - -* feature: add writer and writerlevel to entry (#372) - -# 0.11.4 - -* bug: fix undefined variable on solaris (#493) - -# 0.11.3 - -* formatter: configure quoting of empty values (#484) -* formatter: configure quoting character (default is `"`) (#484) -* bug: fix not importing io correctly in non-linux environments (#481) - -# 0.11.2 - -* bug: fix windows terminal detection (#476) - -# 0.11.1 - -* bug: fix tty detection with custom out (#471) - -# 0.11.0 - -* performance: Use bufferpool to allocate (#370) -* terminal: terminal detection for app-engine (#343) -* feature: exit handler (#375) - -# 0.10.0 - -* feature: Add a test hook (#180) -* feature: `ParseLevel` is now case-insensitive (#326) -* feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308) -* performance: avoid re-allocations on `WithFields` (#335) - -# 0.9.0 - -* logrus/text_formatter: don't emit empty msg -* logrus/hooks/airbrake: move out of main repository -* logrus/hooks/sentry: move out of main repository -* logrus/hooks/papertrail: move out of main repository -* logrus/hooks/bugsnag: move out of main repository -* logrus/core: run tests with `-race` -* logrus/core: detect TTY based on `stderr` -* logrus/core: support `WithError` on logger -* logrus/core: Solaris support - -# 0.8.7 - -* logrus/core: fix possible race (#216) -* logrus/doc: small typo fixes and doc improvements - - -# 0.8.6 - -* hooks/raven: allow passing an initialized client - -# 0.8.5 - -* logrus/core: revert #208 - -# 0.8.4 - -* formatter/text: fix data race (#218) - -# 0.8.3 - -* logrus/core: fix entry log level (#208) -* logrus/core: improve performance of text formatter by 40% -* logrus/core: expose `LevelHooks` type -* logrus/core: add support for DragonflyBSD and NetBSD -* formatter/text: print structs more verbosely - -# 0.8.2 - -* logrus: fix more Fatal family functions - -# 0.8.1 - -* logrus: fix not exiting on `Fatalf` and `Fatalln` - -# 0.8.0 - -* logrus: defaults to stderr instead of stdout -* hooks/sentry: add special field for `*http.Request` -* formatter/text: ignore Windows for colors - -# 0.7.3 - -* formatter/\*: allow configuration of timestamp layout - -# 0.7.2 - -* formatter/text: Add configuration option for time format (#158) diff --git a/vendor/github.com/sirupsen/logrus/LICENSE b/vendor/github.com/sirupsen/logrus/LICENSE deleted file mode 100644 index f090cb42f..000000000 --- a/vendor/github.com/sirupsen/logrus/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Simon Eskildsen - -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. diff --git a/vendor/github.com/sirupsen/logrus/README.md b/vendor/github.com/sirupsen/logrus/README.md deleted file mode 100644 index d1d4a85fd..000000000 --- a/vendor/github.com/sirupsen/logrus/README.md +++ /dev/null @@ -1,515 +0,0 @@ -# Logrus :walrus: [![Build Status](https://github.com/sirupsen/logrus/workflows/CI/badge.svg)](https://github.com/sirupsen/logrus/actions?query=workflow%3ACI) [![Build Status](https://travis-ci.org/sirupsen/logrus.svg?branch=master)](https://travis-ci.org/sirupsen/logrus) [![Go Reference](https://pkg.go.dev/badge/github.com/sirupsen/logrus.svg)](https://pkg.go.dev/github.com/sirupsen/logrus) - -Logrus is a structured logger for Go (golang), completely API compatible with -the standard library logger. - -**Logrus is in maintenance-mode.** We will not be introducing new features. It's -simply too hard to do in a way that won't break many people's projects, which is -the last thing you want from your Logging library (again...). - -This does not mean Logrus is dead. Logrus will continue to be maintained for -security, (backwards compatible) bug fixes, and performance (where we are -limited by the interface). - -I believe Logrus' biggest contribution is to have played a part in today's -widespread use of structured logging in Golang. There doesn't seem to be a -reason to do a major, breaking iteration into Logrus V2, since the fantastic Go -community has built those independently. Many fantastic alternatives have sprung -up. Logrus would look like those, had it been re-designed with what we know -about structured logging in Go today. Check out, for example, -[Zerolog][zerolog], [Zap][zap], and [Apex][apex]. - -[zerolog]: https://github.com/rs/zerolog -[zap]: https://github.com/uber-go/zap -[apex]: https://github.com/apex/log - -**Seeing weird case-sensitive problems?** It's in the past been possible to -import Logrus as both upper- and lower-case. Due to the Go package environment, -this caused issues in the community and we needed a standard. Some environments -experienced problems with the upper-case variant, so the lower-case was decided. -Everything using `logrus` will need to use the lower-case: -`github.com/sirupsen/logrus`. Any package that isn't, should be changed. - -To fix Glide, see [these -comments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437). -For an in-depth explanation of the casing issue, see [this -comment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276). - -Nicely color-coded in development (when a TTY is attached, otherwise just -plain text): - -![Colored](http://i.imgur.com/PY7qMwd.png) - -With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash -or Splunk: - -```text -{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the -ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} - -{"level":"warning","msg":"The group's number increased tremendously!", -"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"} - -{"animal":"walrus","level":"info","msg":"A giant walrus appears!", -"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"} - -{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.", -"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"} - -{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true, -"time":"2014-03-10 19:57:38.562543128 -0400 EDT"} -``` - -With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not -attached, the output is compatible with the -[logfmt](http://godoc.org/github.com/kr/logfmt) format: - -```text -time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8 -time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 -time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true -time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4 -time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009 -time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true -``` -To ensure this behaviour even if a TTY is attached, set your formatter as follows: - -```go - log.SetFormatter(&log.TextFormatter{ - DisableColors: true, - FullTimestamp: true, - }) -``` - -#### Logging Method Name - -If you wish to add the calling method as a field, instruct the logger via: -```go -log.SetReportCaller(true) -``` -This adds the caller as 'method' like so: - -```json -{"animal":"penguin","level":"fatal","method":"github.com/sirupsen/arcticcreatures.migrate","msg":"a penguin swims by", -"time":"2014-03-10 19:57:38.562543129 -0400 EDT"} -``` - -```text -time="2015-03-26T01:27:38-04:00" level=fatal method=github.com/sirupsen/arcticcreatures.migrate msg="a penguin swims by" animal=penguin -``` -Note that this does add measurable overhead - the cost will depend on the version of Go, but is -between 20 and 40% in recent tests with 1.6 and 1.7. You can validate this in your -environment via benchmarks: -``` -go test -bench=.*CallerTracing -``` - - -#### Case-sensitivity - -The organization's name was changed to lower-case--and this will not be changed -back. If you are getting import conflicts due to case sensitivity, please use -the lower-case import: `github.com/sirupsen/logrus`. - -#### Example - -The simplest way to use Logrus is simply the package-level exported logger: - -```go -package main - -import ( - log "github.com/sirupsen/logrus" -) - -func main() { - log.WithFields(log.Fields{ - "animal": "walrus", - }).Info("A walrus appears") -} -``` - -Note that it's completely api-compatible with the stdlib logger, so you can -replace your `log` imports everywhere with `log "github.com/sirupsen/logrus"` -and you'll now have the flexibility of Logrus. You can customize it all you -want: - -```go -package main - -import ( - "os" - log "github.com/sirupsen/logrus" -) - -func init() { - // Log as JSON instead of the default ASCII formatter. - log.SetFormatter(&log.JSONFormatter{}) - - // Output to stdout instead of the default stderr - // Can be any io.Writer, see below for File example - log.SetOutput(os.Stdout) - - // Only log the warning severity or above. - log.SetLevel(log.WarnLevel) -} - -func main() { - log.WithFields(log.Fields{ - "animal": "walrus", - "size": 10, - }).Info("A group of walrus emerges from the ocean") - - log.WithFields(log.Fields{ - "omg": true, - "number": 122, - }).Warn("The group's number increased tremendously!") - - log.WithFields(log.Fields{ - "omg": true, - "number": 100, - }).Fatal("The ice breaks!") - - // A common pattern is to re-use fields between logging statements by re-using - // the logrus.Entry returned from WithFields() - contextLogger := log.WithFields(log.Fields{ - "common": "this is a common field", - "other": "I also should be logged always", - }) - - contextLogger.Info("I'll be logged with common and other field") - contextLogger.Info("Me too") -} -``` - -For more advanced usage such as logging to multiple locations from the same -application, you can also create an instance of the `logrus` Logger: - -```go -package main - -import ( - "os" - "github.com/sirupsen/logrus" -) - -// Create a new instance of the logger. You can have any number of instances. -var log = logrus.New() - -func main() { - // The API for setting attributes is a little different than the package level - // exported logger. See Godoc. - log.Out = os.Stdout - - // You could set this to any `io.Writer` such as a file - // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) - // if err == nil { - // log.Out = file - // } else { - // log.Info("Failed to log to file, using default stderr") - // } - - log.WithFields(logrus.Fields{ - "animal": "walrus", - "size": 10, - }).Info("A group of walrus emerges from the ocean") -} -``` - -#### Fields - -Logrus encourages careful, structured logging through logging fields instead of -long, unparseable error messages. For example, instead of: `log.Fatalf("Failed -to send event %s to topic %s with key %d")`, you should log the much more -discoverable: - -```go -log.WithFields(log.Fields{ - "event": event, - "topic": topic, - "key": key, -}).Fatal("Failed to send event") -``` - -We've found this API forces you to think about logging in a way that produces -much more useful logging messages. We've been in countless situations where just -a single added field to a log statement that was already there would've saved us -hours. The `WithFields` call is optional. - -In general, with Logrus using any of the `printf`-family functions should be -seen as a hint you should add a field, however, you can still use the -`printf`-family functions with Logrus. - -#### Default Fields - -Often it's helpful to have fields _always_ attached to log statements in an -application or parts of one. For example, you may want to always log the -`request_id` and `user_ip` in the context of a request. Instead of writing -`log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})` on -every line, you can create a `logrus.Entry` to pass around instead: - -```go -requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip}) -requestLogger.Info("something happened on that request") # will log request_id and user_ip -requestLogger.Warn("something not great happened") -``` - -#### Hooks - -You can add hooks for logging levels. For example to send errors to an exception -tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to -multiple places simultaneously, e.g. syslog. - -Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in -`init`: - -```go -import ( - log "github.com/sirupsen/logrus" - "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "airbrake" - logrus_syslog "github.com/sirupsen/logrus/hooks/syslog" - "log/syslog" -) - -func init() { - - // Use the Airbrake hook to report errors that have Error severity or above to - // an exception tracker. You can create custom hooks, see the Hooks section. - log.AddHook(airbrake.NewHook(123, "xyz", "production")) - - hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") - if err != nil { - log.Error("Unable to connect to local syslog daemon") - } else { - log.AddHook(hook) - } -} -``` -Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md). - -A list of currently known service hooks can be found in this wiki [page](https://github.com/sirupsen/logrus/wiki/Hooks) - - -#### Level logging - -Logrus has seven logging levels: Trace, Debug, Info, Warning, Error, Fatal and Panic. - -```go -log.Trace("Something very low level.") -log.Debug("Useful debugging information.") -log.Info("Something noteworthy happened!") -log.Warn("You should probably take a look at this.") -log.Error("Something failed but I'm not quitting.") -// Calls os.Exit(1) after logging -log.Fatal("Bye.") -// Calls panic() after logging -log.Panic("I'm bailing.") -``` - -You can set the logging level on a `Logger`, then it will only log entries with -that severity or anything above it: - -```go -// Will log anything that is info or above (warn, error, fatal, panic). Default. -log.SetLevel(log.InfoLevel) -``` - -It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose -environment if your application has that. - -Note: If you want different log levels for global (`log.SetLevel(...)`) and syslog logging, please check the [syslog hook README](hooks/syslog/README.md#different-log-levels-for-local-and-remote-logging). - -#### Entries - -Besides the fields added with `WithField` or `WithFields` some fields are -automatically added to all logging events: - -1. `time`. The timestamp when the entry was created. -2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after - the `AddFields` call. E.g. `Failed to send event.` -3. `level`. The logging level. E.g. `info`. - -#### Environments - -Logrus has no notion of environment. - -If you wish for hooks and formatters to only be used in specific environments, -you should handle that yourself. For example, if your application has a global -variable `Environment`, which is a string representation of the environment you -could do: - -```go -import ( - log "github.com/sirupsen/logrus" -) - -func init() { - // do something here to set environment depending on an environment variable - // or command-line flag - if Environment == "production" { - log.SetFormatter(&log.JSONFormatter{}) - } else { - // The TextFormatter is default, you don't actually have to do this. - log.SetFormatter(&log.TextFormatter{}) - } -} -``` - -This configuration is how `logrus` was intended to be used, but JSON in -production is mostly only useful if you do log aggregation with tools like -Splunk or Logstash. - -#### Formatters - -The built-in logging formatters are: - -* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise - without colors. - * *Note:* to force colored output when there is no TTY, set the `ForceColors` - field to `true`. To force no colored output even if there is a TTY set the - `DisableColors` field to `true`. For Windows, see - [github.com/mattn/go-colorable](https://github.com/mattn/go-colorable). - * When colors are enabled, levels are truncated to 4 characters by default. To disable - truncation set the `DisableLevelTruncation` field to `true`. - * When outputting to a TTY, it's often helpful to visually scan down a column where all the levels are the same width. Setting the `PadLevelText` field to `true` enables this behavior, by adding padding to the level text. - * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter). -* `logrus.JSONFormatter`. Logs fields as JSON. - * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter). - -Third party logging formatters: - -* [`FluentdFormatter`](https://github.com/joonix/log). Formats entries that can be parsed by Kubernetes and Google Container Engine. -* [`GELF`](https://github.com/fabienm/go-logrus-formatters). Formats entries so they comply to Graylog's [GELF 1.1 specification](http://docs.graylog.org/en/2.4/pages/gelf.html). -* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events. -* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout. -* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the Power of Zalgo. -* [`nested-logrus-formatter`](https://github.com/antonfisher/nested-logrus-formatter). Converts logrus fields to a nested structure. -* [`powerful-logrus-formatter`](https://github.com/zput/zxcTool). get fileName, log's line number and the latest function's name when print log; Sava log to files. -* [`caption-json-formatter`](https://github.com/nolleh/caption_json_formatter). logrus's message json formatter with human-readable caption added. - -You can define your formatter by implementing the `Formatter` interface, -requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a -`Fields` type (`map[string]interface{}`) with all your fields as well as the -default ones (see Entries section above): - -```go -type MyJSONFormatter struct { -} - -log.SetFormatter(new(MyJSONFormatter)) - -func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) { - // Note this doesn't include Time, Level and Message which are available on - // the Entry. Consult `godoc` on information about those fields or read the - // source of the official loggers. - serialized, err := json.Marshal(entry.Data) - if err != nil { - return nil, fmt.Errorf("Failed to marshal fields to JSON, %w", err) - } - return append(serialized, '\n'), nil -} -``` - -#### Logger as an `io.Writer` - -Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it. - -```go -w := logger.Writer() -defer w.Close() - -srv := http.Server{ - // create a stdlib log.Logger that writes to - // logrus.Logger. - ErrorLog: log.New(w, "", 0), -} -``` - -Each line written to that writer will be printed the usual way, using formatters -and hooks. The level for those entries is `info`. - -This means that we can override the standard library logger easily: - -```go -logger := logrus.New() -logger.Formatter = &logrus.JSONFormatter{} - -// Use logrus for standard log output -// Note that `log` here references stdlib's log -// Not logrus imported under the name `log`. -log.SetOutput(logger.Writer()) -``` - -#### Rotation - -Log rotation is not provided with Logrus. Log rotation should be done by an -external program (like `logrotate(8)`) that can compress and delete old log -entries. It should not be a feature of the application-level logger. - -#### Tools - -| Tool | Description | -| ---- | ----------- | -|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will be generated with different configs in different environments.| -|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) | - -#### Testing - -Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides: - -* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just adds the `test` hook -* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any): - -```go -import( - "github.com/sirupsen/logrus" - "github.com/sirupsen/logrus/hooks/test" - "github.com/stretchr/testify/assert" - "testing" -) - -func TestSomething(t*testing.T){ - logger, hook := test.NewNullLogger() - logger.Error("Helloerror") - - assert.Equal(t, 1, len(hook.Entries)) - assert.Equal(t, logrus.ErrorLevel, hook.LastEntry().Level) - assert.Equal(t, "Helloerror", hook.LastEntry().Message) - - hook.Reset() - assert.Nil(t, hook.LastEntry()) -} -``` - -#### Fatal handlers - -Logrus can register one or more functions that will be called when any `fatal` -level message is logged. The registered handlers will be executed before -logrus performs an `os.Exit(1)`. This behavior may be helpful if callers need -to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted. - -``` -... -handler := func() { - // gracefully shutdown something... -} -logrus.RegisterExitHandler(handler) -... -``` - -#### Thread safety - -By default, Logger is protected by a mutex for concurrent writes. The mutex is held when calling hooks and writing logs. -If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking. - -Situation when locking is not needed includes: - -* You have no hooks registered, or hooks calling is already thread-safe. - -* Writing to logger.Out is already thread-safe, for example: - - 1) logger.Out is protected by locks. - - 2) logger.Out is an os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allows multi-thread/multi-process writing) - - (Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/) diff --git a/vendor/github.com/sirupsen/logrus/alt_exit.go b/vendor/github.com/sirupsen/logrus/alt_exit.go deleted file mode 100644 index 8fd189e1c..000000000 --- a/vendor/github.com/sirupsen/logrus/alt_exit.go +++ /dev/null @@ -1,76 +0,0 @@ -package logrus - -// The following code was sourced and modified from the -// https://github.com/tebeka/atexit package governed by the following license: -// -// Copyright (c) 2012 Miki Tebeka . -// -// 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. - -import ( - "fmt" - "os" -) - -var handlers = []func(){} - -func runHandler(handler func()) { - defer func() { - if err := recover(); err != nil { - fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err) - } - }() - - handler() -} - -func runHandlers() { - for _, handler := range handlers { - runHandler(handler) - } -} - -// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code) -func Exit(code int) { - runHandlers() - os.Exit(code) -} - -// RegisterExitHandler appends a Logrus Exit handler to the list of handlers, -// call logrus.Exit to invoke all handlers. The handlers will also be invoked when -// any Fatal log entry is made. -// -// This method is useful when a caller wishes to use logrus to log a fatal -// message but also needs to gracefully shutdown. An example usecase could be -// closing database connections, or sending a alert that the application is -// closing. -func RegisterExitHandler(handler func()) { - handlers = append(handlers, handler) -} - -// DeferExitHandler prepends a Logrus Exit handler to the list of handlers, -// call logrus.Exit to invoke all handlers. The handlers will also be invoked when -// any Fatal log entry is made. -// -// This method is useful when a caller wishes to use logrus to log a fatal -// message but also needs to gracefully shutdown. An example usecase could be -// closing database connections, or sending a alert that the application is -// closing. -func DeferExitHandler(handler func()) { - handlers = append([]func(){handler}, handlers...) -} diff --git a/vendor/github.com/sirupsen/logrus/appveyor.yml b/vendor/github.com/sirupsen/logrus/appveyor.yml deleted file mode 100644 index df9d65c3a..000000000 --- a/vendor/github.com/sirupsen/logrus/appveyor.yml +++ /dev/null @@ -1,14 +0,0 @@ -version: "{build}" -platform: x64 -clone_folder: c:\gopath\src\github.com\sirupsen\logrus -environment: - GOPATH: c:\gopath -branches: - only: - - master -install: - - set PATH=%GOPATH%\bin;c:\go\bin;%PATH% - - go version -build_script: - - go get -t - - go test diff --git a/vendor/github.com/sirupsen/logrus/buffer_pool.go b/vendor/github.com/sirupsen/logrus/buffer_pool.go deleted file mode 100644 index c7787f77c..000000000 --- a/vendor/github.com/sirupsen/logrus/buffer_pool.go +++ /dev/null @@ -1,43 +0,0 @@ -package logrus - -import ( - "bytes" - "sync" -) - -var ( - bufferPool BufferPool -) - -type BufferPool interface { - Put(*bytes.Buffer) - Get() *bytes.Buffer -} - -type defaultPool struct { - pool *sync.Pool -} - -func (p *defaultPool) Put(buf *bytes.Buffer) { - p.pool.Put(buf) -} - -func (p *defaultPool) Get() *bytes.Buffer { - return p.pool.Get().(*bytes.Buffer) -} - -// SetBufferPool allows to replace the default logrus buffer pool -// to better meets the specific needs of an application. -func SetBufferPool(bp BufferPool) { - bufferPool = bp -} - -func init() { - SetBufferPool(&defaultPool{ - pool: &sync.Pool{ - New: func() interface{} { - return new(bytes.Buffer) - }, - }, - }) -} diff --git a/vendor/github.com/sirupsen/logrus/doc.go b/vendor/github.com/sirupsen/logrus/doc.go deleted file mode 100644 index da67aba06..000000000 --- a/vendor/github.com/sirupsen/logrus/doc.go +++ /dev/null @@ -1,26 +0,0 @@ -/* -Package logrus is a structured logger for Go, completely API compatible with the standard library logger. - - -The simplest way to use Logrus is simply the package-level exported logger: - - package main - - import ( - log "github.com/sirupsen/logrus" - ) - - func main() { - log.WithFields(log.Fields{ - "animal": "walrus", - "number": 1, - "size": 10, - }).Info("A walrus appears") - } - -Output: - time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10 - -For a full guide visit https://github.com/sirupsen/logrus -*/ -package logrus diff --git a/vendor/github.com/sirupsen/logrus/entry.go b/vendor/github.com/sirupsen/logrus/entry.go deleted file mode 100644 index 71cdbbc35..000000000 --- a/vendor/github.com/sirupsen/logrus/entry.go +++ /dev/null @@ -1,442 +0,0 @@ -package logrus - -import ( - "bytes" - "context" - "fmt" - "os" - "reflect" - "runtime" - "strings" - "sync" - "time" -) - -var ( - - // qualified package name, cached at first use - logrusPackage string - - // Positions in the call stack when tracing to report the calling method - minimumCallerDepth int - - // Used for caller information initialisation - callerInitOnce sync.Once -) - -const ( - maximumCallerDepth int = 25 - knownLogrusFrames int = 4 -) - -func init() { - // start at the bottom of the stack before the package-name cache is primed - minimumCallerDepth = 1 -} - -// Defines the key when adding errors using WithError. -var ErrorKey = "error" - -// An entry is the final or intermediate Logrus logging entry. It contains all -// the fields passed with WithField{,s}. It's finally logged when Trace, Debug, -// Info, Warn, Error, Fatal or Panic is called on it. These objects can be -// reused and passed around as much as you wish to avoid field duplication. -type Entry struct { - Logger *Logger - - // Contains all the fields set by the user. - Data Fields - - // Time at which the log entry was created - Time time.Time - - // Level the log entry was logged at: Trace, Debug, Info, Warn, Error, Fatal or Panic - // This field will be set on entry firing and the value will be equal to the one in Logger struct field. - Level Level - - // Calling method, with package name - Caller *runtime.Frame - - // Message passed to Trace, Debug, Info, Warn, Error, Fatal or Panic - Message string - - // When formatter is called in entry.log(), a Buffer may be set to entry - Buffer *bytes.Buffer - - // Contains the context set by the user. Useful for hook processing etc. - Context context.Context - - // err may contain a field formatting error - err string -} - -func NewEntry(logger *Logger) *Entry { - return &Entry{ - Logger: logger, - // Default is three fields, plus one optional. Give a little extra room. - Data: make(Fields, 6), - } -} - -func (entry *Entry) Dup() *Entry { - data := make(Fields, len(entry.Data)) - for k, v := range entry.Data { - data[k] = v - } - return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, Context: entry.Context, err: entry.err} -} - -// Returns the bytes representation of this entry from the formatter. -func (entry *Entry) Bytes() ([]byte, error) { - return entry.Logger.Formatter.Format(entry) -} - -// Returns the string representation from the reader and ultimately the -// formatter. -func (entry *Entry) String() (string, error) { - serialized, err := entry.Bytes() - if err != nil { - return "", err - } - str := string(serialized) - return str, nil -} - -// Add an error as single field (using the key defined in ErrorKey) to the Entry. -func (entry *Entry) WithError(err error) *Entry { - return entry.WithField(ErrorKey, err) -} - -// Add a context to the Entry. -func (entry *Entry) WithContext(ctx context.Context) *Entry { - dataCopy := make(Fields, len(entry.Data)) - for k, v := range entry.Data { - dataCopy[k] = v - } - return &Entry{Logger: entry.Logger, Data: dataCopy, Time: entry.Time, err: entry.err, Context: ctx} -} - -// Add a single field to the Entry. -func (entry *Entry) WithField(key string, value interface{}) *Entry { - return entry.WithFields(Fields{key: value}) -} - -// Add a map of fields to the Entry. -func (entry *Entry) WithFields(fields Fields) *Entry { - data := make(Fields, len(entry.Data)+len(fields)) - for k, v := range entry.Data { - data[k] = v - } - fieldErr := entry.err - for k, v := range fields { - isErrField := false - if t := reflect.TypeOf(v); t != nil { - switch { - case t.Kind() == reflect.Func, t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Func: - isErrField = true - } - } - if isErrField { - tmp := fmt.Sprintf("can not add field %q", k) - if fieldErr != "" { - fieldErr = entry.err + ", " + tmp - } else { - fieldErr = tmp - } - } else { - data[k] = v - } - } - return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: fieldErr, Context: entry.Context} -} - -// Overrides the time of the Entry. -func (entry *Entry) WithTime(t time.Time) *Entry { - dataCopy := make(Fields, len(entry.Data)) - for k, v := range entry.Data { - dataCopy[k] = v - } - return &Entry{Logger: entry.Logger, Data: dataCopy, Time: t, err: entry.err, Context: entry.Context} -} - -// getPackageName reduces a fully qualified function name to the package name -// There really ought to be to be a better way... -func getPackageName(f string) string { - for { - lastPeriod := strings.LastIndex(f, ".") - lastSlash := strings.LastIndex(f, "/") - if lastPeriod > lastSlash { - f = f[:lastPeriod] - } else { - break - } - } - - return f -} - -// getCaller retrieves the name of the first non-logrus calling function -func getCaller() *runtime.Frame { - // cache this package's fully-qualified name - callerInitOnce.Do(func() { - pcs := make([]uintptr, maximumCallerDepth) - _ = runtime.Callers(0, pcs) - - // dynamic get the package name and the minimum caller depth - for i := 0; i < maximumCallerDepth; i++ { - funcName := runtime.FuncForPC(pcs[i]).Name() - if strings.Contains(funcName, "getCaller") { - logrusPackage = getPackageName(funcName) - break - } - } - - minimumCallerDepth = knownLogrusFrames - }) - - // Restrict the lookback frames to avoid runaway lookups - pcs := make([]uintptr, maximumCallerDepth) - depth := runtime.Callers(minimumCallerDepth, pcs) - frames := runtime.CallersFrames(pcs[:depth]) - - for f, again := frames.Next(); again; f, again = frames.Next() { - pkg := getPackageName(f.Function) - - // If the caller isn't part of this package, we're done - if pkg != logrusPackage { - return &f //nolint:scopelint - } - } - - // if we got here, we failed to find the caller's context - return nil -} - -func (entry Entry) HasCaller() (has bool) { - return entry.Logger != nil && - entry.Logger.ReportCaller && - entry.Caller != nil -} - -func (entry *Entry) log(level Level, msg string) { - var buffer *bytes.Buffer - - newEntry := entry.Dup() - - if newEntry.Time.IsZero() { - newEntry.Time = time.Now() - } - - newEntry.Level = level - newEntry.Message = msg - - newEntry.Logger.mu.Lock() - reportCaller := newEntry.Logger.ReportCaller - bufPool := newEntry.getBufferPool() - newEntry.Logger.mu.Unlock() - - if reportCaller { - newEntry.Caller = getCaller() - } - - newEntry.fireHooks() - buffer = bufPool.Get() - defer func() { - newEntry.Buffer = nil - buffer.Reset() - bufPool.Put(buffer) - }() - buffer.Reset() - newEntry.Buffer = buffer - - newEntry.write() - - newEntry.Buffer = nil - - // To avoid Entry#log() returning a value that only would make sense for - // panic() to use in Entry#Panic(), we avoid the allocation by checking - // directly here. - if level <= PanicLevel { - panic(newEntry) - } -} - -func (entry *Entry) getBufferPool() (pool BufferPool) { - if entry.Logger.BufferPool != nil { - return entry.Logger.BufferPool - } - return bufferPool -} - -func (entry *Entry) fireHooks() { - var tmpHooks LevelHooks - entry.Logger.mu.Lock() - tmpHooks = make(LevelHooks, len(entry.Logger.Hooks)) - for k, v := range entry.Logger.Hooks { - tmpHooks[k] = v - } - entry.Logger.mu.Unlock() - - err := tmpHooks.Fire(entry.Level, entry) - if err != nil { - fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err) - } -} - -func (entry *Entry) write() { - entry.Logger.mu.Lock() - defer entry.Logger.mu.Unlock() - serialized, err := entry.Logger.Formatter.Format(entry) - if err != nil { - fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err) - return - } - if _, err := entry.Logger.Out.Write(serialized); err != nil { - fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err) - } -} - -// Log will log a message at the level given as parameter. -// Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit. -// For this behaviour Entry.Panic or Entry.Fatal should be used instead. -func (entry *Entry) Log(level Level, args ...interface{}) { - if entry.Logger.IsLevelEnabled(level) { - entry.log(level, fmt.Sprint(args...)) - } -} - -func (entry *Entry) Trace(args ...interface{}) { - entry.Log(TraceLevel, args...) -} - -func (entry *Entry) Debug(args ...interface{}) { - entry.Log(DebugLevel, args...) -} - -func (entry *Entry) Print(args ...interface{}) { - entry.Info(args...) -} - -func (entry *Entry) Info(args ...interface{}) { - entry.Log(InfoLevel, args...) -} - -func (entry *Entry) Warn(args ...interface{}) { - entry.Log(WarnLevel, args...) -} - -func (entry *Entry) Warning(args ...interface{}) { - entry.Warn(args...) -} - -func (entry *Entry) Error(args ...interface{}) { - entry.Log(ErrorLevel, args...) -} - -func (entry *Entry) Fatal(args ...interface{}) { - entry.Log(FatalLevel, args...) - entry.Logger.Exit(1) -} - -func (entry *Entry) Panic(args ...interface{}) { - entry.Log(PanicLevel, args...) -} - -// Entry Printf family functions - -func (entry *Entry) Logf(level Level, format string, args ...interface{}) { - if entry.Logger.IsLevelEnabled(level) { - entry.Log(level, fmt.Sprintf(format, args...)) - } -} - -func (entry *Entry) Tracef(format string, args ...interface{}) { - entry.Logf(TraceLevel, format, args...) -} - -func (entry *Entry) Debugf(format string, args ...interface{}) { - entry.Logf(DebugLevel, format, args...) -} - -func (entry *Entry) Infof(format string, args ...interface{}) { - entry.Logf(InfoLevel, format, args...) -} - -func (entry *Entry) Printf(format string, args ...interface{}) { - entry.Infof(format, args...) -} - -func (entry *Entry) Warnf(format string, args ...interface{}) { - entry.Logf(WarnLevel, format, args...) -} - -func (entry *Entry) Warningf(format string, args ...interface{}) { - entry.Warnf(format, args...) -} - -func (entry *Entry) Errorf(format string, args ...interface{}) { - entry.Logf(ErrorLevel, format, args...) -} - -func (entry *Entry) Fatalf(format string, args ...interface{}) { - entry.Logf(FatalLevel, format, args...) - entry.Logger.Exit(1) -} - -func (entry *Entry) Panicf(format string, args ...interface{}) { - entry.Logf(PanicLevel, format, args...) -} - -// Entry Println family functions - -func (entry *Entry) Logln(level Level, args ...interface{}) { - if entry.Logger.IsLevelEnabled(level) { - entry.Log(level, entry.sprintlnn(args...)) - } -} - -func (entry *Entry) Traceln(args ...interface{}) { - entry.Logln(TraceLevel, args...) -} - -func (entry *Entry) Debugln(args ...interface{}) { - entry.Logln(DebugLevel, args...) -} - -func (entry *Entry) Infoln(args ...interface{}) { - entry.Logln(InfoLevel, args...) -} - -func (entry *Entry) Println(args ...interface{}) { - entry.Infoln(args...) -} - -func (entry *Entry) Warnln(args ...interface{}) { - entry.Logln(WarnLevel, args...) -} - -func (entry *Entry) Warningln(args ...interface{}) { - entry.Warnln(args...) -} - -func (entry *Entry) Errorln(args ...interface{}) { - entry.Logln(ErrorLevel, args...) -} - -func (entry *Entry) Fatalln(args ...interface{}) { - entry.Logln(FatalLevel, args...) - entry.Logger.Exit(1) -} - -func (entry *Entry) Panicln(args ...interface{}) { - entry.Logln(PanicLevel, args...) -} - -// Sprintlnn => Sprint no newline. This is to get the behavior of how -// fmt.Sprintln where spaces are always added between operands, regardless of -// their type. Instead of vendoring the Sprintln implementation to spare a -// string allocation, we do the simplest thing. -func (entry *Entry) sprintlnn(args ...interface{}) string { - msg := fmt.Sprintln(args...) - return msg[:len(msg)-1] -} diff --git a/vendor/github.com/sirupsen/logrus/exported.go b/vendor/github.com/sirupsen/logrus/exported.go deleted file mode 100644 index 017c30ce6..000000000 --- a/vendor/github.com/sirupsen/logrus/exported.go +++ /dev/null @@ -1,270 +0,0 @@ -package logrus - -import ( - "context" - "io" - "time" -) - -var ( - // std is the name of the standard logger in stdlib `log` - std = New() -) - -func StandardLogger() *Logger { - return std -} - -// SetOutput sets the standard logger output. -func SetOutput(out io.Writer) { - std.SetOutput(out) -} - -// SetFormatter sets the standard logger formatter. -func SetFormatter(formatter Formatter) { - std.SetFormatter(formatter) -} - -// SetReportCaller sets whether the standard logger will include the calling -// method as a field. -func SetReportCaller(include bool) { - std.SetReportCaller(include) -} - -// SetLevel sets the standard logger level. -func SetLevel(level Level) { - std.SetLevel(level) -} - -// GetLevel returns the standard logger level. -func GetLevel() Level { - return std.GetLevel() -} - -// IsLevelEnabled checks if the log level of the standard logger is greater than the level param -func IsLevelEnabled(level Level) bool { - return std.IsLevelEnabled(level) -} - -// AddHook adds a hook to the standard logger hooks. -func AddHook(hook Hook) { - std.AddHook(hook) -} - -// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key. -func WithError(err error) *Entry { - return std.WithField(ErrorKey, err) -} - -// WithContext creates an entry from the standard logger and adds a context to it. -func WithContext(ctx context.Context) *Entry { - return std.WithContext(ctx) -} - -// WithField creates an entry from the standard logger and adds a field to -// it. If you want multiple fields, use `WithFields`. -// -// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal -// or Panic on the Entry it returns. -func WithField(key string, value interface{}) *Entry { - return std.WithField(key, value) -} - -// WithFields creates an entry from the standard logger and adds multiple -// fields to it. This is simply a helper for `WithField`, invoking it -// once for each field. -// -// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal -// or Panic on the Entry it returns. -func WithFields(fields Fields) *Entry { - return std.WithFields(fields) -} - -// WithTime creates an entry from the standard logger and overrides the time of -// logs generated with it. -// -// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal -// or Panic on the Entry it returns. -func WithTime(t time.Time) *Entry { - return std.WithTime(t) -} - -// Trace logs a message at level Trace on the standard logger. -func Trace(args ...interface{}) { - std.Trace(args...) -} - -// Debug logs a message at level Debug on the standard logger. -func Debug(args ...interface{}) { - std.Debug(args...) -} - -// Print logs a message at level Info on the standard logger. -func Print(args ...interface{}) { - std.Print(args...) -} - -// Info logs a message at level Info on the standard logger. -func Info(args ...interface{}) { - std.Info(args...) -} - -// Warn logs a message at level Warn on the standard logger. -func Warn(args ...interface{}) { - std.Warn(args...) -} - -// Warning logs a message at level Warn on the standard logger. -func Warning(args ...interface{}) { - std.Warning(args...) -} - -// Error logs a message at level Error on the standard logger. -func Error(args ...interface{}) { - std.Error(args...) -} - -// Panic logs a message at level Panic on the standard logger. -func Panic(args ...interface{}) { - std.Panic(args...) -} - -// Fatal logs a message at level Fatal on the standard logger then the process will exit with status set to 1. -func Fatal(args ...interface{}) { - std.Fatal(args...) -} - -// TraceFn logs a message from a func at level Trace on the standard logger. -func TraceFn(fn LogFunction) { - std.TraceFn(fn) -} - -// DebugFn logs a message from a func at level Debug on the standard logger. -func DebugFn(fn LogFunction) { - std.DebugFn(fn) -} - -// PrintFn logs a message from a func at level Info on the standard logger. -func PrintFn(fn LogFunction) { - std.PrintFn(fn) -} - -// InfoFn logs a message from a func at level Info on the standard logger. -func InfoFn(fn LogFunction) { - std.InfoFn(fn) -} - -// WarnFn logs a message from a func at level Warn on the standard logger. -func WarnFn(fn LogFunction) { - std.WarnFn(fn) -} - -// WarningFn logs a message from a func at level Warn on the standard logger. -func WarningFn(fn LogFunction) { - std.WarningFn(fn) -} - -// ErrorFn logs a message from a func at level Error on the standard logger. -func ErrorFn(fn LogFunction) { - std.ErrorFn(fn) -} - -// PanicFn logs a message from a func at level Panic on the standard logger. -func PanicFn(fn LogFunction) { - std.PanicFn(fn) -} - -// FatalFn logs a message from a func at level Fatal on the standard logger then the process will exit with status set to 1. -func FatalFn(fn LogFunction) { - std.FatalFn(fn) -} - -// Tracef logs a message at level Trace on the standard logger. -func Tracef(format string, args ...interface{}) { - std.Tracef(format, args...) -} - -// Debugf logs a message at level Debug on the standard logger. -func Debugf(format string, args ...interface{}) { - std.Debugf(format, args...) -} - -// Printf logs a message at level Info on the standard logger. -func Printf(format string, args ...interface{}) { - std.Printf(format, args...) -} - -// Infof logs a message at level Info on the standard logger. -func Infof(format string, args ...interface{}) { - std.Infof(format, args...) -} - -// Warnf logs a message at level Warn on the standard logger. -func Warnf(format string, args ...interface{}) { - std.Warnf(format, args...) -} - -// Warningf logs a message at level Warn on the standard logger. -func Warningf(format string, args ...interface{}) { - std.Warningf(format, args...) -} - -// Errorf logs a message at level Error on the standard logger. -func Errorf(format string, args ...interface{}) { - std.Errorf(format, args...) -} - -// Panicf logs a message at level Panic on the standard logger. -func Panicf(format string, args ...interface{}) { - std.Panicf(format, args...) -} - -// Fatalf logs a message at level Fatal on the standard logger then the process will exit with status set to 1. -func Fatalf(format string, args ...interface{}) { - std.Fatalf(format, args...) -} - -// Traceln logs a message at level Trace on the standard logger. -func Traceln(args ...interface{}) { - std.Traceln(args...) -} - -// Debugln logs a message at level Debug on the standard logger. -func Debugln(args ...interface{}) { - std.Debugln(args...) -} - -// Println logs a message at level Info on the standard logger. -func Println(args ...interface{}) { - std.Println(args...) -} - -// Infoln logs a message at level Info on the standard logger. -func Infoln(args ...interface{}) { - std.Infoln(args...) -} - -// Warnln logs a message at level Warn on the standard logger. -func Warnln(args ...interface{}) { - std.Warnln(args...) -} - -// Warningln logs a message at level Warn on the standard logger. -func Warningln(args ...interface{}) { - std.Warningln(args...) -} - -// Errorln logs a message at level Error on the standard logger. -func Errorln(args ...interface{}) { - std.Errorln(args...) -} - -// Panicln logs a message at level Panic on the standard logger. -func Panicln(args ...interface{}) { - std.Panicln(args...) -} - -// Fatalln logs a message at level Fatal on the standard logger then the process will exit with status set to 1. -func Fatalln(args ...interface{}) { - std.Fatalln(args...) -} diff --git a/vendor/github.com/sirupsen/logrus/formatter.go b/vendor/github.com/sirupsen/logrus/formatter.go deleted file mode 100644 index 408883773..000000000 --- a/vendor/github.com/sirupsen/logrus/formatter.go +++ /dev/null @@ -1,78 +0,0 @@ -package logrus - -import "time" - -// Default key names for the default fields -const ( - defaultTimestampFormat = time.RFC3339 - FieldKeyMsg = "msg" - FieldKeyLevel = "level" - FieldKeyTime = "time" - FieldKeyLogrusError = "logrus_error" - FieldKeyFunc = "func" - FieldKeyFile = "file" -) - -// The Formatter interface is used to implement a custom Formatter. It takes an -// `Entry`. It exposes all the fields, including the default ones: -// -// * `entry.Data["msg"]`. The message passed from Info, Warn, Error .. -// * `entry.Data["time"]`. The timestamp. -// * `entry.Data["level"]. The level the entry was logged at. -// -// Any additional fields added with `WithField` or `WithFields` are also in -// `entry.Data`. Format is expected to return an array of bytes which are then -// logged to `logger.Out`. -type Formatter interface { - Format(*Entry) ([]byte, error) -} - -// This is to not silently overwrite `time`, `msg`, `func` and `level` fields when -// dumping it. If this code wasn't there doing: -// -// logrus.WithField("level", 1).Info("hello") -// -// Would just silently drop the user provided level. Instead with this code -// it'll logged as: -// -// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."} -// -// It's not exported because it's still using Data in an opinionated way. It's to -// avoid code duplication between the two default formatters. -func prefixFieldClashes(data Fields, fieldMap FieldMap, reportCaller bool) { - timeKey := fieldMap.resolve(FieldKeyTime) - if t, ok := data[timeKey]; ok { - data["fields."+timeKey] = t - delete(data, timeKey) - } - - msgKey := fieldMap.resolve(FieldKeyMsg) - if m, ok := data[msgKey]; ok { - data["fields."+msgKey] = m - delete(data, msgKey) - } - - levelKey := fieldMap.resolve(FieldKeyLevel) - if l, ok := data[levelKey]; ok { - data["fields."+levelKey] = l - delete(data, levelKey) - } - - logrusErrKey := fieldMap.resolve(FieldKeyLogrusError) - if l, ok := data[logrusErrKey]; ok { - data["fields."+logrusErrKey] = l - delete(data, logrusErrKey) - } - - // If reportCaller is not set, 'func' will not conflict. - if reportCaller { - funcKey := fieldMap.resolve(FieldKeyFunc) - if l, ok := data[funcKey]; ok { - data["fields."+funcKey] = l - } - fileKey := fieldMap.resolve(FieldKeyFile) - if l, ok := data[fileKey]; ok { - data["fields."+fileKey] = l - } - } -} diff --git a/vendor/github.com/sirupsen/logrus/hooks.go b/vendor/github.com/sirupsen/logrus/hooks.go deleted file mode 100644 index 3f151cdc3..000000000 --- a/vendor/github.com/sirupsen/logrus/hooks.go +++ /dev/null @@ -1,34 +0,0 @@ -package logrus - -// A hook to be fired when logging on the logging levels returned from -// `Levels()` on your implementation of the interface. Note that this is not -// fired in a goroutine or a channel with workers, you should handle such -// functionality yourself if your call is non-blocking and you don't wish for -// the logging calls for levels returned from `Levels()` to block. -type Hook interface { - Levels() []Level - Fire(*Entry) error -} - -// Internal type for storing the hooks on a logger instance. -type LevelHooks map[Level][]Hook - -// Add a hook to an instance of logger. This is called with -// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface. -func (hooks LevelHooks) Add(hook Hook) { - for _, level := range hook.Levels() { - hooks[level] = append(hooks[level], hook) - } -} - -// Fire all the hooks for the passed level. Used by `entry.log` to fire -// appropriate hooks for a log entry. -func (hooks LevelHooks) Fire(level Level, entry *Entry) error { - for _, hook := range hooks[level] { - if err := hook.Fire(entry); err != nil { - return err - } - } - - return nil -} diff --git a/vendor/github.com/sirupsen/logrus/json_formatter.go b/vendor/github.com/sirupsen/logrus/json_formatter.go deleted file mode 100644 index c96dc5636..000000000 --- a/vendor/github.com/sirupsen/logrus/json_formatter.go +++ /dev/null @@ -1,128 +0,0 @@ -package logrus - -import ( - "bytes" - "encoding/json" - "fmt" - "runtime" -) - -type fieldKey string - -// FieldMap allows customization of the key names for default fields. -type FieldMap map[fieldKey]string - -func (f FieldMap) resolve(key fieldKey) string { - if k, ok := f[key]; ok { - return k - } - - return string(key) -} - -// JSONFormatter formats logs into parsable json -type JSONFormatter struct { - // TimestampFormat sets the format used for marshaling timestamps. - // The format to use is the same than for time.Format or time.Parse from the standard - // library. - // The standard Library already provides a set of predefined format. - TimestampFormat string - - // DisableTimestamp allows disabling automatic timestamps in output - DisableTimestamp bool - - // DisableHTMLEscape allows disabling html escaping in output - DisableHTMLEscape bool - - // DataKey allows users to put all the log entry parameters into a nested dictionary at a given key. - DataKey string - - // FieldMap allows users to customize the names of keys for default fields. - // As an example: - // formatter := &JSONFormatter{ - // FieldMap: FieldMap{ - // FieldKeyTime: "@timestamp", - // FieldKeyLevel: "@level", - // FieldKeyMsg: "@message", - // FieldKeyFunc: "@caller", - // }, - // } - FieldMap FieldMap - - // CallerPrettyfier can be set by the user to modify the content - // of the function and file keys in the json data when ReportCaller is - // activated. If any of the returned value is the empty string the - // corresponding key will be removed from json fields. - CallerPrettyfier func(*runtime.Frame) (function string, file string) - - // PrettyPrint will indent all json logs - PrettyPrint bool -} - -// Format renders a single log entry -func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { - data := make(Fields, len(entry.Data)+4) - for k, v := range entry.Data { - switch v := v.(type) { - case error: - // Otherwise errors are ignored by `encoding/json` - // https://github.com/sirupsen/logrus/issues/137 - data[k] = v.Error() - default: - data[k] = v - } - } - - if f.DataKey != "" { - newData := make(Fields, 4) - newData[f.DataKey] = data - data = newData - } - - prefixFieldClashes(data, f.FieldMap, entry.HasCaller()) - - timestampFormat := f.TimestampFormat - if timestampFormat == "" { - timestampFormat = defaultTimestampFormat - } - - if entry.err != "" { - data[f.FieldMap.resolve(FieldKeyLogrusError)] = entry.err - } - if !f.DisableTimestamp { - data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat) - } - data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message - data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String() - if entry.HasCaller() { - funcVal := entry.Caller.Function - fileVal := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line) - if f.CallerPrettyfier != nil { - funcVal, fileVal = f.CallerPrettyfier(entry.Caller) - } - if funcVal != "" { - data[f.FieldMap.resolve(FieldKeyFunc)] = funcVal - } - if fileVal != "" { - data[f.FieldMap.resolve(FieldKeyFile)] = fileVal - } - } - - var b *bytes.Buffer - if entry.Buffer != nil { - b = entry.Buffer - } else { - b = &bytes.Buffer{} - } - - encoder := json.NewEncoder(b) - encoder.SetEscapeHTML(!f.DisableHTMLEscape) - if f.PrettyPrint { - encoder.SetIndent("", " ") - } - if err := encoder.Encode(data); err != nil { - return nil, fmt.Errorf("failed to marshal fields to JSON, %w", err) - } - - return b.Bytes(), nil -} diff --git a/vendor/github.com/sirupsen/logrus/logger.go b/vendor/github.com/sirupsen/logrus/logger.go deleted file mode 100644 index 5ff0aef6d..000000000 --- a/vendor/github.com/sirupsen/logrus/logger.go +++ /dev/null @@ -1,417 +0,0 @@ -package logrus - -import ( - "context" - "io" - "os" - "sync" - "sync/atomic" - "time" -) - -// LogFunction For big messages, it can be more efficient to pass a function -// and only call it if the log level is actually enables rather than -// generating the log message and then checking if the level is enabled -type LogFunction func() []interface{} - -type Logger struct { - // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a - // file, or leave it default which is `os.Stderr`. You can also set this to - // something more adventurous, such as logging to Kafka. - Out io.Writer - // Hooks for the logger instance. These allow firing events based on logging - // levels and log entries. For example, to send errors to an error tracking - // service, log to StatsD or dump the core on fatal errors. - Hooks LevelHooks - // All log entries pass through the formatter before logged to Out. The - // included formatters are `TextFormatter` and `JSONFormatter` for which - // TextFormatter is the default. In development (when a TTY is attached) it - // logs with colors, but to a file it wouldn't. You can easily implement your - // own that implements the `Formatter` interface, see the `README` or included - // formatters for examples. - Formatter Formatter - - // Flag for whether to log caller info (off by default) - ReportCaller bool - - // The logging level the logger should log at. This is typically (and defaults - // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be - // logged. - Level Level - // Used to sync writing to the log. Locking is enabled by Default - mu MutexWrap - // Reusable empty entry - entryPool sync.Pool - // Function to exit the application, defaults to `os.Exit()` - ExitFunc exitFunc - // The buffer pool used to format the log. If it is nil, the default global - // buffer pool will be used. - BufferPool BufferPool -} - -type exitFunc func(int) - -type MutexWrap struct { - lock sync.Mutex - disabled bool -} - -func (mw *MutexWrap) Lock() { - if !mw.disabled { - mw.lock.Lock() - } -} - -func (mw *MutexWrap) Unlock() { - if !mw.disabled { - mw.lock.Unlock() - } -} - -func (mw *MutexWrap) Disable() { - mw.disabled = true -} - -// Creates a new logger. Configuration should be set by changing `Formatter`, -// `Out` and `Hooks` directly on the default logger instance. You can also just -// instantiate your own: -// -// var log = &logrus.Logger{ -// Out: os.Stderr, -// Formatter: new(logrus.TextFormatter), -// Hooks: make(logrus.LevelHooks), -// Level: logrus.DebugLevel, -// } -// -// It's recommended to make this a global instance called `log`. -func New() *Logger { - return &Logger{ - Out: os.Stderr, - Formatter: new(TextFormatter), - Hooks: make(LevelHooks), - Level: InfoLevel, - ExitFunc: os.Exit, - ReportCaller: false, - } -} - -func (logger *Logger) newEntry() *Entry { - entry, ok := logger.entryPool.Get().(*Entry) - if ok { - return entry - } - return NewEntry(logger) -} - -func (logger *Logger) releaseEntry(entry *Entry) { - entry.Data = map[string]interface{}{} - logger.entryPool.Put(entry) -} - -// WithField allocates a new entry and adds a field to it. -// Debug, Print, Info, Warn, Error, Fatal or Panic must be then applied to -// this new returned entry. -// If you want multiple fields, use `WithFields`. -func (logger *Logger) WithField(key string, value interface{}) *Entry { - entry := logger.newEntry() - defer logger.releaseEntry(entry) - return entry.WithField(key, value) -} - -// Adds a struct of fields to the log entry. All it does is call `WithField` for -// each `Field`. -func (logger *Logger) WithFields(fields Fields) *Entry { - entry := logger.newEntry() - defer logger.releaseEntry(entry) - return entry.WithFields(fields) -} - -// Add an error as single field to the log entry. All it does is call -// `WithError` for the given `error`. -func (logger *Logger) WithError(err error) *Entry { - entry := logger.newEntry() - defer logger.releaseEntry(entry) - return entry.WithError(err) -} - -// Add a context to the log entry. -func (logger *Logger) WithContext(ctx context.Context) *Entry { - entry := logger.newEntry() - defer logger.releaseEntry(entry) - return entry.WithContext(ctx) -} - -// Overrides the time of the log entry. -func (logger *Logger) WithTime(t time.Time) *Entry { - entry := logger.newEntry() - defer logger.releaseEntry(entry) - return entry.WithTime(t) -} - -func (logger *Logger) Logf(level Level, format string, args ...interface{}) { - if logger.IsLevelEnabled(level) { - entry := logger.newEntry() - entry.Logf(level, format, args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Tracef(format string, args ...interface{}) { - logger.Logf(TraceLevel, format, args...) -} - -func (logger *Logger) Debugf(format string, args ...interface{}) { - logger.Logf(DebugLevel, format, args...) -} - -func (logger *Logger) Infof(format string, args ...interface{}) { - logger.Logf(InfoLevel, format, args...) -} - -func (logger *Logger) Printf(format string, args ...interface{}) { - entry := logger.newEntry() - entry.Printf(format, args...) - logger.releaseEntry(entry) -} - -func (logger *Logger) Warnf(format string, args ...interface{}) { - logger.Logf(WarnLevel, format, args...) -} - -func (logger *Logger) Warningf(format string, args ...interface{}) { - logger.Warnf(format, args...) -} - -func (logger *Logger) Errorf(format string, args ...interface{}) { - logger.Logf(ErrorLevel, format, args...) -} - -func (logger *Logger) Fatalf(format string, args ...interface{}) { - logger.Logf(FatalLevel, format, args...) - logger.Exit(1) -} - -func (logger *Logger) Panicf(format string, args ...interface{}) { - logger.Logf(PanicLevel, format, args...) -} - -// Log will log a message at the level given as parameter. -// Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit. -// For this behaviour Logger.Panic or Logger.Fatal should be used instead. -func (logger *Logger) Log(level Level, args ...interface{}) { - if logger.IsLevelEnabled(level) { - entry := logger.newEntry() - entry.Log(level, args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) LogFn(level Level, fn LogFunction) { - if logger.IsLevelEnabled(level) { - entry := logger.newEntry() - entry.Log(level, fn()...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Trace(args ...interface{}) { - logger.Log(TraceLevel, args...) -} - -func (logger *Logger) Debug(args ...interface{}) { - logger.Log(DebugLevel, args...) -} - -func (logger *Logger) Info(args ...interface{}) { - logger.Log(InfoLevel, args...) -} - -func (logger *Logger) Print(args ...interface{}) { - entry := logger.newEntry() - entry.Print(args...) - logger.releaseEntry(entry) -} - -func (logger *Logger) Warn(args ...interface{}) { - logger.Log(WarnLevel, args...) -} - -func (logger *Logger) Warning(args ...interface{}) { - logger.Warn(args...) -} - -func (logger *Logger) Error(args ...interface{}) { - logger.Log(ErrorLevel, args...) -} - -func (logger *Logger) Fatal(args ...interface{}) { - logger.Log(FatalLevel, args...) - logger.Exit(1) -} - -func (logger *Logger) Panic(args ...interface{}) { - logger.Log(PanicLevel, args...) -} - -func (logger *Logger) TraceFn(fn LogFunction) { - logger.LogFn(TraceLevel, fn) -} - -func (logger *Logger) DebugFn(fn LogFunction) { - logger.LogFn(DebugLevel, fn) -} - -func (logger *Logger) InfoFn(fn LogFunction) { - logger.LogFn(InfoLevel, fn) -} - -func (logger *Logger) PrintFn(fn LogFunction) { - entry := logger.newEntry() - entry.Print(fn()...) - logger.releaseEntry(entry) -} - -func (logger *Logger) WarnFn(fn LogFunction) { - logger.LogFn(WarnLevel, fn) -} - -func (logger *Logger) WarningFn(fn LogFunction) { - logger.WarnFn(fn) -} - -func (logger *Logger) ErrorFn(fn LogFunction) { - logger.LogFn(ErrorLevel, fn) -} - -func (logger *Logger) FatalFn(fn LogFunction) { - logger.LogFn(FatalLevel, fn) - logger.Exit(1) -} - -func (logger *Logger) PanicFn(fn LogFunction) { - logger.LogFn(PanicLevel, fn) -} - -func (logger *Logger) Logln(level Level, args ...interface{}) { - if logger.IsLevelEnabled(level) { - entry := logger.newEntry() - entry.Logln(level, args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Traceln(args ...interface{}) { - logger.Logln(TraceLevel, args...) -} - -func (logger *Logger) Debugln(args ...interface{}) { - logger.Logln(DebugLevel, args...) -} - -func (logger *Logger) Infoln(args ...interface{}) { - logger.Logln(InfoLevel, args...) -} - -func (logger *Logger) Println(args ...interface{}) { - entry := logger.newEntry() - entry.Println(args...) - logger.releaseEntry(entry) -} - -func (logger *Logger) Warnln(args ...interface{}) { - logger.Logln(WarnLevel, args...) -} - -func (logger *Logger) Warningln(args ...interface{}) { - logger.Warnln(args...) -} - -func (logger *Logger) Errorln(args ...interface{}) { - logger.Logln(ErrorLevel, args...) -} - -func (logger *Logger) Fatalln(args ...interface{}) { - logger.Logln(FatalLevel, args...) - logger.Exit(1) -} - -func (logger *Logger) Panicln(args ...interface{}) { - logger.Logln(PanicLevel, args...) -} - -func (logger *Logger) Exit(code int) { - runHandlers() - if logger.ExitFunc == nil { - logger.ExitFunc = os.Exit - } - logger.ExitFunc(code) -} - -//When file is opened with appending mode, it's safe to -//write concurrently to a file (within 4k message on Linux). -//In these cases user can choose to disable the lock. -func (logger *Logger) SetNoLock() { - logger.mu.Disable() -} - -func (logger *Logger) level() Level { - return Level(atomic.LoadUint32((*uint32)(&logger.Level))) -} - -// SetLevel sets the logger level. -func (logger *Logger) SetLevel(level Level) { - atomic.StoreUint32((*uint32)(&logger.Level), uint32(level)) -} - -// GetLevel returns the logger level. -func (logger *Logger) GetLevel() Level { - return logger.level() -} - -// AddHook adds a hook to the logger hooks. -func (logger *Logger) AddHook(hook Hook) { - logger.mu.Lock() - defer logger.mu.Unlock() - logger.Hooks.Add(hook) -} - -// IsLevelEnabled checks if the log level of the logger is greater than the level param -func (logger *Logger) IsLevelEnabled(level Level) bool { - return logger.level() >= level -} - -// SetFormatter sets the logger formatter. -func (logger *Logger) SetFormatter(formatter Formatter) { - logger.mu.Lock() - defer logger.mu.Unlock() - logger.Formatter = formatter -} - -// SetOutput sets the logger output. -func (logger *Logger) SetOutput(output io.Writer) { - logger.mu.Lock() - defer logger.mu.Unlock() - logger.Out = output -} - -func (logger *Logger) SetReportCaller(reportCaller bool) { - logger.mu.Lock() - defer logger.mu.Unlock() - logger.ReportCaller = reportCaller -} - -// ReplaceHooks replaces the logger hooks and returns the old ones -func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks { - logger.mu.Lock() - oldHooks := logger.Hooks - logger.Hooks = hooks - logger.mu.Unlock() - return oldHooks -} - -// SetBufferPool sets the logger buffer pool. -func (logger *Logger) SetBufferPool(pool BufferPool) { - logger.mu.Lock() - defer logger.mu.Unlock() - logger.BufferPool = pool -} diff --git a/vendor/github.com/sirupsen/logrus/logrus.go b/vendor/github.com/sirupsen/logrus/logrus.go deleted file mode 100644 index 2f16224cb..000000000 --- a/vendor/github.com/sirupsen/logrus/logrus.go +++ /dev/null @@ -1,186 +0,0 @@ -package logrus - -import ( - "fmt" - "log" - "strings" -) - -// Fields type, used to pass to `WithFields`. -type Fields map[string]interface{} - -// Level type -type Level uint32 - -// Convert the Level to a string. E.g. PanicLevel becomes "panic". -func (level Level) String() string { - if b, err := level.MarshalText(); err == nil { - return string(b) - } else { - return "unknown" - } -} - -// ParseLevel takes a string level and returns the Logrus log level constant. -func ParseLevel(lvl string) (Level, error) { - switch strings.ToLower(lvl) { - case "panic": - return PanicLevel, nil - case "fatal": - return FatalLevel, nil - case "error": - return ErrorLevel, nil - case "warn", "warning": - return WarnLevel, nil - case "info": - return InfoLevel, nil - case "debug": - return DebugLevel, nil - case "trace": - return TraceLevel, nil - } - - var l Level - return l, fmt.Errorf("not a valid logrus Level: %q", lvl) -} - -// UnmarshalText implements encoding.TextUnmarshaler. -func (level *Level) UnmarshalText(text []byte) error { - l, err := ParseLevel(string(text)) - if err != nil { - return err - } - - *level = l - - return nil -} - -func (level Level) MarshalText() ([]byte, error) { - switch level { - case TraceLevel: - return []byte("trace"), nil - case DebugLevel: - return []byte("debug"), nil - case InfoLevel: - return []byte("info"), nil - case WarnLevel: - return []byte("warning"), nil - case ErrorLevel: - return []byte("error"), nil - case FatalLevel: - return []byte("fatal"), nil - case PanicLevel: - return []byte("panic"), nil - } - - return nil, fmt.Errorf("not a valid logrus level %d", level) -} - -// A constant exposing all logging levels -var AllLevels = []Level{ - PanicLevel, - FatalLevel, - ErrorLevel, - WarnLevel, - InfoLevel, - DebugLevel, - TraceLevel, -} - -// These are the different logging levels. You can set the logging level to log -// on your instance of logger, obtained with `logrus.New()`. -const ( - // PanicLevel level, highest level of severity. Logs and then calls panic with the - // message passed to Debug, Info, ... - PanicLevel Level = iota - // FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the - // logging level is set to Panic. - FatalLevel - // ErrorLevel level. Logs. Used for errors that should definitely be noted. - // Commonly used for hooks to send errors to an error tracking service. - ErrorLevel - // WarnLevel level. Non-critical entries that deserve eyes. - WarnLevel - // InfoLevel level. General operational entries about what's going on inside the - // application. - InfoLevel - // DebugLevel level. Usually only enabled when debugging. Very verbose logging. - DebugLevel - // TraceLevel level. Designates finer-grained informational events than the Debug. - TraceLevel -) - -// Won't compile if StdLogger can't be realized by a log.Logger -var ( - _ StdLogger = &log.Logger{} - _ StdLogger = &Entry{} - _ StdLogger = &Logger{} -) - -// StdLogger is what your logrus-enabled library should take, that way -// it'll accept a stdlib logger and a logrus logger. There's no standard -// interface, this is the closest we get, unfortunately. -type StdLogger interface { - Print(...interface{}) - Printf(string, ...interface{}) - Println(...interface{}) - - Fatal(...interface{}) - Fatalf(string, ...interface{}) - Fatalln(...interface{}) - - Panic(...interface{}) - Panicf(string, ...interface{}) - Panicln(...interface{}) -} - -// The FieldLogger interface generalizes the Entry and Logger types -type FieldLogger interface { - WithField(key string, value interface{}) *Entry - WithFields(fields Fields) *Entry - WithError(err error) *Entry - - Debugf(format string, args ...interface{}) - Infof(format string, args ...interface{}) - Printf(format string, args ...interface{}) - Warnf(format string, args ...interface{}) - Warningf(format string, args ...interface{}) - Errorf(format string, args ...interface{}) - Fatalf(format string, args ...interface{}) - Panicf(format string, args ...interface{}) - - Debug(args ...interface{}) - Info(args ...interface{}) - Print(args ...interface{}) - Warn(args ...interface{}) - Warning(args ...interface{}) - Error(args ...interface{}) - Fatal(args ...interface{}) - Panic(args ...interface{}) - - Debugln(args ...interface{}) - Infoln(args ...interface{}) - Println(args ...interface{}) - Warnln(args ...interface{}) - Warningln(args ...interface{}) - Errorln(args ...interface{}) - Fatalln(args ...interface{}) - Panicln(args ...interface{}) - - // IsDebugEnabled() bool - // IsInfoEnabled() bool - // IsWarnEnabled() bool - // IsErrorEnabled() bool - // IsFatalEnabled() bool - // IsPanicEnabled() bool -} - -// Ext1FieldLogger (the first extension to FieldLogger) is superfluous, it is -// here for consistancy. Do not use. Use Logger or Entry instead. -type Ext1FieldLogger interface { - FieldLogger - Tracef(format string, args ...interface{}) - Trace(args ...interface{}) - Traceln(args ...interface{}) -} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go b/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go deleted file mode 100644 index 2403de981..000000000 --- a/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build appengine - -package logrus - -import ( - "io" -) - -func checkIfTerminal(w io.Writer) bool { - return true -} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go b/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go deleted file mode 100644 index 499789984..000000000 --- a/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build darwin dragonfly freebsd netbsd openbsd -// +build !js - -package logrus - -import "golang.org/x/sys/unix" - -const ioctlReadTermios = unix.TIOCGETA - -func isTerminal(fd int) bool { - _, err := unix.IoctlGetTermios(fd, ioctlReadTermios) - return err == nil -} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_js.go b/vendor/github.com/sirupsen/logrus/terminal_check_js.go deleted file mode 100644 index ebdae3ec6..000000000 --- a/vendor/github.com/sirupsen/logrus/terminal_check_js.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build js - -package logrus - -func isTerminal(fd int) bool { - return false -} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go b/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go deleted file mode 100644 index 97af92c68..000000000 --- a/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build js nacl plan9 - -package logrus - -import ( - "io" -) - -func checkIfTerminal(w io.Writer) bool { - return false -} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go b/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go deleted file mode 100644 index 3293fb3ca..000000000 --- a/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go +++ /dev/null @@ -1,17 +0,0 @@ -// +build !appengine,!js,!windows,!nacl,!plan9 - -package logrus - -import ( - "io" - "os" -) - -func checkIfTerminal(w io.Writer) bool { - switch v := w.(type) { - case *os.File: - return isTerminal(int(v.Fd())) - default: - return false - } -} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_solaris.go b/vendor/github.com/sirupsen/logrus/terminal_check_solaris.go deleted file mode 100644 index f6710b3bd..000000000 --- a/vendor/github.com/sirupsen/logrus/terminal_check_solaris.go +++ /dev/null @@ -1,11 +0,0 @@ -package logrus - -import ( - "golang.org/x/sys/unix" -) - -// IsTerminal returns true if the given file descriptor is a terminal. -func isTerminal(fd int) bool { - _, err := unix.IoctlGetTermio(fd, unix.TCGETA) - return err == nil -} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_unix.go b/vendor/github.com/sirupsen/logrus/terminal_check_unix.go deleted file mode 100644 index 04748b851..000000000 --- a/vendor/github.com/sirupsen/logrus/terminal_check_unix.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build linux aix zos -// +build !js - -package logrus - -import "golang.org/x/sys/unix" - -const ioctlReadTermios = unix.TCGETS - -func isTerminal(fd int) bool { - _, err := unix.IoctlGetTermios(fd, ioctlReadTermios) - return err == nil -} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_windows.go b/vendor/github.com/sirupsen/logrus/terminal_check_windows.go deleted file mode 100644 index 2879eb50e..000000000 --- a/vendor/github.com/sirupsen/logrus/terminal_check_windows.go +++ /dev/null @@ -1,27 +0,0 @@ -// +build !appengine,!js,windows - -package logrus - -import ( - "io" - "os" - - "golang.org/x/sys/windows" -) - -func checkIfTerminal(w io.Writer) bool { - switch v := w.(type) { - case *os.File: - handle := windows.Handle(v.Fd()) - var mode uint32 - if err := windows.GetConsoleMode(handle, &mode); err != nil { - return false - } - mode |= windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING - if err := windows.SetConsoleMode(handle, mode); err != nil { - return false - } - return true - } - return false -} diff --git a/vendor/github.com/sirupsen/logrus/text_formatter.go b/vendor/github.com/sirupsen/logrus/text_formatter.go deleted file mode 100644 index be2c6efe5..000000000 --- a/vendor/github.com/sirupsen/logrus/text_formatter.go +++ /dev/null @@ -1,339 +0,0 @@ -package logrus - -import ( - "bytes" - "fmt" - "os" - "runtime" - "sort" - "strconv" - "strings" - "sync" - "time" - "unicode/utf8" -) - -const ( - red = 31 - yellow = 33 - blue = 36 - gray = 37 -) - -var baseTimestamp time.Time - -func init() { - baseTimestamp = time.Now() -} - -// TextFormatter formats logs into text -type TextFormatter struct { - // Set to true to bypass checking for a TTY before outputting colors. - ForceColors bool - - // Force disabling colors. - DisableColors bool - - // Force quoting of all values - ForceQuote bool - - // DisableQuote disables quoting for all values. - // DisableQuote will have a lower priority than ForceQuote. - // If both of them are set to true, quote will be forced on all values. - DisableQuote bool - - // Override coloring based on CLICOLOR and CLICOLOR_FORCE. - https://bixense.com/clicolors/ - EnvironmentOverrideColors bool - - // Disable timestamp logging. useful when output is redirected to logging - // system that already adds timestamps. - DisableTimestamp bool - - // Enable logging the full timestamp when a TTY is attached instead of just - // the time passed since beginning of execution. - FullTimestamp bool - - // TimestampFormat to use for display when a full timestamp is printed. - // The format to use is the same than for time.Format or time.Parse from the standard - // library. - // The standard Library already provides a set of predefined format. - TimestampFormat string - - // The fields are sorted by default for a consistent output. For applications - // that log extremely frequently and don't use the JSON formatter this may not - // be desired. - DisableSorting bool - - // The keys sorting function, when uninitialized it uses sort.Strings. - SortingFunc func([]string) - - // Disables the truncation of the level text to 4 characters. - DisableLevelTruncation bool - - // PadLevelText Adds padding the level text so that all the levels output at the same length - // PadLevelText is a superset of the DisableLevelTruncation option - PadLevelText bool - - // QuoteEmptyFields will wrap empty fields in quotes if true - QuoteEmptyFields bool - - // Whether the logger's out is to a terminal - isTerminal bool - - // FieldMap allows users to customize the names of keys for default fields. - // As an example: - // formatter := &TextFormatter{ - // FieldMap: FieldMap{ - // FieldKeyTime: "@timestamp", - // FieldKeyLevel: "@level", - // FieldKeyMsg: "@message"}} - FieldMap FieldMap - - // CallerPrettyfier can be set by the user to modify the content - // of the function and file keys in the data when ReportCaller is - // activated. If any of the returned value is the empty string the - // corresponding key will be removed from fields. - CallerPrettyfier func(*runtime.Frame) (function string, file string) - - terminalInitOnce sync.Once - - // The max length of the level text, generated dynamically on init - levelTextMaxLength int -} - -func (f *TextFormatter) init(entry *Entry) { - if entry.Logger != nil { - f.isTerminal = checkIfTerminal(entry.Logger.Out) - } - // Get the max length of the level text - for _, level := range AllLevels { - levelTextLength := utf8.RuneCount([]byte(level.String())) - if levelTextLength > f.levelTextMaxLength { - f.levelTextMaxLength = levelTextLength - } - } -} - -func (f *TextFormatter) isColored() bool { - isColored := f.ForceColors || (f.isTerminal && (runtime.GOOS != "windows")) - - if f.EnvironmentOverrideColors { - switch force, ok := os.LookupEnv("CLICOLOR_FORCE"); { - case ok && force != "0": - isColored = true - case ok && force == "0", os.Getenv("CLICOLOR") == "0": - isColored = false - } - } - - return isColored && !f.DisableColors -} - -// Format renders a single log entry -func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { - data := make(Fields) - for k, v := range entry.Data { - data[k] = v - } - prefixFieldClashes(data, f.FieldMap, entry.HasCaller()) - keys := make([]string, 0, len(data)) - for k := range data { - keys = append(keys, k) - } - - var funcVal, fileVal string - - fixedKeys := make([]string, 0, 4+len(data)) - if !f.DisableTimestamp { - fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyTime)) - } - fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLevel)) - if entry.Message != "" { - fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyMsg)) - } - if entry.err != "" { - fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLogrusError)) - } - if entry.HasCaller() { - if f.CallerPrettyfier != nil { - funcVal, fileVal = f.CallerPrettyfier(entry.Caller) - } else { - funcVal = entry.Caller.Function - fileVal = fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line) - } - - if funcVal != "" { - fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFunc)) - } - if fileVal != "" { - fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFile)) - } - } - - if !f.DisableSorting { - if f.SortingFunc == nil { - sort.Strings(keys) - fixedKeys = append(fixedKeys, keys...) - } else { - if !f.isColored() { - fixedKeys = append(fixedKeys, keys...) - f.SortingFunc(fixedKeys) - } else { - f.SortingFunc(keys) - } - } - } else { - fixedKeys = append(fixedKeys, keys...) - } - - var b *bytes.Buffer - if entry.Buffer != nil { - b = entry.Buffer - } else { - b = &bytes.Buffer{} - } - - f.terminalInitOnce.Do(func() { f.init(entry) }) - - timestampFormat := f.TimestampFormat - if timestampFormat == "" { - timestampFormat = defaultTimestampFormat - } - if f.isColored() { - f.printColored(b, entry, keys, data, timestampFormat) - } else { - - for _, key := range fixedKeys { - var value interface{} - switch { - case key == f.FieldMap.resolve(FieldKeyTime): - value = entry.Time.Format(timestampFormat) - case key == f.FieldMap.resolve(FieldKeyLevel): - value = entry.Level.String() - case key == f.FieldMap.resolve(FieldKeyMsg): - value = entry.Message - case key == f.FieldMap.resolve(FieldKeyLogrusError): - value = entry.err - case key == f.FieldMap.resolve(FieldKeyFunc) && entry.HasCaller(): - value = funcVal - case key == f.FieldMap.resolve(FieldKeyFile) && entry.HasCaller(): - value = fileVal - default: - value = data[key] - } - f.appendKeyValue(b, key, value) - } - } - - b.WriteByte('\n') - return b.Bytes(), nil -} - -func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, data Fields, timestampFormat string) { - var levelColor int - switch entry.Level { - case DebugLevel, TraceLevel: - levelColor = gray - case WarnLevel: - levelColor = yellow - case ErrorLevel, FatalLevel, PanicLevel: - levelColor = red - case InfoLevel: - levelColor = blue - default: - levelColor = blue - } - - levelText := strings.ToUpper(entry.Level.String()) - if !f.DisableLevelTruncation && !f.PadLevelText { - levelText = levelText[0:4] - } - if f.PadLevelText { - // Generates the format string used in the next line, for example "%-6s" or "%-7s". - // Based on the max level text length. - formatString := "%-" + strconv.Itoa(f.levelTextMaxLength) + "s" - // Formats the level text by appending spaces up to the max length, for example: - // - "INFO " - // - "WARNING" - levelText = fmt.Sprintf(formatString, levelText) - } - - // Remove a single newline if it already exists in the message to keep - // the behavior of logrus text_formatter the same as the stdlib log package - entry.Message = strings.TrimSuffix(entry.Message, "\n") - - caller := "" - if entry.HasCaller() { - funcVal := fmt.Sprintf("%s()", entry.Caller.Function) - fileVal := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line) - - if f.CallerPrettyfier != nil { - funcVal, fileVal = f.CallerPrettyfier(entry.Caller) - } - - if fileVal == "" { - caller = funcVal - } else if funcVal == "" { - caller = fileVal - } else { - caller = fileVal + " " + funcVal - } - } - - switch { - case f.DisableTimestamp: - fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m%s %-44s ", levelColor, levelText, caller, entry.Message) - case !f.FullTimestamp: - fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d]%s %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), caller, entry.Message) - default: - fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s]%s %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), caller, entry.Message) - } - for _, k := range keys { - v := data[k] - fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k) - f.appendValue(b, v) - } -} - -func (f *TextFormatter) needsQuoting(text string) bool { - if f.ForceQuote { - return true - } - if f.QuoteEmptyFields && len(text) == 0 { - return true - } - if f.DisableQuote { - return false - } - for _, ch := range text { - if !((ch >= 'a' && ch <= 'z') || - (ch >= 'A' && ch <= 'Z') || - (ch >= '0' && ch <= '9') || - ch == '-' || ch == '.' || ch == '_' || ch == '/' || ch == '@' || ch == '^' || ch == '+') { - return true - } - } - return false -} - -func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) { - if b.Len() > 0 { - b.WriteByte(' ') - } - b.WriteString(key) - b.WriteByte('=') - f.appendValue(b, value) -} - -func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) { - stringVal, ok := value.(string) - if !ok { - stringVal = fmt.Sprint(value) - } - - if !f.needsQuoting(stringVal) { - b.WriteString(stringVal) - } else { - b.WriteString(fmt.Sprintf("%q", stringVal)) - } -} diff --git a/vendor/github.com/sirupsen/logrus/writer.go b/vendor/github.com/sirupsen/logrus/writer.go deleted file mode 100644 index 074fd4b8b..000000000 --- a/vendor/github.com/sirupsen/logrus/writer.go +++ /dev/null @@ -1,102 +0,0 @@ -package logrus - -import ( - "bufio" - "io" - "runtime" - "strings" -) - -// Writer at INFO level. See WriterLevel for details. -func (logger *Logger) Writer() *io.PipeWriter { - return logger.WriterLevel(InfoLevel) -} - -// WriterLevel returns an io.Writer that can be used to write arbitrary text to -// the logger at the given log level. Each line written to the writer will be -// printed in the usual way using formatters and hooks. The writer is part of an -// io.Pipe and it is the callers responsibility to close the writer when done. -// This can be used to override the standard library logger easily. -func (logger *Logger) WriterLevel(level Level) *io.PipeWriter { - return NewEntry(logger).WriterLevel(level) -} - -// Writer returns an io.Writer that writes to the logger at the info log level -func (entry *Entry) Writer() *io.PipeWriter { - return entry.WriterLevel(InfoLevel) -} - -// WriterLevel returns an io.Writer that writes to the logger at the given log level -func (entry *Entry) WriterLevel(level Level) *io.PipeWriter { - reader, writer := io.Pipe() - - var printFunc func(args ...interface{}) - - // Determine which log function to use based on the specified log level - switch level { - case TraceLevel: - printFunc = entry.Trace - case DebugLevel: - printFunc = entry.Debug - case InfoLevel: - printFunc = entry.Info - case WarnLevel: - printFunc = entry.Warn - case ErrorLevel: - printFunc = entry.Error - case FatalLevel: - printFunc = entry.Fatal - case PanicLevel: - printFunc = entry.Panic - default: - printFunc = entry.Print - } - - // Start a new goroutine to scan the input and write it to the logger using the specified print function. - // It splits the input into chunks of up to 64KB to avoid buffer overflows. - go entry.writerScanner(reader, printFunc) - - // Set a finalizer function to close the writer when it is garbage collected - runtime.SetFinalizer(writer, writerFinalizer) - - return writer -} - -// writerScanner scans the input from the reader and writes it to the logger -func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) { - scanner := bufio.NewScanner(reader) - - // Set the buffer size to the maximum token size to avoid buffer overflows - scanner.Buffer(make([]byte, bufio.MaxScanTokenSize), bufio.MaxScanTokenSize) - - // Define a split function to split the input into chunks of up to 64KB - chunkSize := bufio.MaxScanTokenSize // 64KB - splitFunc := func(data []byte, atEOF bool) (int, []byte, error) { - if len(data) >= chunkSize { - return chunkSize, data[:chunkSize], nil - } - - return bufio.ScanLines(data, atEOF) - } - - // Use the custom split function to split the input - scanner.Split(splitFunc) - - // Scan the input and write it to the logger using the specified print function - for scanner.Scan() { - printFunc(strings.TrimRight(scanner.Text(), "\r\n")) - } - - // If there was an error while scanning the input, log an error - if err := scanner.Err(); err != nil { - entry.Errorf("Error while reading from Writer: %s", err) - } - - // Close the reader when we are done - reader.Close() -} - -// WriterFinalizer is a finalizer function that closes then given writer when it is garbage collected -func writerFinalizer(writer *io.PipeWriter) { - writer.Close() -} diff --git a/vendor/github.com/vbatts/tar-split/LICENSE b/vendor/github.com/vbatts/tar-split/LICENSE deleted file mode 100644 index ca03685b1..000000000 --- a/vendor/github.com/vbatts/tar-split/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright (c) 2015 Vincent Batts, Raleigh, NC, USA - -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this -list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, -this list of conditions and the following disclaimer in the documentation -and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors -may be used to endorse or promote products derived from this software without -specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/vbatts/tar-split/archive/tar/common.go b/vendor/github.com/vbatts/tar-split/archive/tar/common.go deleted file mode 100644 index dee9e47e4..000000000 --- a/vendor/github.com/vbatts/tar-split/archive/tar/common.go +++ /dev/null @@ -1,723 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package tar implements access to tar archives. -// -// Tape archives (tar) are a file format for storing a sequence of files that -// can be read and written in a streaming manner. -// This package aims to cover most variations of the format, -// including those produced by GNU and BSD tar tools. -package tar - -import ( - "errors" - "fmt" - "math" - "os" - "path" - "reflect" - "strconv" - "strings" - "time" -) - -// BUG: Use of the Uid and Gid fields in Header could overflow on 32-bit -// architectures. If a large value is encountered when decoding, the result -// stored in Header will be the truncated version. - -var ( - ErrHeader = errors.New("archive/tar: invalid tar header") - ErrWriteTooLong = errors.New("archive/tar: write too long") - ErrFieldTooLong = errors.New("archive/tar: header field too long") - ErrWriteAfterClose = errors.New("archive/tar: write after close") - errMissData = errors.New("archive/tar: sparse file references non-existent data") - errUnrefData = errors.New("archive/tar: sparse file contains unreferenced data") - errWriteHole = errors.New("archive/tar: write non-NUL byte in sparse hole") -) - -type headerError []string - -func (he headerError) Error() string { - const prefix = "archive/tar: cannot encode header" - var ss []string - for _, s := range he { - if s != "" { - ss = append(ss, s) - } - } - if len(ss) == 0 { - return prefix - } - return fmt.Sprintf("%s: %v", prefix, strings.Join(ss, "; and ")) -} - -// Type flags for Header.Typeflag. -const ( - // Type '0' indicates a regular file. - TypeReg = '0' - TypeRegA = '\x00' // Deprecated: Use TypeReg instead. - - // Type '1' to '6' are header-only flags and may not have a data body. - TypeLink = '1' // Hard link - TypeSymlink = '2' // Symbolic link - TypeChar = '3' // Character device node - TypeBlock = '4' // Block device node - TypeDir = '5' // Directory - TypeFifo = '6' // FIFO node - - // Type '7' is reserved. - TypeCont = '7' - - // Type 'x' is used by the PAX format to store key-value records that - // are only relevant to the next file. - // This package transparently handles these types. - TypeXHeader = 'x' - - // Type 'g' is used by the PAX format to store key-value records that - // are relevant to all subsequent files. - // This package only supports parsing and composing such headers, - // but does not currently support persisting the global state across files. - TypeXGlobalHeader = 'g' - - // Type 'S' indicates a sparse file in the GNU format. - TypeGNUSparse = 'S' - - // Types 'L' and 'K' are used by the GNU format for a meta file - // used to store the path or link name for the next file. - // This package transparently handles these types. - TypeGNULongName = 'L' - TypeGNULongLink = 'K' -) - -// Keywords for PAX extended header records. -const ( - paxNone = "" // Indicates that no PAX key is suitable - paxPath = "path" - paxLinkpath = "linkpath" - paxSize = "size" - paxUid = "uid" - paxGid = "gid" - paxUname = "uname" - paxGname = "gname" - paxMtime = "mtime" - paxAtime = "atime" - paxCtime = "ctime" // Removed from later revision of PAX spec, but was valid - paxCharset = "charset" // Currently unused - paxComment = "comment" // Currently unused - - paxSchilyXattr = "SCHILY.xattr." - - // Keywords for GNU sparse files in a PAX extended header. - paxGNUSparse = "GNU.sparse." - paxGNUSparseNumBlocks = "GNU.sparse.numblocks" - paxGNUSparseOffset = "GNU.sparse.offset" - paxGNUSparseNumBytes = "GNU.sparse.numbytes" - paxGNUSparseMap = "GNU.sparse.map" - paxGNUSparseName = "GNU.sparse.name" - paxGNUSparseMajor = "GNU.sparse.major" - paxGNUSparseMinor = "GNU.sparse.minor" - paxGNUSparseSize = "GNU.sparse.size" - paxGNUSparseRealSize = "GNU.sparse.realsize" -) - -// basicKeys is a set of the PAX keys for which we have built-in support. -// This does not contain "charset" or "comment", which are both PAX-specific, -// so adding them as first-class features of Header is unlikely. -// Users can use the PAXRecords field to set it themselves. -var basicKeys = map[string]bool{ - paxPath: true, paxLinkpath: true, paxSize: true, paxUid: true, paxGid: true, - paxUname: true, paxGname: true, paxMtime: true, paxAtime: true, paxCtime: true, -} - -// A Header represents a single header in a tar archive. -// Some fields may not be populated. -// -// For forward compatibility, users that retrieve a Header from Reader.Next, -// mutate it in some ways, and then pass it back to Writer.WriteHeader -// should do so by creating a new Header and copying the fields -// that they are interested in preserving. -type Header struct { - // Typeflag is the type of header entry. - // The zero value is automatically promoted to either TypeReg or TypeDir - // depending on the presence of a trailing slash in Name. - Typeflag byte - - Name string // Name of file entry - Linkname string // Target name of link (valid for TypeLink or TypeSymlink) - - Size int64 // Logical file size in bytes - Mode int64 // Permission and mode bits - Uid int // User ID of owner - Gid int // Group ID of owner - Uname string // User name of owner - Gname string // Group name of owner - - // If the Format is unspecified, then Writer.WriteHeader rounds ModTime - // to the nearest second and ignores the AccessTime and ChangeTime fields. - // - // To use AccessTime or ChangeTime, specify the Format as PAX or GNU. - // To use sub-second resolution, specify the Format as PAX. - ModTime time.Time // Modification time - AccessTime time.Time // Access time (requires either PAX or GNU support) - ChangeTime time.Time // Change time (requires either PAX or GNU support) - - Devmajor int64 // Major device number (valid for TypeChar or TypeBlock) - Devminor int64 // Minor device number (valid for TypeChar or TypeBlock) - - // Xattrs stores extended attributes as PAX records under the - // "SCHILY.xattr." namespace. - // - // The following are semantically equivalent: - // h.Xattrs[key] = value - // h.PAXRecords["SCHILY.xattr."+key] = value - // - // When Writer.WriteHeader is called, the contents of Xattrs will take - // precedence over those in PAXRecords. - // - // Deprecated: Use PAXRecords instead. - Xattrs map[string]string - - // PAXRecords is a map of PAX extended header records. - // - // User-defined records should have keys of the following form: - // VENDOR.keyword - // Where VENDOR is some namespace in all uppercase, and keyword may - // not contain the '=' character (e.g., "GOLANG.pkg.version"). - // The key and value should be non-empty UTF-8 strings. - // - // When Writer.WriteHeader is called, PAX records derived from the - // other fields in Header take precedence over PAXRecords. - PAXRecords map[string]string - - // Format specifies the format of the tar header. - // - // This is set by Reader.Next as a best-effort guess at the format. - // Since the Reader liberally reads some non-compliant files, - // it is possible for this to be FormatUnknown. - // - // If the format is unspecified when Writer.WriteHeader is called, - // then it uses the first format (in the order of USTAR, PAX, GNU) - // capable of encoding this Header (see Format). - Format Format -} - -// sparseEntry represents a Length-sized fragment at Offset in the file. -type sparseEntry struct{ Offset, Length int64 } - -func (s sparseEntry) endOffset() int64 { return s.Offset + s.Length } - -// A sparse file can be represented as either a sparseDatas or a sparseHoles. -// As long as the total size is known, they are equivalent and one can be -// converted to the other form and back. The various tar formats with sparse -// file support represent sparse files in the sparseDatas form. That is, they -// specify the fragments in the file that has data, and treat everything else as -// having zero bytes. As such, the encoding and decoding logic in this package -// deals with sparseDatas. -// -// However, the external API uses sparseHoles instead of sparseDatas because the -// zero value of sparseHoles logically represents a normal file (i.e., there are -// no holes in it). On the other hand, the zero value of sparseDatas implies -// that the file has no data in it, which is rather odd. -// -// As an example, if the underlying raw file contains the 10-byte data: -// var compactFile = "abcdefgh" -// -// And the sparse map has the following entries: -// var spd sparseDatas = []sparseEntry{ -// {Offset: 2, Length: 5}, // Data fragment for 2..6 -// {Offset: 18, Length: 3}, // Data fragment for 18..20 -// } -// var sph sparseHoles = []sparseEntry{ -// {Offset: 0, Length: 2}, // Hole fragment for 0..1 -// {Offset: 7, Length: 11}, // Hole fragment for 7..17 -// {Offset: 21, Length: 4}, // Hole fragment for 21..24 -// } -// -// Then the content of the resulting sparse file with a Header.Size of 25 is: -// var sparseFile = "\x00"*2 + "abcde" + "\x00"*11 + "fgh" + "\x00"*4 -type ( - sparseDatas []sparseEntry - sparseHoles []sparseEntry -) - -// validateSparseEntries reports whether sp is a valid sparse map. -// It does not matter whether sp represents data fragments or hole fragments. -func validateSparseEntries(sp []sparseEntry, size int64) bool { - // Validate all sparse entries. These are the same checks as performed by - // the BSD tar utility. - if size < 0 { - return false - } - var pre sparseEntry - for _, cur := range sp { - switch { - case cur.Offset < 0 || cur.Length < 0: - return false // Negative values are never okay - case cur.Offset > math.MaxInt64-cur.Length: - return false // Integer overflow with large length - case cur.endOffset() > size: - return false // Region extends beyond the actual size - case pre.endOffset() > cur.Offset: - return false // Regions cannot overlap and must be in order - } - pre = cur - } - return true -} - -// alignSparseEntries mutates src and returns dst where each fragment's -// starting offset is aligned up to the nearest block edge, and each -// ending offset is aligned down to the nearest block edge. -// -// Even though the Go tar Reader and the BSD tar utility can handle entries -// with arbitrary offsets and lengths, the GNU tar utility can only handle -// offsets and lengths that are multiples of blockSize. -func alignSparseEntries(src []sparseEntry, size int64) []sparseEntry { - dst := src[:0] - for _, s := range src { - pos, end := s.Offset, s.endOffset() - pos += blockPadding(+pos) // Round-up to nearest blockSize - if end != size { - end -= blockPadding(-end) // Round-down to nearest blockSize - } - if pos < end { - dst = append(dst, sparseEntry{Offset: pos, Length: end - pos}) - } - } - return dst -} - -// invertSparseEntries converts a sparse map from one form to the other. -// If the input is sparseHoles, then it will output sparseDatas and vice-versa. -// The input must have been already validated. -// -// This function mutates src and returns a normalized map where: -// * adjacent fragments are coalesced together -// * only the last fragment may be empty -// * the endOffset of the last fragment is the total size -func invertSparseEntries(src []sparseEntry, size int64) []sparseEntry { - dst := src[:0] - var pre sparseEntry - for _, cur := range src { - if cur.Length == 0 { - continue // Skip empty fragments - } - pre.Length = cur.Offset - pre.Offset - if pre.Length > 0 { - dst = append(dst, pre) // Only add non-empty fragments - } - pre.Offset = cur.endOffset() - } - pre.Length = size - pre.Offset // Possibly the only empty fragment - return append(dst, pre) -} - -// fileState tracks the number of logical (includes sparse holes) and physical -// (actual in tar archive) bytes remaining for the current file. -// -// Invariant: LogicalRemaining >= PhysicalRemaining -type fileState interface { - LogicalRemaining() int64 - PhysicalRemaining() int64 -} - -// allowedFormats determines which formats can be used. -// The value returned is the logical OR of multiple possible formats. -// If the value is FormatUnknown, then the input Header cannot be encoded -// and an error is returned explaining why. -// -// As a by-product of checking the fields, this function returns paxHdrs, which -// contain all fields that could not be directly encoded. -// A value receiver ensures that this method does not mutate the source Header. -func (h Header) allowedFormats() (format Format, paxHdrs map[string]string, err error) { - format = FormatUSTAR | FormatPAX | FormatGNU - paxHdrs = make(map[string]string) - - var whyNoUSTAR, whyNoPAX, whyNoGNU string - var preferPAX bool // Prefer PAX over USTAR - verifyString := func(s string, size int, name, paxKey string) { - // NUL-terminator is optional for path and linkpath. - // Technically, it is required for uname and gname, - // but neither GNU nor BSD tar checks for it. - tooLong := len(s) > size - allowLongGNU := paxKey == paxPath || paxKey == paxLinkpath - if hasNUL(s) || (tooLong && !allowLongGNU) { - whyNoGNU = fmt.Sprintf("GNU cannot encode %s=%q", name, s) - format.mustNotBe(FormatGNU) - } - if !isASCII(s) || tooLong { - canSplitUSTAR := paxKey == paxPath - if _, _, ok := splitUSTARPath(s); !canSplitUSTAR || !ok { - whyNoUSTAR = fmt.Sprintf("USTAR cannot encode %s=%q", name, s) - format.mustNotBe(FormatUSTAR) - } - if paxKey == paxNone { - whyNoPAX = fmt.Sprintf("PAX cannot encode %s=%q", name, s) - format.mustNotBe(FormatPAX) - } else { - paxHdrs[paxKey] = s - } - } - if v, ok := h.PAXRecords[paxKey]; ok && v == s { - paxHdrs[paxKey] = v - } - } - verifyNumeric := func(n int64, size int, name, paxKey string) { - if !fitsInBase256(size, n) { - whyNoGNU = fmt.Sprintf("GNU cannot encode %s=%d", name, n) - format.mustNotBe(FormatGNU) - } - if !fitsInOctal(size, n) { - whyNoUSTAR = fmt.Sprintf("USTAR cannot encode %s=%d", name, n) - format.mustNotBe(FormatUSTAR) - if paxKey == paxNone { - whyNoPAX = fmt.Sprintf("PAX cannot encode %s=%d", name, n) - format.mustNotBe(FormatPAX) - } else { - paxHdrs[paxKey] = strconv.FormatInt(n, 10) - } - } - if v, ok := h.PAXRecords[paxKey]; ok && v == strconv.FormatInt(n, 10) { - paxHdrs[paxKey] = v - } - } - verifyTime := func(ts time.Time, size int, name, paxKey string) { - if ts.IsZero() { - return // Always okay - } - if !fitsInBase256(size, ts.Unix()) { - whyNoGNU = fmt.Sprintf("GNU cannot encode %s=%v", name, ts) - format.mustNotBe(FormatGNU) - } - isMtime := paxKey == paxMtime - fitsOctal := fitsInOctal(size, ts.Unix()) - if (isMtime && !fitsOctal) || !isMtime { - whyNoUSTAR = fmt.Sprintf("USTAR cannot encode %s=%v", name, ts) - format.mustNotBe(FormatUSTAR) - } - needsNano := ts.Nanosecond() != 0 - if !isMtime || !fitsOctal || needsNano { - preferPAX = true // USTAR may truncate sub-second measurements - if paxKey == paxNone { - whyNoPAX = fmt.Sprintf("PAX cannot encode %s=%v", name, ts) - format.mustNotBe(FormatPAX) - } else { - paxHdrs[paxKey] = formatPAXTime(ts) - } - } - if v, ok := h.PAXRecords[paxKey]; ok && v == formatPAXTime(ts) { - paxHdrs[paxKey] = v - } - } - - // Check basic fields. - var blk block - v7 := blk.V7() - ustar := blk.USTAR() - gnu := blk.GNU() - verifyString(h.Name, len(v7.Name()), "Name", paxPath) - verifyString(h.Linkname, len(v7.LinkName()), "Linkname", paxLinkpath) - verifyString(h.Uname, len(ustar.UserName()), "Uname", paxUname) - verifyString(h.Gname, len(ustar.GroupName()), "Gname", paxGname) - verifyNumeric(h.Mode, len(v7.Mode()), "Mode", paxNone) - verifyNumeric(int64(h.Uid), len(v7.UID()), "Uid", paxUid) - verifyNumeric(int64(h.Gid), len(v7.GID()), "Gid", paxGid) - verifyNumeric(h.Size, len(v7.Size()), "Size", paxSize) - verifyNumeric(h.Devmajor, len(ustar.DevMajor()), "Devmajor", paxNone) - verifyNumeric(h.Devminor, len(ustar.DevMinor()), "Devminor", paxNone) - verifyTime(h.ModTime, len(v7.ModTime()), "ModTime", paxMtime) - verifyTime(h.AccessTime, len(gnu.AccessTime()), "AccessTime", paxAtime) - verifyTime(h.ChangeTime, len(gnu.ChangeTime()), "ChangeTime", paxCtime) - - // Check for header-only types. - var whyOnlyPAX, whyOnlyGNU string - switch h.Typeflag { - case TypeReg, TypeChar, TypeBlock, TypeFifo, TypeGNUSparse: - // Exclude TypeLink and TypeSymlink, since they may reference directories. - if strings.HasSuffix(h.Name, "/") { - return FormatUnknown, nil, headerError{"filename may not have trailing slash"} - } - case TypeXHeader, TypeGNULongName, TypeGNULongLink: - return FormatUnknown, nil, headerError{"cannot manually encode TypeXHeader, TypeGNULongName, or TypeGNULongLink headers"} - case TypeXGlobalHeader: - h2 := Header{Name: h.Name, Typeflag: h.Typeflag, Xattrs: h.Xattrs, PAXRecords: h.PAXRecords, Format: h.Format} - if !reflect.DeepEqual(h, h2) { - return FormatUnknown, nil, headerError{"only PAXRecords should be set for TypeXGlobalHeader"} - } - whyOnlyPAX = "only PAX supports TypeXGlobalHeader" - format.mayOnlyBe(FormatPAX) - } - if !isHeaderOnlyType(h.Typeflag) && h.Size < 0 { - return FormatUnknown, nil, headerError{"negative size on header-only type"} - } - - // Check PAX records. - if len(h.Xattrs) > 0 { - for k, v := range h.Xattrs { - paxHdrs[paxSchilyXattr+k] = v - } - whyOnlyPAX = "only PAX supports Xattrs" - format.mayOnlyBe(FormatPAX) - } - if len(h.PAXRecords) > 0 { - for k, v := range h.PAXRecords { - switch _, exists := paxHdrs[k]; { - case exists: - continue // Do not overwrite existing records - case h.Typeflag == TypeXGlobalHeader: - paxHdrs[k] = v // Copy all records - case !basicKeys[k] && !strings.HasPrefix(k, paxGNUSparse): - paxHdrs[k] = v // Ignore local records that may conflict - } - } - whyOnlyPAX = "only PAX supports PAXRecords" - format.mayOnlyBe(FormatPAX) - } - for k, v := range paxHdrs { - if !validPAXRecord(k, v) { - return FormatUnknown, nil, headerError{fmt.Sprintf("invalid PAX record: %q", k+" = "+v)} - } - } - - // TODO(dsnet): Re-enable this when adding sparse support. - // See https://golang.org/issue/22735 - /* - // Check sparse files. - if len(h.SparseHoles) > 0 || h.Typeflag == TypeGNUSparse { - if isHeaderOnlyType(h.Typeflag) { - return FormatUnknown, nil, headerError{"header-only type cannot be sparse"} - } - if !validateSparseEntries(h.SparseHoles, h.Size) { - return FormatUnknown, nil, headerError{"invalid sparse holes"} - } - if h.Typeflag == TypeGNUSparse { - whyOnlyGNU = "only GNU supports TypeGNUSparse" - format.mayOnlyBe(FormatGNU) - } else { - whyNoGNU = "GNU supports sparse files only with TypeGNUSparse" - format.mustNotBe(FormatGNU) - } - whyNoUSTAR = "USTAR does not support sparse files" - format.mustNotBe(FormatUSTAR) - } - */ - - // Check desired format. - if wantFormat := h.Format; wantFormat != FormatUnknown { - if wantFormat.has(FormatPAX) && !preferPAX { - wantFormat.mayBe(FormatUSTAR) // PAX implies USTAR allowed too - } - format.mayOnlyBe(wantFormat) // Set union of formats allowed and format wanted - } - if format == FormatUnknown { - switch h.Format { - case FormatUSTAR: - err = headerError{"Format specifies USTAR", whyNoUSTAR, whyOnlyPAX, whyOnlyGNU} - case FormatPAX: - err = headerError{"Format specifies PAX", whyNoPAX, whyOnlyGNU} - case FormatGNU: - err = headerError{"Format specifies GNU", whyNoGNU, whyOnlyPAX} - default: - err = headerError{whyNoUSTAR, whyNoPAX, whyNoGNU, whyOnlyPAX, whyOnlyGNU} - } - } - return format, paxHdrs, err -} - -// FileInfo returns an os.FileInfo for the Header. -func (h *Header) FileInfo() os.FileInfo { - return headerFileInfo{h} -} - -// headerFileInfo implements os.FileInfo. -type headerFileInfo struct { - h *Header -} - -func (fi headerFileInfo) Size() int64 { return fi.h.Size } -func (fi headerFileInfo) IsDir() bool { return fi.Mode().IsDir() } -func (fi headerFileInfo) ModTime() time.Time { return fi.h.ModTime } -func (fi headerFileInfo) Sys() interface{} { return fi.h } - -// Name returns the base name of the file. -func (fi headerFileInfo) Name() string { - if fi.IsDir() { - return path.Base(path.Clean(fi.h.Name)) - } - return path.Base(fi.h.Name) -} - -// Mode returns the permission and mode bits for the headerFileInfo. -func (fi headerFileInfo) Mode() (mode os.FileMode) { - // Set file permission bits. - mode = os.FileMode(fi.h.Mode).Perm() - - // Set setuid, setgid and sticky bits. - if fi.h.Mode&c_ISUID != 0 { - mode |= os.ModeSetuid - } - if fi.h.Mode&c_ISGID != 0 { - mode |= os.ModeSetgid - } - if fi.h.Mode&c_ISVTX != 0 { - mode |= os.ModeSticky - } - - // Set file mode bits; clear perm, setuid, setgid, and sticky bits. - switch m := os.FileMode(fi.h.Mode) &^ 07777; m { - case c_ISDIR: - mode |= os.ModeDir - case c_ISFIFO: - mode |= os.ModeNamedPipe - case c_ISLNK: - mode |= os.ModeSymlink - case c_ISBLK: - mode |= os.ModeDevice - case c_ISCHR: - mode |= os.ModeDevice - mode |= os.ModeCharDevice - case c_ISSOCK: - mode |= os.ModeSocket - } - - switch fi.h.Typeflag { - case TypeSymlink: - mode |= os.ModeSymlink - case TypeChar: - mode |= os.ModeDevice - mode |= os.ModeCharDevice - case TypeBlock: - mode |= os.ModeDevice - case TypeDir: - mode |= os.ModeDir - case TypeFifo: - mode |= os.ModeNamedPipe - } - - return mode -} - -// sysStat, if non-nil, populates h from system-dependent fields of fi. -var sysStat func(fi os.FileInfo, h *Header) error - -const ( - // Mode constants from the USTAR spec: - // See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html#tag_20_92_13_06 - c_ISUID = 04000 // Set uid - c_ISGID = 02000 // Set gid - c_ISVTX = 01000 // Save text (sticky bit) - - // Common Unix mode constants; these are not defined in any common tar standard. - // Header.FileInfo understands these, but FileInfoHeader will never produce these. - c_ISDIR = 040000 // Directory - c_ISFIFO = 010000 // FIFO - c_ISREG = 0100000 // Regular file - c_ISLNK = 0120000 // Symbolic link - c_ISBLK = 060000 // Block special file - c_ISCHR = 020000 // Character special file - c_ISSOCK = 0140000 // Socket -) - -// FileInfoHeader creates a partially-populated Header from fi. -// If fi describes a symlink, FileInfoHeader records link as the link target. -// If fi describes a directory, a slash is appended to the name. -// -// Since os.FileInfo's Name method only returns the base name of -// the file it describes, it may be necessary to modify Header.Name -// to provide the full path name of the file. -func FileInfoHeader(fi os.FileInfo, link string) (*Header, error) { - if fi == nil { - return nil, errors.New("archive/tar: FileInfo is nil") - } - fm := fi.Mode() - h := &Header{ - Name: fi.Name(), - ModTime: fi.ModTime(), - Mode: int64(fm.Perm()), // or'd with c_IS* constants later - } - switch { - case fm.IsRegular(): - h.Typeflag = TypeReg - h.Size = fi.Size() - case fi.IsDir(): - h.Typeflag = TypeDir - h.Name += "/" - case fm&os.ModeSymlink != 0: - h.Typeflag = TypeSymlink - h.Linkname = link - case fm&os.ModeDevice != 0: - if fm&os.ModeCharDevice != 0 { - h.Typeflag = TypeChar - } else { - h.Typeflag = TypeBlock - } - case fm&os.ModeNamedPipe != 0: - h.Typeflag = TypeFifo - case fm&os.ModeSocket != 0: - return nil, fmt.Errorf("archive/tar: sockets not supported") - default: - return nil, fmt.Errorf("archive/tar: unknown file mode %v", fm) - } - if fm&os.ModeSetuid != 0 { - h.Mode |= c_ISUID - } - if fm&os.ModeSetgid != 0 { - h.Mode |= c_ISGID - } - if fm&os.ModeSticky != 0 { - h.Mode |= c_ISVTX - } - // If possible, populate additional fields from OS-specific - // FileInfo fields. - if sys, ok := fi.Sys().(*Header); ok { - // This FileInfo came from a Header (not the OS). Use the - // original Header to populate all remaining fields. - h.Uid = sys.Uid - h.Gid = sys.Gid - h.Uname = sys.Uname - h.Gname = sys.Gname - h.AccessTime = sys.AccessTime - h.ChangeTime = sys.ChangeTime - if sys.Xattrs != nil { - h.Xattrs = make(map[string]string) - for k, v := range sys.Xattrs { - h.Xattrs[k] = v - } - } - if sys.Typeflag == TypeLink { - // hard link - h.Typeflag = TypeLink - h.Size = 0 - h.Linkname = sys.Linkname - } - if sys.PAXRecords != nil { - h.PAXRecords = make(map[string]string) - for k, v := range sys.PAXRecords { - h.PAXRecords[k] = v - } - } - } - if sysStat != nil { - return h, sysStat(fi, h) - } - return h, nil -} - -// isHeaderOnlyType checks if the given type flag is of the type that has no -// data section even if a size is specified. -func isHeaderOnlyType(flag byte) bool { - switch flag { - case TypeLink, TypeSymlink, TypeChar, TypeBlock, TypeDir, TypeFifo: - return true - default: - return false - } -} - -func min(a, b int64) int64 { - if a < b { - return a - } - return b -} diff --git a/vendor/github.com/vbatts/tar-split/archive/tar/format.go b/vendor/github.com/vbatts/tar-split/archive/tar/format.go deleted file mode 100644 index 1f89d0c59..000000000 --- a/vendor/github.com/vbatts/tar-split/archive/tar/format.go +++ /dev/null @@ -1,303 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tar - -import "strings" - -// Format represents the tar archive format. -// -// The original tar format was introduced in Unix V7. -// Since then, there have been multiple competing formats attempting to -// standardize or extend the V7 format to overcome its limitations. -// The most common formats are the USTAR, PAX, and GNU formats, -// each with their own advantages and limitations. -// -// The following table captures the capabilities of each format: -// -// | USTAR | PAX | GNU -// ------------------+--------+-----------+---------- -// Name | 256B | unlimited | unlimited -// Linkname | 100B | unlimited | unlimited -// Size | uint33 | unlimited | uint89 -// Mode | uint21 | uint21 | uint57 -// Uid/Gid | uint21 | unlimited | uint57 -// Uname/Gname | 32B | unlimited | 32B -// ModTime | uint33 | unlimited | int89 -// AccessTime | n/a | unlimited | int89 -// ChangeTime | n/a | unlimited | int89 -// Devmajor/Devminor | uint21 | uint21 | uint57 -// ------------------+--------+-----------+---------- -// string encoding | ASCII | UTF-8 | binary -// sub-second times | no | yes | no -// sparse files | no | yes | yes -// -// The table's upper portion shows the Header fields, where each format reports -// the maximum number of bytes allowed for each string field and -// the integer type used to store each numeric field -// (where timestamps are stored as the number of seconds since the Unix epoch). -// -// The table's lower portion shows specialized features of each format, -// such as supported string encodings, support for sub-second timestamps, -// or support for sparse files. -// -// The Writer currently provides no support for sparse files. -type Format int - -// Constants to identify various tar formats. -const ( - // Deliberately hide the meaning of constants from public API. - _ Format = (1 << iota) / 4 // Sequence of 0, 0, 1, 2, 4, 8, etc... - - // FormatUnknown indicates that the format is unknown. - FormatUnknown - - // The format of the original Unix V7 tar tool prior to standardization. - formatV7 - - // FormatUSTAR represents the USTAR header format defined in POSIX.1-1988. - // - // While this format is compatible with most tar readers, - // the format has several limitations making it unsuitable for some usages. - // Most notably, it cannot support sparse files, files larger than 8GiB, - // filenames larger than 256 characters, and non-ASCII filenames. - // - // Reference: - // http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html#tag_20_92_13_06 - FormatUSTAR - - // FormatPAX represents the PAX header format defined in POSIX.1-2001. - // - // PAX extends USTAR by writing a special file with Typeflag TypeXHeader - // preceding the original header. This file contains a set of key-value - // records, which are used to overcome USTAR's shortcomings, in addition to - // providing the ability to have sub-second resolution for timestamps. - // - // Some newer formats add their own extensions to PAX by defining their - // own keys and assigning certain semantic meaning to the associated values. - // For example, sparse file support in PAX is implemented using keys - // defined by the GNU manual (e.g., "GNU.sparse.map"). - // - // Reference: - // http://pubs.opengroup.org/onlinepubs/009695399/utilities/pax.html - FormatPAX - - // FormatGNU represents the GNU header format. - // - // The GNU header format is older than the USTAR and PAX standards and - // is not compatible with them. The GNU format supports - // arbitrary file sizes, filenames of arbitrary encoding and length, - // sparse files, and other features. - // - // It is recommended that PAX be chosen over GNU unless the target - // application can only parse GNU formatted archives. - // - // Reference: - // https://www.gnu.org/software/tar/manual/html_node/Standard.html - FormatGNU - - // Schily's tar format, which is incompatible with USTAR. - // This does not cover STAR extensions to the PAX format; these fall under - // the PAX format. - formatSTAR - - formatMax -) - -func (f Format) has(f2 Format) bool { return f&f2 != 0 } -func (f *Format) mayBe(f2 Format) { *f |= f2 } -func (f *Format) mayOnlyBe(f2 Format) { *f &= f2 } -func (f *Format) mustNotBe(f2 Format) { *f &^= f2 } - -var formatNames = map[Format]string{ - formatV7: "V7", FormatUSTAR: "USTAR", FormatPAX: "PAX", FormatGNU: "GNU", formatSTAR: "STAR", -} - -func (f Format) String() string { - var ss []string - for f2 := Format(1); f2 < formatMax; f2 <<= 1 { - if f.has(f2) { - ss = append(ss, formatNames[f2]) - } - } - switch len(ss) { - case 0: - return "" - case 1: - return ss[0] - default: - return "(" + strings.Join(ss, " | ") + ")" - } -} - -// Magics used to identify various formats. -const ( - magicGNU, versionGNU = "ustar ", " \x00" - magicUSTAR, versionUSTAR = "ustar\x00", "00" - trailerSTAR = "tar\x00" -) - -// Size constants from various tar specifications. -const ( - blockSize = 512 // Size of each block in a tar stream - nameSize = 100 // Max length of the name field in USTAR format - prefixSize = 155 // Max length of the prefix field in USTAR format -) - -// blockPadding computes the number of bytes needed to pad offset up to the -// nearest block edge where 0 <= n < blockSize. -func blockPadding(offset int64) (n int64) { - return -offset & (blockSize - 1) -} - -var zeroBlock block - -type block [blockSize]byte - -// Convert block to any number of formats. -func (b *block) V7() *headerV7 { return (*headerV7)(b) } -func (b *block) GNU() *headerGNU { return (*headerGNU)(b) } -func (b *block) STAR() *headerSTAR { return (*headerSTAR)(b) } -func (b *block) USTAR() *headerUSTAR { return (*headerUSTAR)(b) } -func (b *block) Sparse() sparseArray { return (sparseArray)(b[:]) } - -// GetFormat checks that the block is a valid tar header based on the checksum. -// It then attempts to guess the specific format based on magic values. -// If the checksum fails, then FormatUnknown is returned. -func (b *block) GetFormat() Format { - // Verify checksum. - var p parser - value := p.parseOctal(b.V7().Chksum()) - chksum1, chksum2 := b.ComputeChecksum() - if p.err != nil || (value != chksum1 && value != chksum2) { - return FormatUnknown - } - - // Guess the magic values. - magic := string(b.USTAR().Magic()) - version := string(b.USTAR().Version()) - trailer := string(b.STAR().Trailer()) - switch { - case magic == magicUSTAR && trailer == trailerSTAR: - return formatSTAR - case magic == magicUSTAR: - return FormatUSTAR | FormatPAX - case magic == magicGNU && version == versionGNU: - return FormatGNU - default: - return formatV7 - } -} - -// SetFormat writes the magic values necessary for specified format -// and then updates the checksum accordingly. -func (b *block) SetFormat(format Format) { - // Set the magic values. - switch { - case format.has(formatV7): - // Do nothing. - case format.has(FormatGNU): - copy(b.GNU().Magic(), magicGNU) - copy(b.GNU().Version(), versionGNU) - case format.has(formatSTAR): - copy(b.STAR().Magic(), magicUSTAR) - copy(b.STAR().Version(), versionUSTAR) - copy(b.STAR().Trailer(), trailerSTAR) - case format.has(FormatUSTAR | FormatPAX): - copy(b.USTAR().Magic(), magicUSTAR) - copy(b.USTAR().Version(), versionUSTAR) - default: - panic("invalid format") - } - - // Update checksum. - // This field is special in that it is terminated by a NULL then space. - var f formatter - field := b.V7().Chksum() - chksum, _ := b.ComputeChecksum() // Possible values are 256..128776 - f.formatOctal(field[:7], chksum) // Never fails since 128776 < 262143 - field[7] = ' ' -} - -// ComputeChecksum computes the checksum for the header block. -// POSIX specifies a sum of the unsigned byte values, but the Sun tar used -// signed byte values. -// We compute and return both. -func (b *block) ComputeChecksum() (unsigned, signed int64) { - for i, c := range b { - if 148 <= i && i < 156 { - c = ' ' // Treat the checksum field itself as all spaces. - } - unsigned += int64(c) - signed += int64(int8(c)) - } - return unsigned, signed -} - -// Reset clears the block with all zeros. -func (b *block) Reset() { - *b = block{} -} - -type headerV7 [blockSize]byte - -func (h *headerV7) Name() []byte { return h[000:][:100] } -func (h *headerV7) Mode() []byte { return h[100:][:8] } -func (h *headerV7) UID() []byte { return h[108:][:8] } -func (h *headerV7) GID() []byte { return h[116:][:8] } -func (h *headerV7) Size() []byte { return h[124:][:12] } -func (h *headerV7) ModTime() []byte { return h[136:][:12] } -func (h *headerV7) Chksum() []byte { return h[148:][:8] } -func (h *headerV7) TypeFlag() []byte { return h[156:][:1] } -func (h *headerV7) LinkName() []byte { return h[157:][:100] } - -type headerGNU [blockSize]byte - -func (h *headerGNU) V7() *headerV7 { return (*headerV7)(h) } -func (h *headerGNU) Magic() []byte { return h[257:][:6] } -func (h *headerGNU) Version() []byte { return h[263:][:2] } -func (h *headerGNU) UserName() []byte { return h[265:][:32] } -func (h *headerGNU) GroupName() []byte { return h[297:][:32] } -func (h *headerGNU) DevMajor() []byte { return h[329:][:8] } -func (h *headerGNU) DevMinor() []byte { return h[337:][:8] } -func (h *headerGNU) AccessTime() []byte { return h[345:][:12] } -func (h *headerGNU) ChangeTime() []byte { return h[357:][:12] } -func (h *headerGNU) Sparse() sparseArray { return (sparseArray)(h[386:][:24*4+1]) } -func (h *headerGNU) RealSize() []byte { return h[483:][:12] } - -type headerSTAR [blockSize]byte - -func (h *headerSTAR) V7() *headerV7 { return (*headerV7)(h) } -func (h *headerSTAR) Magic() []byte { return h[257:][:6] } -func (h *headerSTAR) Version() []byte { return h[263:][:2] } -func (h *headerSTAR) UserName() []byte { return h[265:][:32] } -func (h *headerSTAR) GroupName() []byte { return h[297:][:32] } -func (h *headerSTAR) DevMajor() []byte { return h[329:][:8] } -func (h *headerSTAR) DevMinor() []byte { return h[337:][:8] } -func (h *headerSTAR) Prefix() []byte { return h[345:][:131] } -func (h *headerSTAR) AccessTime() []byte { return h[476:][:12] } -func (h *headerSTAR) ChangeTime() []byte { return h[488:][:12] } -func (h *headerSTAR) Trailer() []byte { return h[508:][:4] } - -type headerUSTAR [blockSize]byte - -func (h *headerUSTAR) V7() *headerV7 { return (*headerV7)(h) } -func (h *headerUSTAR) Magic() []byte { return h[257:][:6] } -func (h *headerUSTAR) Version() []byte { return h[263:][:2] } -func (h *headerUSTAR) UserName() []byte { return h[265:][:32] } -func (h *headerUSTAR) GroupName() []byte { return h[297:][:32] } -func (h *headerUSTAR) DevMajor() []byte { return h[329:][:8] } -func (h *headerUSTAR) DevMinor() []byte { return h[337:][:8] } -func (h *headerUSTAR) Prefix() []byte { return h[345:][:155] } - -type sparseArray []byte - -func (s sparseArray) Entry(i int) sparseElem { return (sparseElem)(s[i*24:]) } -func (s sparseArray) IsExtended() []byte { return s[24*s.MaxEntries():][:1] } -func (s sparseArray) MaxEntries() int { return len(s) / 24 } - -type sparseElem []byte - -func (s sparseElem) Offset() []byte { return s[00:][:12] } -func (s sparseElem) Length() []byte { return s[12:][:12] } diff --git a/vendor/github.com/vbatts/tar-split/archive/tar/reader.go b/vendor/github.com/vbatts/tar-split/archive/tar/reader.go deleted file mode 100644 index fcf321553..000000000 --- a/vendor/github.com/vbatts/tar-split/archive/tar/reader.go +++ /dev/null @@ -1,925 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tar - -import ( - "bytes" - "io" - "io/ioutil" - "strconv" - "strings" - "time" -) - -// Reader provides sequential access to the contents of a tar archive. -// Reader.Next advances to the next file in the archive (including the first), -// and then Reader can be treated as an io.Reader to access the file's data. -type Reader struct { - r io.Reader - pad int64 // Amount of padding (ignored) after current file entry - curr fileReader // Reader for current file entry - blk block // Buffer to use as temporary local storage - - // err is a persistent error. - // It is only the responsibility of every exported method of Reader to - // ensure that this error is sticky. - err error - - RawAccounting bool // Whether to enable the access needed to reassemble the tar from raw bytes. Some performance/memory hit for this. - rawBytes *bytes.Buffer // last raw bits -} - -type fileReader interface { - io.Reader - fileState - - WriteTo(io.Writer) (int64, error) -} - -// RawBytes accesses the raw bytes of the archive, apart from the file payload itself. -// This includes the header and padding. -// -// # This call resets the current rawbytes buffer -// -// Only when RawAccounting is enabled, otherwise this returns nil -func (tr *Reader) RawBytes() []byte { - if !tr.RawAccounting { - return nil - } - if tr.rawBytes == nil { - tr.rawBytes = bytes.NewBuffer(nil) - } - defer tr.rawBytes.Reset() // if we've read them, then flush them. - - return tr.rawBytes.Bytes() - -} - -// NewReader creates a new Reader reading from r. -func NewReader(r io.Reader) *Reader { - return &Reader{r: r, curr: ®FileReader{r, 0}} -} - -// Next advances to the next entry in the tar archive. -// The Header.Size determines how many bytes can be read for the next file. -// Any remaining data in the current file is automatically discarded. -// -// io.EOF is returned at the end of the input. -func (tr *Reader) Next() (*Header, error) { - if tr.err != nil { - return nil, tr.err - } - hdr, err := tr.next() - tr.err = err - return hdr, err -} - -func (tr *Reader) next() (*Header, error) { - var paxHdrs map[string]string - var gnuLongName, gnuLongLink string - - if tr.RawAccounting { - if tr.rawBytes == nil { - tr.rawBytes = bytes.NewBuffer(nil) - } else { - tr.rawBytes.Reset() - } - } - - // Externally, Next iterates through the tar archive as if it is a series of - // files. Internally, the tar format often uses fake "files" to add meta - // data that describes the next file. These meta data "files" should not - // normally be visible to the outside. As such, this loop iterates through - // one or more "header files" until it finds a "normal file". - format := FormatUSTAR | FormatPAX | FormatGNU - for { - // Discard the remainder of the file and any padding. - if err := discard(tr, tr.curr.PhysicalRemaining()); err != nil { - return nil, err - } - n, err := tryReadFull(tr.r, tr.blk[:tr.pad]) - if err != nil { - return nil, err - } - if tr.RawAccounting { - tr.rawBytes.Write(tr.blk[:n]) - } - tr.pad = 0 - - hdr, rawHdr, err := tr.readHeader() - if err != nil { - return nil, err - } - if err := tr.handleRegularFile(hdr); err != nil { - return nil, err - } - format.mayOnlyBe(hdr.Format) - - // Check for PAX/GNU special headers and files. - switch hdr.Typeflag { - case TypeXHeader, TypeXGlobalHeader: - format.mayOnlyBe(FormatPAX) - paxHdrs, err = parsePAX(tr) - if err != nil { - return nil, err - } - if hdr.Typeflag == TypeXGlobalHeader { - if err = mergePAX(hdr, paxHdrs); err != nil { - return nil, err - } - return &Header{ - Name: hdr.Name, - Typeflag: hdr.Typeflag, - Xattrs: hdr.Xattrs, - PAXRecords: hdr.PAXRecords, - Format: format, - }, nil - } - continue // This is a meta header affecting the next header - case TypeGNULongName, TypeGNULongLink: - format.mayOnlyBe(FormatGNU) - realname, err := ioutil.ReadAll(tr) - if err != nil { - return nil, err - } - - if tr.RawAccounting { - tr.rawBytes.Write(realname) - } - - var p parser - switch hdr.Typeflag { - case TypeGNULongName: - gnuLongName = p.parseString(realname) - case TypeGNULongLink: - gnuLongLink = p.parseString(realname) - } - continue // This is a meta header affecting the next header - default: - // The old GNU sparse format is handled here since it is technically - // just a regular file with additional attributes. - - if err := mergePAX(hdr, paxHdrs); err != nil { - return nil, err - } - if gnuLongName != "" { - hdr.Name = gnuLongName - } - if gnuLongLink != "" { - hdr.Linkname = gnuLongLink - } - if hdr.Typeflag == TypeRegA { - if strings.HasSuffix(hdr.Name, "/") { - hdr.Typeflag = TypeDir // Legacy archives use trailing slash for directories - } else { - hdr.Typeflag = TypeReg - } - } - - // The extended headers may have updated the size. - // Thus, setup the regFileReader again after merging PAX headers. - if err := tr.handleRegularFile(hdr); err != nil { - return nil, err - } - - // Sparse formats rely on being able to read from the logical data - // section; there must be a preceding call to handleRegularFile. - if err := tr.handleSparseFile(hdr, rawHdr); err != nil { - return nil, err - } - - // Set the final guess at the format. - if format.has(FormatUSTAR) && format.has(FormatPAX) { - format.mayOnlyBe(FormatUSTAR) - } - hdr.Format = format - return hdr, nil // This is a file, so stop - } - } -} - -// handleRegularFile sets up the current file reader and padding such that it -// can only read the following logical data section. It will properly handle -// special headers that contain no data section. -func (tr *Reader) handleRegularFile(hdr *Header) error { - nb := hdr.Size - if isHeaderOnlyType(hdr.Typeflag) { - nb = 0 - } - if nb < 0 { - return ErrHeader - } - - tr.pad = blockPadding(nb) - tr.curr = ®FileReader{r: tr.r, nb: nb} - return nil -} - -// handleSparseFile checks if the current file is a sparse format of any type -// and sets the curr reader appropriately. -func (tr *Reader) handleSparseFile(hdr *Header, rawHdr *block) error { - var spd sparseDatas - var err error - if hdr.Typeflag == TypeGNUSparse { - spd, err = tr.readOldGNUSparseMap(hdr, rawHdr) - } else { - spd, err = tr.readGNUSparsePAXHeaders(hdr) - } - - // If sp is non-nil, then this is a sparse file. - // Note that it is possible for len(sp) == 0. - if err == nil && spd != nil { - if isHeaderOnlyType(hdr.Typeflag) || !validateSparseEntries(spd, hdr.Size) { - return ErrHeader - } - sph := invertSparseEntries(spd, hdr.Size) - tr.curr = &sparseFileReader{tr.curr, sph, 0} - } - return err -} - -// readGNUSparsePAXHeaders checks the PAX headers for GNU sparse headers. -// If they are found, then this function reads the sparse map and returns it. -// This assumes that 0.0 headers have already been converted to 0.1 headers -// by the PAX header parsing logic. -func (tr *Reader) readGNUSparsePAXHeaders(hdr *Header) (sparseDatas, error) { - // Identify the version of GNU headers. - var is1x0 bool - major, minor := hdr.PAXRecords[paxGNUSparseMajor], hdr.PAXRecords[paxGNUSparseMinor] - switch { - case major == "0" && (minor == "0" || minor == "1"): - is1x0 = false - case major == "1" && minor == "0": - is1x0 = true - case major != "" || minor != "": - return nil, nil // Unknown GNU sparse PAX version - case hdr.PAXRecords[paxGNUSparseMap] != "": - is1x0 = false // 0.0 and 0.1 did not have explicit version records, so guess - default: - return nil, nil // Not a PAX format GNU sparse file. - } - hdr.Format.mayOnlyBe(FormatPAX) - - // Update hdr from GNU sparse PAX headers. - if name := hdr.PAXRecords[paxGNUSparseName]; name != "" { - hdr.Name = name - } - size := hdr.PAXRecords[paxGNUSparseSize] - if size == "" { - size = hdr.PAXRecords[paxGNUSparseRealSize] - } - if size != "" { - n, err := strconv.ParseInt(size, 10, 64) - if err != nil { - return nil, ErrHeader - } - hdr.Size = n - } - - // Read the sparse map according to the appropriate format. - if is1x0 { - return readGNUSparseMap1x0(tr.curr) - } - return readGNUSparseMap0x1(hdr.PAXRecords) -} - -// mergePAX merges paxHdrs into hdr for all relevant fields of Header. -func mergePAX(hdr *Header, paxHdrs map[string]string) (err error) { - for k, v := range paxHdrs { - if v == "" { - continue // Keep the original USTAR value - } - var id64 int64 - switch k { - case paxPath: - hdr.Name = v - case paxLinkpath: - hdr.Linkname = v - case paxUname: - hdr.Uname = v - case paxGname: - hdr.Gname = v - case paxUid: - id64, err = strconv.ParseInt(v, 10, 64) - hdr.Uid = int(id64) // Integer overflow possible - case paxGid: - id64, err = strconv.ParseInt(v, 10, 64) - hdr.Gid = int(id64) // Integer overflow possible - case paxAtime: - hdr.AccessTime, err = parsePAXTime(v) - case paxMtime: - hdr.ModTime, err = parsePAXTime(v) - case paxCtime: - hdr.ChangeTime, err = parsePAXTime(v) - case paxSize: - hdr.Size, err = strconv.ParseInt(v, 10, 64) - default: - if strings.HasPrefix(k, paxSchilyXattr) { - if hdr.Xattrs == nil { - hdr.Xattrs = make(map[string]string) - } - hdr.Xattrs[k[len(paxSchilyXattr):]] = v - } - } - if err != nil { - return ErrHeader - } - } - hdr.PAXRecords = paxHdrs - return nil -} - -// parsePAX parses PAX headers. -// If an extended header (type 'x') is invalid, ErrHeader is returned -func parsePAX(r io.Reader) (map[string]string, error) { - buf, err := ioutil.ReadAll(r) - if err != nil { - return nil, err - } - // leaving this function for io.Reader makes it more testable - if tr, ok := r.(*Reader); ok && tr.RawAccounting { - if _, err = tr.rawBytes.Write(buf); err != nil { - return nil, err - } - } - sbuf := string(buf) - - // For GNU PAX sparse format 0.0 support. - // This function transforms the sparse format 0.0 headers into format 0.1 - // headers since 0.0 headers were not PAX compliant. - var sparseMap []string - - paxHdrs := make(map[string]string) - for len(sbuf) > 0 { - key, value, residual, err := parsePAXRecord(sbuf) - if err != nil { - return nil, ErrHeader - } - sbuf = residual - - switch key { - case paxGNUSparseOffset, paxGNUSparseNumBytes: - // Validate sparse header order and value. - if (len(sparseMap)%2 == 0 && key != paxGNUSparseOffset) || - (len(sparseMap)%2 == 1 && key != paxGNUSparseNumBytes) || - strings.Contains(value, ",") { - return nil, ErrHeader - } - sparseMap = append(sparseMap, value) - default: - paxHdrs[key] = value - } - } - if len(sparseMap) > 0 { - paxHdrs[paxGNUSparseMap] = strings.Join(sparseMap, ",") - } - return paxHdrs, nil -} - -// readHeader reads the next block header and assumes that the underlying reader -// is already aligned to a block boundary. It returns the raw block of the -// header in case further processing is required. -// -// The err will be set to io.EOF only when one of the following occurs: -// - Exactly 0 bytes are read and EOF is hit. -// - Exactly 1 block of zeros is read and EOF is hit. -// - At least 2 blocks of zeros are read. -func (tr *Reader) readHeader() (*Header, *block, error) { - // Two blocks of zero bytes marks the end of the archive. - n, err := io.ReadFull(tr.r, tr.blk[:]) - if tr.RawAccounting && (err == nil || err == io.EOF) { - tr.rawBytes.Write(tr.blk[:n]) - } - if err != nil { - return nil, nil, err // EOF is okay here; exactly 0 bytes read - } - - if bytes.Equal(tr.blk[:], zeroBlock[:]) { - n, err = io.ReadFull(tr.r, tr.blk[:]) - if tr.RawAccounting && (err == nil || err == io.EOF) { - tr.rawBytes.Write(tr.blk[:n]) - } - if err != nil { - return nil, nil, err // EOF is okay here; exactly 1 block of zeros read - } - if bytes.Equal(tr.blk[:], zeroBlock[:]) { - return nil, nil, io.EOF // normal EOF; exactly 2 block of zeros read - } - return nil, nil, ErrHeader // Zero block and then non-zero block - } - - // Verify the header matches a known format. - format := tr.blk.GetFormat() - if format == FormatUnknown { - return nil, nil, ErrHeader - } - - var p parser - hdr := new(Header) - - // Unpack the V7 header. - v7 := tr.blk.V7() - hdr.Typeflag = v7.TypeFlag()[0] - hdr.Name = p.parseString(v7.Name()) - hdr.Linkname = p.parseString(v7.LinkName()) - hdr.Size = p.parseNumeric(v7.Size()) - hdr.Mode = p.parseNumeric(v7.Mode()) - hdr.Uid = int(p.parseNumeric(v7.UID())) - hdr.Gid = int(p.parseNumeric(v7.GID())) - hdr.ModTime = time.Unix(p.parseNumeric(v7.ModTime()), 0) - - // Unpack format specific fields. - if format > formatV7 { - ustar := tr.blk.USTAR() - hdr.Uname = p.parseString(ustar.UserName()) - hdr.Gname = p.parseString(ustar.GroupName()) - hdr.Devmajor = p.parseNumeric(ustar.DevMajor()) - hdr.Devminor = p.parseNumeric(ustar.DevMinor()) - - var prefix string - switch { - case format.has(FormatUSTAR | FormatPAX): - hdr.Format = format - ustar := tr.blk.USTAR() - prefix = p.parseString(ustar.Prefix()) - - // For Format detection, check if block is properly formatted since - // the parser is more liberal than what USTAR actually permits. - notASCII := func(r rune) bool { return r >= 0x80 } - if bytes.IndexFunc(tr.blk[:], notASCII) >= 0 { - hdr.Format = FormatUnknown // Non-ASCII characters in block. - } - nul := func(b []byte) bool { return int(b[len(b)-1]) == 0 } - if !(nul(v7.Size()) && nul(v7.Mode()) && nul(v7.UID()) && nul(v7.GID()) && - nul(v7.ModTime()) && nul(ustar.DevMajor()) && nul(ustar.DevMinor())) { - hdr.Format = FormatUnknown // Numeric fields must end in NUL - } - case format.has(formatSTAR): - star := tr.blk.STAR() - prefix = p.parseString(star.Prefix()) - hdr.AccessTime = time.Unix(p.parseNumeric(star.AccessTime()), 0) - hdr.ChangeTime = time.Unix(p.parseNumeric(star.ChangeTime()), 0) - case format.has(FormatGNU): - hdr.Format = format - var p2 parser - gnu := tr.blk.GNU() - if b := gnu.AccessTime(); b[0] != 0 { - hdr.AccessTime = time.Unix(p2.parseNumeric(b), 0) - } - if b := gnu.ChangeTime(); b[0] != 0 { - hdr.ChangeTime = time.Unix(p2.parseNumeric(b), 0) - } - - // Prior to Go1.8, the Writer had a bug where it would output - // an invalid tar file in certain rare situations because the logic - // incorrectly believed that the old GNU format had a prefix field. - // This is wrong and leads to an output file that mangles the - // atime and ctime fields, which are often left unused. - // - // In order to continue reading tar files created by former, buggy - // versions of Go, we skeptically parse the atime and ctime fields. - // If we are unable to parse them and the prefix field looks like - // an ASCII string, then we fallback on the pre-Go1.8 behavior - // of treating these fields as the USTAR prefix field. - // - // Note that this will not use the fallback logic for all possible - // files generated by a pre-Go1.8 toolchain. If the generated file - // happened to have a prefix field that parses as valid - // atime and ctime fields (e.g., when they are valid octal strings), - // then it is impossible to distinguish between an valid GNU file - // and an invalid pre-Go1.8 file. - // - // See https://golang.org/issues/12594 - // See https://golang.org/issues/21005 - if p2.err != nil { - hdr.AccessTime, hdr.ChangeTime = time.Time{}, time.Time{} - ustar := tr.blk.USTAR() - if s := p.parseString(ustar.Prefix()); isASCII(s) { - prefix = s - } - hdr.Format = FormatUnknown // Buggy file is not GNU - } - } - if len(prefix) > 0 { - hdr.Name = prefix + "/" + hdr.Name - } - } - return hdr, &tr.blk, p.err -} - -// readOldGNUSparseMap reads the sparse map from the old GNU sparse format. -// The sparse map is stored in the tar header if it's small enough. -// If it's larger than four entries, then one or more extension headers are used -// to store the rest of the sparse map. -// -// The Header.Size does not reflect the size of any extended headers used. -// Thus, this function will read from the raw io.Reader to fetch extra headers. -// This method mutates blk in the process. -func (tr *Reader) readOldGNUSparseMap(hdr *Header, blk *block) (sparseDatas, error) { - // Make sure that the input format is GNU. - // Unfortunately, the STAR format also has a sparse header format that uses - // the same type flag but has a completely different layout. - if blk.GetFormat() != FormatGNU { - return nil, ErrHeader - } - hdr.Format.mayOnlyBe(FormatGNU) - - var p parser - hdr.Size = p.parseNumeric(blk.GNU().RealSize()) - if p.err != nil { - return nil, p.err - } - s := blk.GNU().Sparse() - spd := make(sparseDatas, 0, s.MaxEntries()) - for { - for i := 0; i < s.MaxEntries(); i++ { - // This termination condition is identical to GNU and BSD tar. - if s.Entry(i).Offset()[0] == 0x00 { - break // Don't return, need to process extended headers (even if empty) - } - offset := p.parseNumeric(s.Entry(i).Offset()) - length := p.parseNumeric(s.Entry(i).Length()) - if p.err != nil { - return nil, p.err - } - spd = append(spd, sparseEntry{Offset: offset, Length: length}) - } - - if s.IsExtended()[0] > 0 { - // There are more entries. Read an extension header and parse its entries. - if _, err := mustReadFull(tr.r, blk[:]); err != nil { - return nil, err - } - if tr.RawAccounting { - tr.rawBytes.Write(blk[:]) - } - s = blk.Sparse() - continue - } - return spd, nil // Done - } -} - -// readGNUSparseMap1x0 reads the sparse map as stored in GNU's PAX sparse format -// version 1.0. The format of the sparse map consists of a series of -// newline-terminated numeric fields. The first field is the number of entries -// and is always present. Following this are the entries, consisting of two -// fields (offset, length). This function must stop reading at the end -// boundary of the block containing the last newline. -// -// Note that the GNU manual says that numeric values should be encoded in octal -// format. However, the GNU tar utility itself outputs these values in decimal. -// As such, this library treats values as being encoded in decimal. -func readGNUSparseMap1x0(r io.Reader) (sparseDatas, error) { - var ( - cntNewline int64 - buf bytes.Buffer - blk block - ) - - // feedTokens copies data in blocks from r into buf until there are - // at least cnt newlines in buf. It will not read more blocks than needed. - feedTokens := func(n int64) error { - for cntNewline < n { - if _, err := mustReadFull(r, blk[:]); err != nil { - return err - } - buf.Write(blk[:]) - for _, c := range blk { - if c == '\n' { - cntNewline++ - } - } - } - return nil - } - - // nextToken gets the next token delimited by a newline. This assumes that - // at least one newline exists in the buffer. - nextToken := func() string { - cntNewline-- - tok, _ := buf.ReadString('\n') - return strings.TrimRight(tok, "\n") - } - - // Parse for the number of entries. - // Use integer overflow resistant math to check this. - if err := feedTokens(1); err != nil { - return nil, err - } - numEntries, err := strconv.ParseInt(nextToken(), 10, 0) // Intentionally parse as native int - if err != nil || numEntries < 0 || int(2*numEntries) < int(numEntries) { - return nil, ErrHeader - } - - // Parse for all member entries. - // numEntries is trusted after this since a potential attacker must have - // committed resources proportional to what this library used. - if err := feedTokens(2 * numEntries); err != nil { - return nil, err - } - spd := make(sparseDatas, 0, numEntries) - for i := int64(0); i < numEntries; i++ { - offset, err1 := strconv.ParseInt(nextToken(), 10, 64) - length, err2 := strconv.ParseInt(nextToken(), 10, 64) - if err1 != nil || err2 != nil { - return nil, ErrHeader - } - spd = append(spd, sparseEntry{Offset: offset, Length: length}) - } - return spd, nil -} - -// readGNUSparseMap0x1 reads the sparse map as stored in GNU's PAX sparse format -// version 0.1. The sparse map is stored in the PAX headers. -func readGNUSparseMap0x1(paxHdrs map[string]string) (sparseDatas, error) { - // Get number of entries. - // Use integer overflow resistant math to check this. - numEntriesStr := paxHdrs[paxGNUSparseNumBlocks] - numEntries, err := strconv.ParseInt(numEntriesStr, 10, 0) // Intentionally parse as native int - if err != nil || numEntries < 0 || int(2*numEntries) < int(numEntries) { - return nil, ErrHeader - } - - // There should be two numbers in sparseMap for each entry. - sparseMap := strings.Split(paxHdrs[paxGNUSparseMap], ",") - if len(sparseMap) == 1 && sparseMap[0] == "" { - sparseMap = sparseMap[:0] - } - if int64(len(sparseMap)) != 2*numEntries { - return nil, ErrHeader - } - - // Loop through the entries in the sparse map. - // numEntries is trusted now. - spd := make(sparseDatas, 0, numEntries) - for len(sparseMap) >= 2 { - offset, err1 := strconv.ParseInt(sparseMap[0], 10, 64) - length, err2 := strconv.ParseInt(sparseMap[1], 10, 64) - if err1 != nil || err2 != nil { - return nil, ErrHeader - } - spd = append(spd, sparseEntry{Offset: offset, Length: length}) - sparseMap = sparseMap[2:] - } - return spd, nil -} - -// Read reads from the current file in the tar archive. -// It returns (0, io.EOF) when it reaches the end of that file, -// until Next is called to advance to the next file. -// -// If the current file is sparse, then the regions marked as a hole -// are read back as NUL-bytes. -// -// Calling Read on special types like TypeLink, TypeSymlink, TypeChar, -// TypeBlock, TypeDir, and TypeFifo returns (0, io.EOF) regardless of what -// the Header.Size claims. -func (tr *Reader) Read(b []byte) (int, error) { - if tr.err != nil { - return 0, tr.err - } - n, err := tr.curr.Read(b) - if err != nil && err != io.EOF { - tr.err = err - } - return n, err -} - -// writeTo writes the content of the current file to w. -// The bytes written matches the number of remaining bytes in the current file. -// -// If the current file is sparse and w is an io.WriteSeeker, -// then writeTo uses Seek to skip past holes defined in Header.SparseHoles, -// assuming that skipped regions are filled with NULs. -// This always writes the last byte to ensure w is the right size. -// -// TODO(dsnet): Re-export this when adding sparse file support. -// See https://golang.org/issue/22735 -func (tr *Reader) writeTo(w io.Writer) (int64, error) { - if tr.err != nil { - return 0, tr.err - } - n, err := tr.curr.WriteTo(w) - if err != nil { - tr.err = err - } - return n, err -} - -// regFileReader is a fileReader for reading data from a regular file entry. -type regFileReader struct { - r io.Reader // Underlying Reader - nb int64 // Number of remaining bytes to read -} - -func (fr *regFileReader) Read(b []byte) (n int, err error) { - if int64(len(b)) > fr.nb { - b = b[:fr.nb] - } - if len(b) > 0 { - n, err = fr.r.Read(b) - fr.nb -= int64(n) - } - switch { - case err == io.EOF && fr.nb > 0: - return n, io.ErrUnexpectedEOF - case err == nil && fr.nb == 0: - return n, io.EOF - default: - return n, err - } -} - -func (fr *regFileReader) WriteTo(w io.Writer) (int64, error) { - return io.Copy(w, struct{ io.Reader }{fr}) -} - -func (fr regFileReader) LogicalRemaining() int64 { - return fr.nb -} - -func (fr regFileReader) PhysicalRemaining() int64 { - return fr.nb -} - -// sparseFileReader is a fileReader for reading data from a sparse file entry. -type sparseFileReader struct { - fr fileReader // Underlying fileReader - sp sparseHoles // Normalized list of sparse holes - pos int64 // Current position in sparse file -} - -func (sr *sparseFileReader) Read(b []byte) (n int, err error) { - finished := int64(len(b)) >= sr.LogicalRemaining() - if finished { - b = b[:sr.LogicalRemaining()] - } - - b0 := b - endPos := sr.pos + int64(len(b)) - for endPos > sr.pos && err == nil { - var nf int // Bytes read in fragment - holeStart, holeEnd := sr.sp[0].Offset, sr.sp[0].endOffset() - if sr.pos < holeStart { // In a data fragment - bf := b[:min(int64(len(b)), holeStart-sr.pos)] - nf, err = tryReadFull(sr.fr, bf) - } else { // In a hole fragment - bf := b[:min(int64(len(b)), holeEnd-sr.pos)] - nf, err = tryReadFull(zeroReader{}, bf) - } - b = b[nf:] - sr.pos += int64(nf) - if sr.pos >= holeEnd && len(sr.sp) > 1 { - sr.sp = sr.sp[1:] // Ensure last fragment always remains - } - } - - n = len(b0) - len(b) - switch { - case err == io.EOF: - return n, errMissData // Less data in dense file than sparse file - case err != nil: - return n, err - case sr.LogicalRemaining() == 0 && sr.PhysicalRemaining() > 0: - return n, errUnrefData // More data in dense file than sparse file - case finished: - return n, io.EOF - default: - return n, nil - } -} - -func (sr *sparseFileReader) WriteTo(w io.Writer) (n int64, err error) { - ws, ok := w.(io.WriteSeeker) - if ok { - if _, err := ws.Seek(0, io.SeekCurrent); err != nil { - ok = false // Not all io.Seeker can really seek - } - } - if !ok { - return io.Copy(w, struct{ io.Reader }{sr}) - } - - var writeLastByte bool - pos0 := sr.pos - for sr.LogicalRemaining() > 0 && !writeLastByte && err == nil { - var nf int64 // Size of fragment - holeStart, holeEnd := sr.sp[0].Offset, sr.sp[0].endOffset() - if sr.pos < holeStart { // In a data fragment - nf = holeStart - sr.pos - nf, err = io.CopyN(ws, sr.fr, nf) - } else { // In a hole fragment - nf = holeEnd - sr.pos - if sr.PhysicalRemaining() == 0 { - writeLastByte = true - nf-- - } - _, err = ws.Seek(nf, io.SeekCurrent) - } - sr.pos += nf - if sr.pos >= holeEnd && len(sr.sp) > 1 { - sr.sp = sr.sp[1:] // Ensure last fragment always remains - } - } - - // If the last fragment is a hole, then seek to 1-byte before EOF, and - // write a single byte to ensure the file is the right size. - if writeLastByte && err == nil { - _, err = ws.Write([]byte{0}) - sr.pos++ - } - - n = sr.pos - pos0 - switch { - case err == io.EOF: - return n, errMissData // Less data in dense file than sparse file - case err != nil: - return n, err - case sr.LogicalRemaining() == 0 && sr.PhysicalRemaining() > 0: - return n, errUnrefData // More data in dense file than sparse file - default: - return n, nil - } -} - -func (sr sparseFileReader) LogicalRemaining() int64 { - return sr.sp[len(sr.sp)-1].endOffset() - sr.pos -} -func (sr sparseFileReader) PhysicalRemaining() int64 { - return sr.fr.PhysicalRemaining() -} - -type zeroReader struct{} - -func (zeroReader) Read(b []byte) (int, error) { - for i := range b { - b[i] = 0 - } - return len(b), nil -} - -// mustReadFull is like io.ReadFull except it returns -// io.ErrUnexpectedEOF when io.EOF is hit before len(b) bytes are read. -func mustReadFull(r io.Reader, b []byte) (int, error) { - n, err := tryReadFull(r, b) - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - return n, err -} - -// tryReadFull is like io.ReadFull except it returns -// io.EOF when it is hit before len(b) bytes are read. -func tryReadFull(r io.Reader, b []byte) (n int, err error) { - for len(b) > n && err == nil { - var nn int - nn, err = r.Read(b[n:]) - n += nn - } - if len(b) == n && err == io.EOF { - err = nil - } - return n, err -} - -// discard skips n bytes in r, reporting an error if unable to do so. -func discard(tr *Reader, n int64) error { - var seekSkipped, copySkipped int64 - var err error - r := tr.r - if tr.RawAccounting { - - copySkipped, err = io.CopyN(tr.rawBytes, tr.r, n) - goto out - } - - // If possible, Seek to the last byte before the end of the data section. - // Do this because Seek is often lazy about reporting errors; this will mask - // the fact that the stream may be truncated. We can rely on the - // io.CopyN done shortly afterwards to trigger any IO errors. - if sr, ok := r.(io.Seeker); ok && n > 1 { - // Not all io.Seeker can actually Seek. For example, os.Stdin implements - // io.Seeker, but calling Seek always returns an error and performs - // no action. Thus, we try an innocent seek to the current position - // to see if Seek is really supported. - pos1, err := sr.Seek(0, io.SeekCurrent) - if pos1 >= 0 && err == nil { - // Seek seems supported, so perform the real Seek. - pos2, err := sr.Seek(n-1, io.SeekCurrent) - if pos2 < 0 || err != nil { - return err - } - seekSkipped = pos2 - pos1 - } - } - - copySkipped, err = io.CopyN(ioutil.Discard, r, n-seekSkipped) -out: - if err == io.EOF && seekSkipped+copySkipped < n { - err = io.ErrUnexpectedEOF - } - return err -} diff --git a/vendor/github.com/vbatts/tar-split/archive/tar/stat_actime1.go b/vendor/github.com/vbatts/tar-split/archive/tar/stat_actime1.go deleted file mode 100644 index cf9cc79c5..000000000 --- a/vendor/github.com/vbatts/tar-split/archive/tar/stat_actime1.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build linux dragonfly openbsd solaris - -package tar - -import ( - "syscall" - "time" -) - -func statAtime(st *syscall.Stat_t) time.Time { - return time.Unix(st.Atim.Unix()) -} - -func statCtime(st *syscall.Stat_t) time.Time { - return time.Unix(st.Ctim.Unix()) -} diff --git a/vendor/github.com/vbatts/tar-split/archive/tar/stat_actime2.go b/vendor/github.com/vbatts/tar-split/archive/tar/stat_actime2.go deleted file mode 100644 index 6f17dbe30..000000000 --- a/vendor/github.com/vbatts/tar-split/archive/tar/stat_actime2.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin freebsd netbsd - -package tar - -import ( - "syscall" - "time" -) - -func statAtime(st *syscall.Stat_t) time.Time { - return time.Unix(st.Atimespec.Unix()) -} - -func statCtime(st *syscall.Stat_t) time.Time { - return time.Unix(st.Ctimespec.Unix()) -} diff --git a/vendor/github.com/vbatts/tar-split/archive/tar/stat_unix.go b/vendor/github.com/vbatts/tar-split/archive/tar/stat_unix.go deleted file mode 100644 index 868105f33..000000000 --- a/vendor/github.com/vbatts/tar-split/archive/tar/stat_unix.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build linux darwin dragonfly freebsd openbsd netbsd solaris - -package tar - -import ( - "os" - "os/user" - "runtime" - "strconv" - "sync" - "syscall" -) - -func init() { - sysStat = statUnix -} - -// userMap and groupMap caches UID and GID lookups for performance reasons. -// The downside is that renaming uname or gname by the OS never takes effect. -var userMap, groupMap sync.Map // map[int]string - -func statUnix(fi os.FileInfo, h *Header) error { - sys, ok := fi.Sys().(*syscall.Stat_t) - if !ok { - return nil - } - h.Uid = int(sys.Uid) - h.Gid = int(sys.Gid) - - // Best effort at populating Uname and Gname. - // The os/user functions may fail for any number of reasons - // (not implemented on that platform, cgo not enabled, etc). - if u, ok := userMap.Load(h.Uid); ok { - h.Uname = u.(string) - } else if u, err := user.LookupId(strconv.Itoa(h.Uid)); err == nil { - h.Uname = u.Username - userMap.Store(h.Uid, h.Uname) - } - if g, ok := groupMap.Load(h.Gid); ok { - h.Gname = g.(string) - } else if g, err := user.LookupGroupId(strconv.Itoa(h.Gid)); err == nil { - h.Gname = g.Name - groupMap.Store(h.Gid, h.Gname) - } - - h.AccessTime = statAtime(sys) - h.ChangeTime = statCtime(sys) - - // Best effort at populating Devmajor and Devminor. - if h.Typeflag == TypeChar || h.Typeflag == TypeBlock { - dev := uint64(sys.Rdev) // May be int32 or uint32 - switch runtime.GOOS { - case "linux": - // Copied from golang.org/x/sys/unix/dev_linux.go. - major := uint32((dev & 0x00000000000fff00) >> 8) - major |= uint32((dev & 0xfffff00000000000) >> 32) - minor := uint32((dev & 0x00000000000000ff) >> 0) - minor |= uint32((dev & 0x00000ffffff00000) >> 12) - h.Devmajor, h.Devminor = int64(major), int64(minor) - case "darwin": - // Copied from golang.org/x/sys/unix/dev_darwin.go. - major := uint32((dev >> 24) & 0xff) - minor := uint32(dev & 0xffffff) - h.Devmajor, h.Devminor = int64(major), int64(minor) - case "dragonfly": - // Copied from golang.org/x/sys/unix/dev_dragonfly.go. - major := uint32((dev >> 8) & 0xff) - minor := uint32(dev & 0xffff00ff) - h.Devmajor, h.Devminor = int64(major), int64(minor) - case "freebsd": - // Copied from golang.org/x/sys/unix/dev_freebsd.go. - major := uint32((dev >> 8) & 0xff) - minor := uint32(dev & 0xffff00ff) - h.Devmajor, h.Devminor = int64(major), int64(minor) - case "netbsd": - // Copied from golang.org/x/sys/unix/dev_netbsd.go. - major := uint32((dev & 0x000fff00) >> 8) - minor := uint32((dev & 0x000000ff) >> 0) - minor |= uint32((dev & 0xfff00000) >> 12) - h.Devmajor, h.Devminor = int64(major), int64(minor) - case "openbsd": - // Copied from golang.org/x/sys/unix/dev_openbsd.go. - major := uint32((dev & 0x0000ff00) >> 8) - minor := uint32((dev & 0x000000ff) >> 0) - minor |= uint32((dev & 0xffff0000) >> 8) - h.Devmajor, h.Devminor = int64(major), int64(minor) - default: - // TODO: Implement solaris (see https://golang.org/issue/8106) - } - } - return nil -} diff --git a/vendor/github.com/vbatts/tar-split/archive/tar/strconv.go b/vendor/github.com/vbatts/tar-split/archive/tar/strconv.go deleted file mode 100644 index d144485a4..000000000 --- a/vendor/github.com/vbatts/tar-split/archive/tar/strconv.go +++ /dev/null @@ -1,326 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tar - -import ( - "bytes" - "fmt" - "strconv" - "strings" - "time" -) - -// hasNUL reports whether the NUL character exists within s. -func hasNUL(s string) bool { - return strings.IndexByte(s, 0) >= 0 -} - -// isASCII reports whether the input is an ASCII C-style string. -func isASCII(s string) bool { - for _, c := range s { - if c >= 0x80 || c == 0x00 { - return false - } - } - return true -} - -// toASCII converts the input to an ASCII C-style string. -// This a best effort conversion, so invalid characters are dropped. -func toASCII(s string) string { - if isASCII(s) { - return s - } - b := make([]byte, 0, len(s)) - for _, c := range s { - if c < 0x80 && c != 0x00 { - b = append(b, byte(c)) - } - } - return string(b) -} - -type parser struct { - err error // Last error seen -} - -type formatter struct { - err error // Last error seen -} - -// parseString parses bytes as a NUL-terminated C-style string. -// If a NUL byte is not found then the whole slice is returned as a string. -func (*parser) parseString(b []byte) string { - if i := bytes.IndexByte(b, 0); i >= 0 { - return string(b[:i]) - } - return string(b) -} - -// formatString copies s into b, NUL-terminating if possible. -func (f *formatter) formatString(b []byte, s string) { - if len(s) > len(b) { - f.err = ErrFieldTooLong - } - copy(b, s) - if len(s) < len(b) { - b[len(s)] = 0 - } - - // Some buggy readers treat regular files with a trailing slash - // in the V7 path field as a directory even though the full path - // recorded elsewhere (e.g., via PAX record) contains no trailing slash. - if len(s) > len(b) && b[len(b)-1] == '/' { - n := len(strings.TrimRight(s[:len(b)], "/")) - b[n] = 0 // Replace trailing slash with NUL terminator - } -} - -// fitsInBase256 reports whether x can be encoded into n bytes using base-256 -// encoding. Unlike octal encoding, base-256 encoding does not require that the -// string ends with a NUL character. Thus, all n bytes are available for output. -// -// If operating in binary mode, this assumes strict GNU binary mode; which means -// that the first byte can only be either 0x80 or 0xff. Thus, the first byte is -// equivalent to the sign bit in two's complement form. -func fitsInBase256(n int, x int64) bool { - binBits := uint(n-1) * 8 - return n >= 9 || (x >= -1< 0 && b[0]&0x80 != 0 { - // Handling negative numbers relies on the following identity: - // -a-1 == ^a - // - // If the number is negative, we use an inversion mask to invert the - // data bytes and treat the value as an unsigned number. - var inv byte // 0x00 if positive or zero, 0xff if negative - if b[0]&0x40 != 0 { - inv = 0xff - } - - var x uint64 - for i, c := range b { - c ^= inv // Inverts c only if inv is 0xff, otherwise does nothing - if i == 0 { - c &= 0x7f // Ignore signal bit in first byte - } - if (x >> 56) > 0 { - p.err = ErrHeader // Integer overflow - return 0 - } - x = x<<8 | uint64(c) - } - if (x >> 63) > 0 { - p.err = ErrHeader // Integer overflow - return 0 - } - if inv == 0xff { - return ^int64(x) - } - return int64(x) - } - - // Normal case is base-8 (octal) format. - return p.parseOctal(b) -} - -// formatNumeric encodes x into b using base-8 (octal) encoding if possible. -// Otherwise it will attempt to use base-256 (binary) encoding. -func (f *formatter) formatNumeric(b []byte, x int64) { - if fitsInOctal(len(b), x) { - f.formatOctal(b, x) - return - } - - if fitsInBase256(len(b), x) { - for i := len(b) - 1; i >= 0; i-- { - b[i] = byte(x) - x >>= 8 - } - b[0] |= 0x80 // Highest bit indicates binary format - return - } - - f.formatOctal(b, 0) // Last resort, just write zero - f.err = ErrFieldTooLong -} - -func (p *parser) parseOctal(b []byte) int64 { - // Because unused fields are filled with NULs, we need - // to skip leading NULs. Fields may also be padded with - // spaces or NULs. - // So we remove leading and trailing NULs and spaces to - // be sure. - b = bytes.Trim(b, " \x00") - - if len(b) == 0 { - return 0 - } - x, perr := strconv.ParseUint(p.parseString(b), 8, 64) - if perr != nil { - p.err = ErrHeader - } - return int64(x) -} - -func (f *formatter) formatOctal(b []byte, x int64) { - if !fitsInOctal(len(b), x) { - x = 0 // Last resort, just write zero - f.err = ErrFieldTooLong - } - - s := strconv.FormatInt(x, 8) - // Add leading zeros, but leave room for a NUL. - if n := len(b) - len(s) - 1; n > 0 { - s = strings.Repeat("0", n) + s - } - f.formatString(b, s) -} - -// fitsInOctal reports whether the integer x fits in a field n-bytes long -// using octal encoding with the appropriate NUL terminator. -func fitsInOctal(n int, x int64) bool { - octBits := uint(n-1) * 3 - return x >= 0 && (n >= 22 || x < 1<= 0 { - ss, sn = s[:pos], s[pos+1:] - } - - // Parse the seconds. - secs, err := strconv.ParseInt(ss, 10, 64) - if err != nil { - return time.Time{}, ErrHeader - } - if len(sn) == 0 { - return time.Unix(secs, 0), nil // No sub-second values - } - - // Parse the nanoseconds. - if strings.Trim(sn, "0123456789") != "" { - return time.Time{}, ErrHeader - } - if len(sn) < maxNanoSecondDigits { - sn += strings.Repeat("0", maxNanoSecondDigits-len(sn)) // Right pad - } else { - sn = sn[:maxNanoSecondDigits] // Right truncate - } - nsecs, _ := strconv.ParseInt(sn, 10, 64) // Must succeed - if len(ss) > 0 && ss[0] == '-' { - return time.Unix(secs, -1*nsecs), nil // Negative correction - } - return time.Unix(secs, nsecs), nil -} - -// formatPAXTime converts ts into a time of the form %d.%d as described in the -// PAX specification. This function is capable of negative timestamps. -func formatPAXTime(ts time.Time) (s string) { - secs, nsecs := ts.Unix(), ts.Nanosecond() - if nsecs == 0 { - return strconv.FormatInt(secs, 10) - } - - // If seconds is negative, then perform correction. - sign := "" - if secs < 0 { - sign = "-" // Remember sign - secs = -(secs + 1) // Add a second to secs - nsecs = -(nsecs - 1E9) // Take that second away from nsecs - } - return strings.TrimRight(fmt.Sprintf("%s%d.%09d", sign, secs, nsecs), "0") -} - -// parsePAXRecord parses the input PAX record string into a key-value pair. -// If parsing is successful, it will slice off the currently read record and -// return the remainder as r. -func parsePAXRecord(s string) (k, v, r string, err error) { - // The size field ends at the first space. - sp := strings.IndexByte(s, ' ') - if sp == -1 { - return "", "", s, ErrHeader - } - - // Parse the first token as a decimal integer. - n, perr := strconv.ParseInt(s[:sp], 10, 0) // Intentionally parse as native int - if perr != nil || n < 5 || int64(len(s)) < n { - return "", "", s, ErrHeader - } - - // Extract everything between the space and the final newline. - rec, nl, rem := s[sp+1:n-1], s[n-1:n], s[n:] - if nl != "\n" { - return "", "", s, ErrHeader - } - - // The first equals separates the key from the value. - eq := strings.IndexByte(rec, '=') - if eq == -1 { - return "", "", s, ErrHeader - } - k, v = rec[:eq], rec[eq+1:] - - if !validPAXRecord(k, v) { - return "", "", s, ErrHeader - } - return k, v, rem, nil -} - -// formatPAXRecord formats a single PAX record, prefixing it with the -// appropriate length. -func formatPAXRecord(k, v string) (string, error) { - if !validPAXRecord(k, v) { - return "", ErrHeader - } - - const padding = 3 // Extra padding for ' ', '=', and '\n' - size := len(k) + len(v) + padding - size += len(strconv.Itoa(size)) - record := strconv.Itoa(size) + " " + k + "=" + v + "\n" - - // Final adjustment if adding size field increased the record size. - if len(record) != size { - size = len(record) - record = strconv.Itoa(size) + " " + k + "=" + v + "\n" - } - return record, nil -} - -// validPAXRecord reports whether the key-value pair is valid where each -// record is formatted as: -// "%d %s=%s\n" % (size, key, value) -// -// Keys and values should be UTF-8, but the number of bad writers out there -// forces us to be a more liberal. -// Thus, we only reject all keys with NUL, and only reject NULs in values -// for the PAX version of the USTAR string fields. -// The key must not contain an '=' character. -func validPAXRecord(k, v string) bool { - if k == "" || strings.IndexByte(k, '=') >= 0 { - return false - } - switch k { - case paxPath, paxLinkpath, paxUname, paxGname: - return !hasNUL(v) - default: - return !hasNUL(k) - } -} diff --git a/vendor/github.com/vbatts/tar-split/archive/tar/writer.go b/vendor/github.com/vbatts/tar-split/archive/tar/writer.go deleted file mode 100644 index e80498d03..000000000 --- a/vendor/github.com/vbatts/tar-split/archive/tar/writer.go +++ /dev/null @@ -1,653 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tar - -import ( - "fmt" - "io" - "path" - "sort" - "strings" - "time" -) - -// Writer provides sequential writing of a tar archive. -// Write.WriteHeader begins a new file with the provided Header, -// and then Writer can be treated as an io.Writer to supply that file's data. -type Writer struct { - w io.Writer - pad int64 // Amount of padding to write after current file entry - curr fileWriter // Writer for current file entry - hdr Header // Shallow copy of Header that is safe for mutations - blk block // Buffer to use as temporary local storage - - // err is a persistent error. - // It is only the responsibility of every exported method of Writer to - // ensure that this error is sticky. - err error -} - -// NewWriter creates a new Writer writing to w. -func NewWriter(w io.Writer) *Writer { - return &Writer{w: w, curr: ®FileWriter{w, 0}} -} - -type fileWriter interface { - io.Writer - fileState - - ReadFrom(io.Reader) (int64, error) -} - -// Flush finishes writing the current file's block padding. -// The current file must be fully written before Flush can be called. -// -// This is unnecessary as the next call to WriteHeader or Close -// will implicitly flush out the file's padding. -func (tw *Writer) Flush() error { - if tw.err != nil { - return tw.err - } - if nb := tw.curr.LogicalRemaining(); nb > 0 { - return fmt.Errorf("archive/tar: missed writing %d bytes", nb) - } - if _, tw.err = tw.w.Write(zeroBlock[:tw.pad]); tw.err != nil { - return tw.err - } - tw.pad = 0 - return nil -} - -// WriteHeader writes hdr and prepares to accept the file's contents. -// The Header.Size determines how many bytes can be written for the next file. -// If the current file is not fully written, then this returns an error. -// This implicitly flushes any padding necessary before writing the header. -func (tw *Writer) WriteHeader(hdr *Header) error { - if err := tw.Flush(); err != nil { - return err - } - tw.hdr = *hdr // Shallow copy of Header - - // Avoid usage of the legacy TypeRegA flag, and automatically promote - // it to use TypeReg or TypeDir. - if tw.hdr.Typeflag == TypeRegA { - if strings.HasSuffix(tw.hdr.Name, "/") { - tw.hdr.Typeflag = TypeDir - } else { - tw.hdr.Typeflag = TypeReg - } - } - - // Round ModTime and ignore AccessTime and ChangeTime unless - // the format is explicitly chosen. - // This ensures nominal usage of WriteHeader (without specifying the format) - // does not always result in the PAX format being chosen, which - // causes a 1KiB increase to every header. - if tw.hdr.Format == FormatUnknown { - tw.hdr.ModTime = tw.hdr.ModTime.Round(time.Second) - tw.hdr.AccessTime = time.Time{} - tw.hdr.ChangeTime = time.Time{} - } - - allowedFormats, paxHdrs, err := tw.hdr.allowedFormats() - switch { - case allowedFormats.has(FormatUSTAR): - tw.err = tw.writeUSTARHeader(&tw.hdr) - return tw.err - case allowedFormats.has(FormatPAX): - tw.err = tw.writePAXHeader(&tw.hdr, paxHdrs) - return tw.err - case allowedFormats.has(FormatGNU): - tw.err = tw.writeGNUHeader(&tw.hdr) - return tw.err - default: - return err // Non-fatal error - } -} - -func (tw *Writer) writeUSTARHeader(hdr *Header) error { - // Check if we can use USTAR prefix/suffix splitting. - var namePrefix string - if prefix, suffix, ok := splitUSTARPath(hdr.Name); ok { - namePrefix, hdr.Name = prefix, suffix - } - - // Pack the main header. - var f formatter - blk := tw.templateV7Plus(hdr, f.formatString, f.formatOctal) - f.formatString(blk.USTAR().Prefix(), namePrefix) - blk.SetFormat(FormatUSTAR) - if f.err != nil { - return f.err // Should never happen since header is validated - } - return tw.writeRawHeader(blk, hdr.Size, hdr.Typeflag) -} - -func (tw *Writer) writePAXHeader(hdr *Header, paxHdrs map[string]string) error { - realName, realSize := hdr.Name, hdr.Size - - // TODO(dsnet): Re-enable this when adding sparse support. - // See https://golang.org/issue/22735 - /* - // Handle sparse files. - var spd sparseDatas - var spb []byte - if len(hdr.SparseHoles) > 0 { - sph := append([]sparseEntry{}, hdr.SparseHoles...) // Copy sparse map - sph = alignSparseEntries(sph, hdr.Size) - spd = invertSparseEntries(sph, hdr.Size) - - // Format the sparse map. - hdr.Size = 0 // Replace with encoded size - spb = append(strconv.AppendInt(spb, int64(len(spd)), 10), '\n') - for _, s := range spd { - hdr.Size += s.Length - spb = append(strconv.AppendInt(spb, s.Offset, 10), '\n') - spb = append(strconv.AppendInt(spb, s.Length, 10), '\n') - } - pad := blockPadding(int64(len(spb))) - spb = append(spb, zeroBlock[:pad]...) - hdr.Size += int64(len(spb)) // Accounts for encoded sparse map - - // Add and modify appropriate PAX records. - dir, file := path.Split(realName) - hdr.Name = path.Join(dir, "GNUSparseFile.0", file) - paxHdrs[paxGNUSparseMajor] = "1" - paxHdrs[paxGNUSparseMinor] = "0" - paxHdrs[paxGNUSparseName] = realName - paxHdrs[paxGNUSparseRealSize] = strconv.FormatInt(realSize, 10) - paxHdrs[paxSize] = strconv.FormatInt(hdr.Size, 10) - delete(paxHdrs, paxPath) // Recorded by paxGNUSparseName - } - */ - _ = realSize - - // Write PAX records to the output. - isGlobal := hdr.Typeflag == TypeXGlobalHeader - if len(paxHdrs) > 0 || isGlobal { - // Sort keys for deterministic ordering. - var keys []string - for k := range paxHdrs { - keys = append(keys, k) - } - sort.Strings(keys) - - // Write each record to a buffer. - var buf strings.Builder - for _, k := range keys { - rec, err := formatPAXRecord(k, paxHdrs[k]) - if err != nil { - return err - } - buf.WriteString(rec) - } - - // Write the extended header file. - var name string - var flag byte - if isGlobal { - name = realName - if name == "" { - name = "GlobalHead.0.0" - } - flag = TypeXGlobalHeader - } else { - dir, file := path.Split(realName) - name = path.Join(dir, "PaxHeaders.0", file) - flag = TypeXHeader - } - data := buf.String() - if err := tw.writeRawFile(name, data, flag, FormatPAX); err != nil || isGlobal { - return err // Global headers return here - } - } - - // Pack the main header. - var f formatter // Ignore errors since they are expected - fmtStr := func(b []byte, s string) { f.formatString(b, toASCII(s)) } - blk := tw.templateV7Plus(hdr, fmtStr, f.formatOctal) - blk.SetFormat(FormatPAX) - if err := tw.writeRawHeader(blk, hdr.Size, hdr.Typeflag); err != nil { - return err - } - - // TODO(dsnet): Re-enable this when adding sparse support. - // See https://golang.org/issue/22735 - /* - // Write the sparse map and setup the sparse writer if necessary. - if len(spd) > 0 { - // Use tw.curr since the sparse map is accounted for in hdr.Size. - if _, err := tw.curr.Write(spb); err != nil { - return err - } - tw.curr = &sparseFileWriter{tw.curr, spd, 0} - } - */ - return nil -} - -func (tw *Writer) writeGNUHeader(hdr *Header) error { - // Use long-link files if Name or Linkname exceeds the field size. - const longName = "././@LongLink" - if len(hdr.Name) > nameSize { - data := hdr.Name + "\x00" - if err := tw.writeRawFile(longName, data, TypeGNULongName, FormatGNU); err != nil { - return err - } - } - if len(hdr.Linkname) > nameSize { - data := hdr.Linkname + "\x00" - if err := tw.writeRawFile(longName, data, TypeGNULongLink, FormatGNU); err != nil { - return err - } - } - - // Pack the main header. - var f formatter // Ignore errors since they are expected - var spd sparseDatas - var spb []byte - blk := tw.templateV7Plus(hdr, f.formatString, f.formatNumeric) - if !hdr.AccessTime.IsZero() { - f.formatNumeric(blk.GNU().AccessTime(), hdr.AccessTime.Unix()) - } - if !hdr.ChangeTime.IsZero() { - f.formatNumeric(blk.GNU().ChangeTime(), hdr.ChangeTime.Unix()) - } - // TODO(dsnet): Re-enable this when adding sparse support. - // See https://golang.org/issue/22735 - /* - if hdr.Typeflag == TypeGNUSparse { - sph := append([]sparseEntry{}, hdr.SparseHoles...) // Copy sparse map - sph = alignSparseEntries(sph, hdr.Size) - spd = invertSparseEntries(sph, hdr.Size) - - // Format the sparse map. - formatSPD := func(sp sparseDatas, sa sparseArray) sparseDatas { - for i := 0; len(sp) > 0 && i < sa.MaxEntries(); i++ { - f.formatNumeric(sa.Entry(i).Offset(), sp[0].Offset) - f.formatNumeric(sa.Entry(i).Length(), sp[0].Length) - sp = sp[1:] - } - if len(sp) > 0 { - sa.IsExtended()[0] = 1 - } - return sp - } - sp2 := formatSPD(spd, blk.GNU().Sparse()) - for len(sp2) > 0 { - var spHdr block - sp2 = formatSPD(sp2, spHdr.Sparse()) - spb = append(spb, spHdr[:]...) - } - - // Update size fields in the header block. - realSize := hdr.Size - hdr.Size = 0 // Encoded size; does not account for encoded sparse map - for _, s := range spd { - hdr.Size += s.Length - } - copy(blk.V7().Size(), zeroBlock[:]) // Reset field - f.formatNumeric(blk.V7().Size(), hdr.Size) - f.formatNumeric(blk.GNU().RealSize(), realSize) - } - */ - blk.SetFormat(FormatGNU) - if err := tw.writeRawHeader(blk, hdr.Size, hdr.Typeflag); err != nil { - return err - } - - // Write the extended sparse map and setup the sparse writer if necessary. - if len(spd) > 0 { - // Use tw.w since the sparse map is not accounted for in hdr.Size. - if _, err := tw.w.Write(spb); err != nil { - return err - } - tw.curr = &sparseFileWriter{tw.curr, spd, 0} - } - return nil -} - -type ( - stringFormatter func([]byte, string) - numberFormatter func([]byte, int64) -) - -// templateV7Plus fills out the V7 fields of a block using values from hdr. -// It also fills out fields (uname, gname, devmajor, devminor) that are -// shared in the USTAR, PAX, and GNU formats using the provided formatters. -// -// The block returned is only valid until the next call to -// templateV7Plus or writeRawFile. -func (tw *Writer) templateV7Plus(hdr *Header, fmtStr stringFormatter, fmtNum numberFormatter) *block { - tw.blk.Reset() - - modTime := hdr.ModTime - if modTime.IsZero() { - modTime = time.Unix(0, 0) - } - - v7 := tw.blk.V7() - v7.TypeFlag()[0] = hdr.Typeflag - fmtStr(v7.Name(), hdr.Name) - fmtStr(v7.LinkName(), hdr.Linkname) - fmtNum(v7.Mode(), hdr.Mode) - fmtNum(v7.UID(), int64(hdr.Uid)) - fmtNum(v7.GID(), int64(hdr.Gid)) - fmtNum(v7.Size(), hdr.Size) - fmtNum(v7.ModTime(), modTime.Unix()) - - ustar := tw.blk.USTAR() - fmtStr(ustar.UserName(), hdr.Uname) - fmtStr(ustar.GroupName(), hdr.Gname) - fmtNum(ustar.DevMajor(), hdr.Devmajor) - fmtNum(ustar.DevMinor(), hdr.Devminor) - - return &tw.blk -} - -// writeRawFile writes a minimal file with the given name and flag type. -// It uses format to encode the header format and will write data as the body. -// It uses default values for all of the other fields (as BSD and GNU tar does). -func (tw *Writer) writeRawFile(name, data string, flag byte, format Format) error { - tw.blk.Reset() - - // Best effort for the filename. - name = toASCII(name) - if len(name) > nameSize { - name = name[:nameSize] - } - name = strings.TrimRight(name, "/") - - var f formatter - v7 := tw.blk.V7() - v7.TypeFlag()[0] = flag - f.formatString(v7.Name(), name) - f.formatOctal(v7.Mode(), 0) - f.formatOctal(v7.UID(), 0) - f.formatOctal(v7.GID(), 0) - f.formatOctal(v7.Size(), int64(len(data))) // Must be < 8GiB - f.formatOctal(v7.ModTime(), 0) - tw.blk.SetFormat(format) - if f.err != nil { - return f.err // Only occurs if size condition is violated - } - - // Write the header and data. - if err := tw.writeRawHeader(&tw.blk, int64(len(data)), flag); err != nil { - return err - } - _, err := io.WriteString(tw, data) - return err -} - -// writeRawHeader writes the value of blk, regardless of its value. -// It sets up the Writer such that it can accept a file of the given size. -// If the flag is a special header-only flag, then the size is treated as zero. -func (tw *Writer) writeRawHeader(blk *block, size int64, flag byte) error { - if err := tw.Flush(); err != nil { - return err - } - if _, err := tw.w.Write(blk[:]); err != nil { - return err - } - if isHeaderOnlyType(flag) { - size = 0 - } - tw.curr = ®FileWriter{tw.w, size} - tw.pad = blockPadding(size) - return nil -} - -// splitUSTARPath splits a path according to USTAR prefix and suffix rules. -// If the path is not splittable, then it will return ("", "", false). -func splitUSTARPath(name string) (prefix, suffix string, ok bool) { - length := len(name) - if length <= nameSize || !isASCII(name) { - return "", "", false - } else if length > prefixSize+1 { - length = prefixSize + 1 - } else if name[length-1] == '/' { - length-- - } - - i := strings.LastIndex(name[:length], "/") - nlen := len(name) - i - 1 // nlen is length of suffix - plen := i // plen is length of prefix - if i <= 0 || nlen > nameSize || nlen == 0 || plen > prefixSize { - return "", "", false - } - return name[:i], name[i+1:], true -} - -// Write writes to the current file in the tar archive. -// Write returns the error ErrWriteTooLong if more than -// Header.Size bytes are written after WriteHeader. -// -// Calling Write on special types like TypeLink, TypeSymlink, TypeChar, -// TypeBlock, TypeDir, and TypeFifo returns (0, ErrWriteTooLong) regardless -// of what the Header.Size claims. -func (tw *Writer) Write(b []byte) (int, error) { - if tw.err != nil { - return 0, tw.err - } - n, err := tw.curr.Write(b) - if err != nil && err != ErrWriteTooLong { - tw.err = err - } - return n, err -} - -// readFrom populates the content of the current file by reading from r. -// The bytes read must match the number of remaining bytes in the current file. -// -// If the current file is sparse and r is an io.ReadSeeker, -// then readFrom uses Seek to skip past holes defined in Header.SparseHoles, -// assuming that skipped regions are all NULs. -// This always reads the last byte to ensure r is the right size. -// -// TODO(dsnet): Re-export this when adding sparse file support. -// See https://golang.org/issue/22735 -func (tw *Writer) readFrom(r io.Reader) (int64, error) { - if tw.err != nil { - return 0, tw.err - } - n, err := tw.curr.ReadFrom(r) - if err != nil && err != ErrWriteTooLong { - tw.err = err - } - return n, err -} - -// Close closes the tar archive by flushing the padding, and writing the footer. -// If the current file (from a prior call to WriteHeader) is not fully written, -// then this returns an error. -func (tw *Writer) Close() error { - if tw.err == ErrWriteAfterClose { - return nil - } - if tw.err != nil { - return tw.err - } - - // Trailer: two zero blocks. - err := tw.Flush() - for i := 0; i < 2 && err == nil; i++ { - _, err = tw.w.Write(zeroBlock[:]) - } - - // Ensure all future actions are invalid. - tw.err = ErrWriteAfterClose - return err // Report IO errors -} - -// regFileWriter is a fileWriter for writing data to a regular file entry. -type regFileWriter struct { - w io.Writer // Underlying Writer - nb int64 // Number of remaining bytes to write -} - -func (fw *regFileWriter) Write(b []byte) (n int, err error) { - overwrite := int64(len(b)) > fw.nb - if overwrite { - b = b[:fw.nb] - } - if len(b) > 0 { - n, err = fw.w.Write(b) - fw.nb -= int64(n) - } - switch { - case err != nil: - return n, err - case overwrite: - return n, ErrWriteTooLong - default: - return n, nil - } -} - -func (fw *regFileWriter) ReadFrom(r io.Reader) (int64, error) { - return io.Copy(struct{ io.Writer }{fw}, r) -} - -func (fw regFileWriter) LogicalRemaining() int64 { - return fw.nb -} -func (fw regFileWriter) PhysicalRemaining() int64 { - return fw.nb -} - -// sparseFileWriter is a fileWriter for writing data to a sparse file entry. -type sparseFileWriter struct { - fw fileWriter // Underlying fileWriter - sp sparseDatas // Normalized list of data fragments - pos int64 // Current position in sparse file -} - -func (sw *sparseFileWriter) Write(b []byte) (n int, err error) { - overwrite := int64(len(b)) > sw.LogicalRemaining() - if overwrite { - b = b[:sw.LogicalRemaining()] - } - - b0 := b - endPos := sw.pos + int64(len(b)) - for endPos > sw.pos && err == nil { - var nf int // Bytes written in fragment - dataStart, dataEnd := sw.sp[0].Offset, sw.sp[0].endOffset() - if sw.pos < dataStart { // In a hole fragment - bf := b[:min(int64(len(b)), dataStart-sw.pos)] - nf, err = zeroWriter{}.Write(bf) - } else { // In a data fragment - bf := b[:min(int64(len(b)), dataEnd-sw.pos)] - nf, err = sw.fw.Write(bf) - } - b = b[nf:] - sw.pos += int64(nf) - if sw.pos >= dataEnd && len(sw.sp) > 1 { - sw.sp = sw.sp[1:] // Ensure last fragment always remains - } - } - - n = len(b0) - len(b) - switch { - case err == ErrWriteTooLong: - return n, errMissData // Not possible; implies bug in validation logic - case err != nil: - return n, err - case sw.LogicalRemaining() == 0 && sw.PhysicalRemaining() > 0: - return n, errUnrefData // Not possible; implies bug in validation logic - case overwrite: - return n, ErrWriteTooLong - default: - return n, nil - } -} - -func (sw *sparseFileWriter) ReadFrom(r io.Reader) (n int64, err error) { - rs, ok := r.(io.ReadSeeker) - if ok { - if _, err := rs.Seek(0, io.SeekCurrent); err != nil { - ok = false // Not all io.Seeker can really seek - } - } - if !ok { - return io.Copy(struct{ io.Writer }{sw}, r) - } - - var readLastByte bool - pos0 := sw.pos - for sw.LogicalRemaining() > 0 && !readLastByte && err == nil { - var nf int64 // Size of fragment - dataStart, dataEnd := sw.sp[0].Offset, sw.sp[0].endOffset() - if sw.pos < dataStart { // In a hole fragment - nf = dataStart - sw.pos - if sw.PhysicalRemaining() == 0 { - readLastByte = true - nf-- - } - _, err = rs.Seek(nf, io.SeekCurrent) - } else { // In a data fragment - nf = dataEnd - sw.pos - nf, err = io.CopyN(sw.fw, rs, nf) - } - sw.pos += nf - if sw.pos >= dataEnd && len(sw.sp) > 1 { - sw.sp = sw.sp[1:] // Ensure last fragment always remains - } - } - - // If the last fragment is a hole, then seek to 1-byte before EOF, and - // read a single byte to ensure the file is the right size. - if readLastByte && err == nil { - _, err = mustReadFull(rs, []byte{0}) - sw.pos++ - } - - n = sw.pos - pos0 - switch { - case err == io.EOF: - return n, io.ErrUnexpectedEOF - case err == ErrWriteTooLong: - return n, errMissData // Not possible; implies bug in validation logic - case err != nil: - return n, err - case sw.LogicalRemaining() == 0 && sw.PhysicalRemaining() > 0: - return n, errUnrefData // Not possible; implies bug in validation logic - default: - return n, ensureEOF(rs) - } -} - -func (sw sparseFileWriter) LogicalRemaining() int64 { - return sw.sp[len(sw.sp)-1].endOffset() - sw.pos -} -func (sw sparseFileWriter) PhysicalRemaining() int64 { - return sw.fw.PhysicalRemaining() -} - -// zeroWriter may only be written with NULs, otherwise it returns errWriteHole. -type zeroWriter struct{} - -func (zeroWriter) Write(b []byte) (int, error) { - for i, c := range b { - if c != 0 { - return i, errWriteHole - } - } - return len(b), nil -} - -// ensureEOF checks whether r is at EOF, reporting ErrWriteTooLong if not so. -func ensureEOF(r io.Reader) error { - n, err := tryReadFull(r, []byte{0}) - switch { - case n > 0: - return ErrWriteTooLong - case err == io.EOF: - return nil - default: - return err - } -} diff --git a/vendor/go.bytebuilders.dev/audit/LICENSE b/vendor/go.bytebuilders.dev/audit/LICENSE deleted file mode 100644 index 8dada3eda..000000000 --- a/vendor/go.bytebuilders.dev/audit/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - 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 "{}" - 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 - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - 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. diff --git a/vendor/go.bytebuilders.dev/audit/api/v1/doc.go b/vendor/go.bytebuilders.dev/audit/api/v1/doc.go deleted file mode 100644 index 74e191a88..000000000 --- a/vendor/go.bytebuilders.dev/audit/api/v1/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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. -*/ - -// +k8s:deepcopy-gen=package -// +k8s:openapi-gen=true -package v1 // import "go.bytebuilders.dev/audit/api/v1" diff --git a/vendor/go.bytebuilders.dev/audit/api/v1/types.go b/vendor/go.bytebuilders.dev/audit/api/v1/types.go deleted file mode 100644 index db6521ba1..000000000 --- a/vendor/go.bytebuilders.dev/audit/api/v1/types.go +++ /dev/null @@ -1,46 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1 - -import ( - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - kmapi "kmodules.xyz/client-go/api/v1" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -type EventType string - -const ( - // ref: https://github.com/cloudevents/spec/blob/v1.0.1/spec.md#type - - EventCreated EventType = "builders.byte.auditor.created.v1" - EventUpdated EventType = "builders.byte.auditor.updated.v1" - EventDeleted EventType = "builders.byte.auditor.deleted.v1" -) - -// +k8s:deepcopy-gen=false -type Event struct { - LicenseID string `json:"licenseID,omitempty"` - ResourceID kmapi.ResourceID `json:"resourceID,omitempty"` - Resource client.Object `json:"resource,omitempty"` -} - -type UnstructuredEvent struct { - LicenseID string `json:"licenseID,omitempty"` - ResourceID kmapi.ResourceID `json:"resourceID,omitempty"` - Resource *unstructured.Unstructured `json:"resource,omitempty"` -} diff --git a/vendor/go.bytebuilders.dev/audit/api/v1/zz_generated.deepcopy.go b/vendor/go.bytebuilders.dev/audit/api/v1/zz_generated.deepcopy.go deleted file mode 100644 index c0622fb89..000000000 --- a/vendor/go.bytebuilders.dev/audit/api/v1/zz_generated.deepcopy.go +++ /dev/null @@ -1,43 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright AppsCode Inc. and Contributors - -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. -*/ - -// Code generated by deepcopy-gen. DO NOT EDIT. - -package v1 - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *UnstructuredEvent) DeepCopyInto(out *UnstructuredEvent) { - *out = *in - out.ResourceID = in.ResourceID - if in.Resource != nil { - in, out := &in.Resource, &out.Resource - *out = (*in).DeepCopy() - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new UnstructuredEvent. -func (in *UnstructuredEvent) DeepCopy() *UnstructuredEvent { - if in == nil { - return nil - } - out := new(UnstructuredEvent) - in.DeepCopyInto(out) - return out -} diff --git a/vendor/go.bytebuilders.dev/audit/lib/audit_event.go b/vendor/go.bytebuilders.dev/audit/lib/audit_event.go deleted file mode 100644 index c1f59c45b..000000000 --- a/vendor/go.bytebuilders.dev/audit/lib/audit_event.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 lib - -import ( - api "go.bytebuilders.dev/audit/api/v1" - - "kmodules.xyz/client-go/discovery" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -type AuditEventCreator struct { - Mapper discovery.ResourceMapper -} - -func (p *AuditEventCreator) CreateEvent(obj client.Object) (*api.Event, error) { - rid, err := p.Mapper.ResourceIDForGVK(obj.GetObjectKind().GroupVersionKind()) - if err != nil { - return nil, err - } - - return &api.Event{ - Resource: obj, - ResourceID: *rid, - }, nil -} diff --git a/vendor/go.bytebuilders.dev/audit/lib/billing_event.go b/vendor/go.bytebuilders.dev/audit/lib/billing_event.go deleted file mode 100644 index 95c3352af..000000000 --- a/vendor/go.bytebuilders.dev/audit/lib/billing_event.go +++ /dev/null @@ -1,48 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 lib - -import ( - api "go.bytebuilders.dev/audit/api/v1" - - kmapi "kmodules.xyz/client-go/api/v1" - "kmodules.xyz/client-go/discovery" - corev1alpha1 "kmodules.xyz/resource-metadata/apis/core/v1alpha1" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -type BillingEventCreator struct { - Mapper discovery.ResourceMapper - ClusterMetadata *kmapi.ClusterMetadata -} - -func (p *BillingEventCreator) CreateEvent(obj client.Object) (*api.Event, error) { - rid, err := p.Mapper.ResourceIDForGVK(obj.GetObjectKind().GroupVersionKind()) - if err != nil { - return nil, err - } - - res, err := corev1alpha1.ToGenericResource(obj, rid, p.ClusterMetadata) - if err != nil { - return nil, err - } - - return &api.Event{ - Resource: res, - ResourceID: *rid, - }, nil -} diff --git a/vendor/go.bytebuilders.dev/audit/lib/nats.go b/vendor/go.bytebuilders.dev/audit/lib/nats.go deleted file mode 100644 index fa5014952..000000000 --- a/vendor/go.bytebuilders.dev/audit/lib/nats.go +++ /dev/null @@ -1,195 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 lib - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "os" - "time" - - "github.com/nats-io/nats.go" - "github.com/pkg/errors" - proxyserver "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1" - proxyclient "go.bytebuilders.dev/license-proxyserver/client/clientset/versioned" - verifier "go.bytebuilders.dev/license-verifier" - "go.bytebuilders.dev/license-verifier/info" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/rest" - "k8s.io/klog/v2" -) - -const ( - natsConnectionTimeout = 350 * time.Millisecond - natsConnectionRetryInterval = 100 * time.Millisecond - natsEventPublishTimeout = 10 * time.Second - natsRequestTimeout = 2 * time.Second -) - -type NatsConfig struct { - LicenseID string `json:"licenseID"` - Subject string `json:"natsSubject"` - Server string `json:"natsServer"` - Client *nats.Conn `json:"-"` -} - -// NatsCredential represents the api response of the register licensed user api -type NatsCredential struct { - NatsConfig `json:",inline,omitempty"` - Credential []byte `json:"credential"` -} - -func NewNatsConfig(cfg *rest.Config, clusterID string, LicenseFile string) (*NatsConfig, error) { - var licenseBytes []byte - var err error - - licenseBytes, err = os.ReadFile(LicenseFile) - if errors.Is(err, os.ErrNotExist) { - req := proxyserver.LicenseRequest{ - TypeMeta: metav1.TypeMeta{}, - Request: &proxyserver.LicenseRequestRequest{ - Features: info.Features(), - }, - } - pc, err := proxyclient.NewForConfig(cfg) - if err != nil { - return nil, errors.Wrap(err, "failed create client for license-proxyserver") - } - resp, err := pc.ProxyserverV1alpha1().LicenseRequests().Create(context.TODO(), &req, metav1.CreateOptions{}) - if err != nil { - return nil, errors.Wrap(err, "failed to read license") - } - licenseBytes = []byte(resp.Response.License) - } else if err != nil { - return nil, errors.Wrap(err, "failed to read license") - } - - opts := verifier.Options{ - ClusterUID: clusterID, - Features: info.ProductName, - CACert: []byte(info.LicenseCA), - License: licenseBytes, - } - data, err := json.Marshal(opts) - if err != nil { - return nil, err - } - - resp, err := http.Post(info.MustRegistrationAPIEndpoint(), "application/json", bytes.NewReader(data)) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := io.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - if resp.StatusCode != http.StatusOK { - return nil, errors.New(resp.Status + ", " + string(body)) - } - - var natscred NatsCredential - err = json.Unmarshal(body, &natscred) - if err != nil { - return nil, err - } - - klog.V(5).InfoS("using event receiver", "address", natscred.Server, "subject", natscred.Subject, "licenseID", natscred.LicenseID) - - natscred.Client, err = NewConnection(natscred) - if err != nil { - return nil, err - } - - return &natscred.NatsConfig, nil -} - -// NewConnection creates a new NATS connection -func NewConnection(natscred NatsCredential) (nc *nats.Conn, err error) { - servers := natscred.Server - - opts := []nats.Option{ - nats.Name(fmt.Sprintf("%s.%s", natscred.LicenseID, info.ProductName)), - nats.MaxReconnects(-1), - nats.ErrorHandler(errorHandler), - nats.ReconnectHandler(reconnectHandler), - nats.DisconnectErrHandler(disconnectHandler), - // nats.UseOldRequestStyle(), - } - - credFile := "/tmp/nats.creds" - if err = os.WriteFile(credFile, natscred.Credential, 0o600); err != nil { - return nil, err - } - - opts = append(opts, nats.UserCredentials(credFile)) - - //if os.Getenv("NATS_CERTIFICATE") != "" && os.Getenv("NATS_KEY") != "" { - // opts = append(opts, nats.ClientCert(os.Getenv("NATS_CERTIFICATE"), os.Getenv("NATS_KEY"))) - //} - // - //if os.Getenv("NATS_CA") != "" { - // opts = append(opts, nats.RootCAs(os.Getenv("NATS_CA"))) - //} - - // initial connections can error due to DNS lookups etc, just retry, eventually with backoff - ctx, cancel := context.WithTimeout(context.Background(), natsConnectionTimeout) - defer cancel() - - ticker := time.NewTicker(natsConnectionRetryInterval) - for { - select { - case <-ticker.C: - nc, err := nats.Connect(servers, opts...) - if err == nil { - return nc, nil - } - klog.V(5).InfoS("failed to connect to event receiver", "error", err) - case <-ctx.Done(): - return nil, ctx.Err() - } - } -} - -// called during errors subscriptions etc -func errorHandler(nc *nats.Conn, s *nats.Subscription, err error) { - if s != nil { - klog.Warningf("error in event receiver connection: %s: subscription: %s: %s", nc.ConnectedUrl(), s.Subject, err) - return - } - klog.Warningf("Error in event receiver connection: %s: %s", nc.ConnectedUrl(), err) -} - -// called after reconnection -func reconnectHandler(nc *nats.Conn) { - klog.Warningf("Reconnected to %s", nc.ConnectedUrl()) -} - -// called after disconnection -func disconnectHandler(nc *nats.Conn, err error) { - if err != nil { - klog.Warningf("Disconnected from event receiver due to error: %v", err) - } else { - klog.Warningln("Disconnected from event receiver") - } -} diff --git a/vendor/go.bytebuilders.dev/audit/lib/node.go b/vendor/go.bytebuilders.dev/audit/lib/node.go deleted file mode 100644 index 3870d32d1..000000000 --- a/vendor/go.bytebuilders.dev/audit/lib/node.go +++ /dev/null @@ -1,127 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 lib - -import ( - "fmt" - - api "go.bytebuilders.dev/audit/api/v1" - - "gomodules.xyz/counter/hourly" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/client-go/tools/cache" - "k8s.io/klog/v2" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -var siteEventCounter hourly.Int32 - -type SiteInfoPublisher struct { - p *EventPublisher - createEvent EventCreator -} - -var _ cache.ResourceEventHandler = &SiteInfoPublisher{} - -func (p *SiteInfoPublisher) OnAdd(o interface{}, isInInitialList bool) { - obj, ok := o.(client.Object) - if !ok { - return - } - - ev, err := p.createEvent(obj) - if err != nil { - klog.V(5).InfoS("failed to create event data", "error", err) - return - } - - if err = p.p.Publish(ev, api.EventCreated); err != nil { - klog.V(5).InfoS("error while publishing event", "error", err) - return - } - - siteEventCounter.Inc() -} - -func (p *SiteInfoPublisher) OnUpdate(oldObj, newObj interface{}) { - uOld, ok := oldObj.(client.Object) - if !ok { - return - } - uNew, ok := newObj.(client.Object) - if !ok { - return - } - - alreadySentHourly := siteEventCounter.Get() > 0 - if alreadySentHourly && - uOld.GetUID() == uNew.GetUID() && uOld.GetGeneration() == uNew.GetGeneration() { - if klog.V(8).Enabled() { - klog.V(8).InfoS("skipping update event", - "gvk", uNew.GetObjectKind().GroupVersionKind(), - "namespace", uNew.GetNamespace(), - "name", uNew.GetName(), - ) - } - return - } - - ev, err := p.createEvent(uNew) - if err != nil { - klog.V(5).InfoS("failed to create event data", "error", err) - return - } - - if err = p.p.Publish(ev, api.EventUpdated); err != nil { - klog.V(5).InfoS("failed to publish event", "error", err) - return - } - - siteEventCounter.Inc() -} - -func (p *SiteInfoPublisher) OnDelete(obj interface{}) { - var object client.Object - var ok bool - if object, ok = obj.(client.Object); !ok { - tombstone, ok := obj.(cache.DeletedFinalStateUnknown) - if !ok { - klog.V(5).Info("error decoding object, invalid type") - return - } - object, ok = tombstone.Obj.(client.Object) - if !ok { - utilruntime.HandleError(fmt.Errorf("error decoding object tombstone, invalid type")) - return - } - klog.V(5).Infof("Recovered deleted object '%v' from tombstone", tombstone.Obj.(metav1.Object).GetName()) - } - - ev, err := p.createEvent(object) - if err != nil { - klog.V(5).InfoS("failed to create event data", "error", err) - return - } - - if err := p.p.Publish(ev, api.EventDeleted); err != nil { - klog.V(5).InfoS("failed to publish event", "error", err) - return - } - - siteEventCounter.Inc() -} diff --git a/vendor/go.bytebuilders.dev/audit/lib/publisher.go b/vendor/go.bytebuilders.dev/audit/lib/publisher.go deleted file mode 100644 index c5c3fce65..000000000 --- a/vendor/go.bytebuilders.dev/audit/lib/publisher.go +++ /dev/null @@ -1,301 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 lib - -import ( - "context" - "fmt" - gosync "sync" - "time" - - api "go.bytebuilders.dev/audit/api/v1" - - cloudeventssdk "github.com/cloudevents/sdk-go/v2" - "github.com/cloudevents/sdk-go/v2/binding/format" - cloudevents "github.com/cloudevents/sdk-go/v2/event" - "github.com/nats-io/nats.go" - "go.bytebuilders.dev/license-verifier/info" - "gomodules.xyz/sync" - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/client-go/informers" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/cache" - "k8s.io/klog/v2" - kmapi "kmodules.xyz/client-go/api/v1" - "kmodules.xyz/client-go/discovery" - "kmodules.xyz/client-go/tools/clusterid" - auditorapi "kmodules.xyz/custom-resources/apis/auditor/v1alpha1" - "kmodules.xyz/custom-resources/util/siteinfo" - cachex "sigs.k8s.io/controller-runtime/pkg/cache" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/client/apiutil" - "sigs.k8s.io/controller-runtime/pkg/manager" -) - -const eventInterval = 1 * time.Hour - -// Informer - informer allows you interact with the underlying informer. -type Informer interface { - // AddEventHandlerWithResyncPeriod adds an event handler to the shared informer using the - // specified resync period. Events to a single handler are delivered sequentially, but there is - // no coordination between different handlers. - AddEventHandlerWithResyncPeriod(handler cache.ResourceEventHandler, resyncPeriod time.Duration) (cache.ResourceEventHandlerRegistration, error) -} - -type EventCreator func(obj client.Object) (*api.Event, error) - -type EventPublisher struct { - once sync.Once - connect func() error - - nats *NatsConfig - mapper discovery.ResourceMapper - createEvent EventCreator - - siMutex gosync.Mutex - si *auditorapi.SiteInfo -} - -func NewEventPublisher( - nats *NatsConfig, - mapper discovery.ResourceMapper, - fn EventCreator, -) *EventPublisher { - p := &EventPublisher{ - mapper: mapper, - createEvent: fn, - } - p.connect = func() error { - p.nats = nats - return nil - } - return p -} - -func NewResilientEventPublisher( - fnConnect func() (*NatsConfig, error), - mapper discovery.ResourceMapper, - fnCreateEvent EventCreator, -) *EventPublisher { - p := &EventPublisher{ - mapper: mapper, - createEvent: fnCreateEvent, - } - p.connect = func() error { - var err error - p.nats, err = fnConnect() - if err != nil { - klog.V(5).InfoS("failed to connect with event receiver", "error", err) - } - return err - } - return p -} - -func (p *EventPublisher) NatsClient() (*nats.Conn, error) { - p.once.Do(p.connect) - if p.nats == nil { - return nil, fmt.Errorf("not connected to nats") - } - return p.nats.Client, nil -} - -func (p *EventPublisher) Publish(ev *api.Event, et api.EventType) error { - event := cloudeventssdk.NewEvent() - event.SetID(fmt.Sprintf("%s.%d", ev.Resource.GetUID(), ev.Resource.GetGeneration())) - // /byte.builders/auditor/license_id/feature/info.ProductName/api_group/api_resource/ - // ref: https://github.com/cloudevents/spec/blob/v1.0.1/spec.md#source-1 - event.SetSource(fmt.Sprintf("/byte.builders/auditor/%s/feature/%s/%s/%s", ev.LicenseID, info.ProductName, ev.ResourceID.Group, ev.ResourceID.Name)) - // obj.getUID - // ref: https://github.com/cloudevents/spec/blob/v1.0.1/spec.md#subject - event.SetSubject(string(ev.Resource.GetUID())) - // builders.byte.auditor.{created, updated, deleted}.v1 - // ref: https://github.com/cloudevents/spec/blob/v1.0.1/spec.md#type - event.SetType(string(et)) - event.SetTime(time.Now().UTC()) - - if err := event.SetData(cloudevents.ApplicationJSON, ev); err != nil { - return err - } - - data, err := format.JSON.Marshal(&event) - if err != nil { - return err - } - - ctx, cancel := context.WithTimeout(context.TODO(), natsEventPublishTimeout) - defer cancel() - - for { - _, err = p.nats.Client.Request(p.nats.Subject, data, natsRequestTimeout) - if err == nil { - cancel() - } else { - klog.V(5).Infoln(err) - } - - select { - case <-ctx.Done(): - if ctx.Err() == context.DeadlineExceeded { - klog.V(5).Infof("failed to send event : %s", string(data)) - } else if ctx.Err() == context.Canceled { - klog.V(5).Infof("Published event `%s` to channel `%s` and acknowledged", et, p.nats.Subject) - } - return nil - default: - time.Sleep(time.Microsecond * 100) - } - } -} - -func (p *EventPublisher) ForGVK(informer Informer, gvk schema.GroupVersionKind) { - if gvk.Version == "" || gvk.Kind == "" { - panic(fmt.Sprintf("incomplete GVK; %+v", gvk)) - } - - h := &ResourceEventPublisher{ - p: p, - counters: map[kmapi.OID]int32{}, - createEvent: func(obj client.Object) (*api.Event, error) { - r := obj.DeepCopyObject().(client.Object) - r.GetObjectKind().SetGroupVersionKind(gvk) - r.SetManagedFields(nil) - - ev, err := p.createEvent(r) - if err != nil { - return nil, err - } - - p.once.Do(p.connect) - if p.nats == nil { - return nil, fmt.Errorf("not connected to nats") - } - ev.LicenseID = p.nats.LicenseID - - return ev, nil - }, - } - _, _ = informer.AddEventHandlerWithResyncPeriod(h, eventInterval) -} - -type funcNodeLister func() ([]*core.Node, error) - -func (p *EventPublisher) SetupSiteInfoPublisher(cfg *rest.Config, kc kubernetes.Interface, factory informers.SharedInformerFactory) error { - nodeInformer := factory.Core().V1().Nodes().Informer() - nodeLister := factory.Core().V1().Nodes().Lister() - - return p.setupSiteInfoPublisher(cfg, kc, nodeInformer, func() ([]*core.Node, error) { - return nodeLister.List(labels.Everything()) - }) -} - -func (p *EventPublisher) SetupSiteInfoPublisherWithManager(mgr manager.Manager) error { - cfg := mgr.GetConfig() - kc, err := kubernetes.NewForConfig(cfg) - if err != nil { - return err - } - nodeInformer, err := mgr.GetCache().GetInformer(context.TODO(), &core.Node{}) - if err != nil { - return err - } - return p.setupSiteInfoPublisher(cfg, kc, nodeInformer, func() ([]*core.Node, error) { - var nodeList core.NodeList - if err := mgr.GetCache().List(context.TODO(), &nodeList); err != nil { - return nil, err - } - result := make([]*core.Node, len(nodeList.Items)) - for i := range nodeList.Items { - result[i] = &nodeList.Items[i] - } - return result, nil - }) -} - -func (p *EventPublisher) setupSiteInfoPublisher(cfg *rest.Config, kc kubernetes.Interface, nodeInformer cachex.Informer, listNodes funcNodeLister) error { - var err error - p.si, err = siteinfo.GetSiteInfo(cfg, kc, nil, "") - if err != nil { - return err - } - if p.si.Product == nil { - p.si.Product = new(auditorapi.ProductInfo) - } - - _, err = nodeInformer.AddEventHandlerWithResyncPeriod(&SiteInfoPublisher{ - p: p, - createEvent: func(_ client.Object) (*api.Event, error) { - cmeta, err := clusterid.ClusterMetadata(kc.CoreV1().Namespaces()) - if err != nil { - return nil, err - } - nodes, err := listNodes() - if err != nil { - return nil, err - } - - p.siMutex.Lock() - p.si.Kubernetes.Cluster = cmeta - siteinfo.RefreshNodeStats(p.si, nodes) - p.siMutex.Unlock() - - p.once.Do(p.connect) - if p.nats == nil { - return nil, fmt.Errorf("not connected to nats") - } - - p.si.Product.LicenseID = p.nats.LicenseID - p.si.Name = fmt.Sprintf("%s.%s", p.nats.LicenseID, p.si.Product.ProductName) - ev := &api.Event{ - Resource: p.si, - ResourceID: kmapi.ResourceID{ - Group: auditorapi.SchemeGroupVersion.Group, - Version: auditorapi.SchemeGroupVersion.Version, - Name: auditorapi.ResourceSiteInfos, - Kind: auditorapi.ResourceKindSiteInfo, - Scope: kmapi.ClusterScoped, - }, - LicenseID: p.nats.LicenseID, - } - return ev, nil - }, - }, eventInterval) - return err -} - -func (p *EventPublisher) SetupWithManagerForKind(ctx context.Context, mgr manager.Manager, gvk schema.GroupVersionKind) error { - if p == nil { - return nil - } - i, err := mgr.GetCache().GetInformerForKind(ctx, gvk) - if err != nil { - return err - } - p.ForGVK(i, gvk) - return nil -} - -func (p *EventPublisher) SetupWithManager(ctx context.Context, mgr manager.Manager, obj client.Object) error { - gvk, err := apiutil.GVKForObject(obj, mgr.GetScheme()) - if err != nil { - return err - } - return p.SetupWithManagerForKind(ctx, mgr, gvk) -} diff --git a/vendor/go.bytebuilders.dev/audit/lib/resource.go b/vendor/go.bytebuilders.dev/audit/lib/resource.go deleted file mode 100644 index 757936916..000000000 --- a/vendor/go.bytebuilders.dev/audit/lib/resource.go +++ /dev/null @@ -1,150 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 lib - -import ( - "fmt" - gosync "sync" - - api "go.bytebuilders.dev/audit/api/v1" - - "gomodules.xyz/counter/hourly" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/client-go/tools/cache" - "k8s.io/klog/v2" - kmapi "kmodules.xyz/client-go/api/v1" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -type ResourceEventPublisher struct { - p *EventPublisher - createEvent EventCreator - - counters map[kmapi.OID]int32 - mu gosync.Mutex -} - -var _ cache.ResourceEventHandler = &ResourceEventPublisher{} - -func (p *ResourceEventPublisher) OnAdd(o interface{}, isInInitialList bool) { - obj, ok := o.(client.Object) - if !ok { - return - } - - ev, err := p.createEvent(obj) - if err != nil { - klog.V(5).InfoS("failed to create event data", "error", err) - return - } - - if err = p.p.Publish(ev, api.EventCreated); err != nil { - klog.V(5).InfoS("error while publishing event", "error", err) - return - } - - p.mu.Lock() - oid := kmapi.NewObjectID(obj).OID() - c := p.counters[oid] - hourly.Inc32(&c) - p.counters[oid] = c - p.mu.Unlock() -} - -func (p *ResourceEventPublisher) OnUpdate(oldObj, newObj interface{}) { - uOld, ok := oldObj.(client.Object) - if !ok { - return - } - uNew, ok := newObj.(client.Object) - if !ok { - return - } - - alreadySentHourly := false - oid := kmapi.NewObjectID(uNew).OID() - p.mu.Lock() - c := p.counters[oid] - alreadySentHourly = hourly.Get32(&c) > 0 - p.mu.Unlock() - - if alreadySentHourly && - uOld.GetUID() == uNew.GetUID() && uOld.GetGeneration() == uNew.GetGeneration() { - if klog.V(8).Enabled() { - klog.V(8).InfoS("skipping update event", - "gvk", uNew.GetObjectKind().GroupVersionKind(), - "namespace", uNew.GetNamespace(), - "name", uNew.GetName(), - ) - } - return - } - - ev, err := p.createEvent(uNew) - if err != nil { - klog.V(5).InfoS("failed to create event data", "error", err) - return - } - - if err = p.p.Publish(ev, api.EventUpdated); err != nil { - klog.V(5).InfoS("failed to publish event", "error", err) - return - } - - p.mu.Lock() - c = p.counters[oid] - hourly.Inc32(&c) - p.counters[oid] = c - p.mu.Unlock() -} - -func (p *ResourceEventPublisher) OnDelete(obj interface{}) { - var object client.Object - var ok bool - if object, ok = obj.(client.Object); !ok { - tombstone, ok := obj.(cache.DeletedFinalStateUnknown) - if !ok { - klog.V(5).Info("error decoding object, invalid type") - return - } - object, ok = tombstone.Obj.(client.Object) - if !ok { - utilruntime.HandleError(fmt.Errorf("error decoding object tombstone, invalid type")) - return - } - klog.V(5).Infof("Recovered deleted object '%v' from tombstone", tombstone.Obj.(metav1.Object).GetName()) - } - - ev, err := p.createEvent(object) - if err != nil { - klog.V(5).InfoS("failed to create event data", "error", err) - return - } - - if err := p.p.Publish(ev, api.EventDeleted); err != nil { - klog.V(5).InfoS("failed to publish event", "error", err) - return - } - - p.mu.Lock() - oid := kmapi.NewObjectID(object).OID() - c := p.counters[oid] - hourly.Inc32(&c) - p.counters[oid] = c - p.mu.Unlock() -} diff --git a/vendor/go.bytebuilders.dev/license-proxyserver/LICENSE b/vendor/go.bytebuilders.dev/license-proxyserver/LICENSE deleted file mode 100644 index d64569567..000000000 --- a/vendor/go.bytebuilders.dev/license-proxyserver/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - 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 "[]" - 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 - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/register.go b/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/register.go deleted file mode 100644 index 6bbe222ba..000000000 --- a/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/register.go +++ /dev/null @@ -1,21 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors. - -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 proxyserver - -const ( - GroupName = "proxyserver.licenses.appscode.com" -) diff --git a/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/doc.go b/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/doc.go deleted file mode 100644 index 1984c1ac4..000000000 --- a/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/doc.go +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors. - -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 v1alpha1 contains API Schema definitions for the proxyserver v1alpha1 API group - -// +k8s:openapi-gen=true -// +k8s:deepcopy-gen=package -// +k8s:defaulter-gen=TypeMeta -// +groupName=proxyserver.licenses.appscode.com -package v1alpha1 // import "go.bytebuilders.dev/proxyserver/apis/proxyserver/v1alpha1" diff --git a/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/license_request_types.go b/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/license_request_types.go deleted file mode 100644 index e59cf8cf2..000000000 --- a/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/license_request_types.go +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -const ( - ResourceKindLicenseRequest = "LicenseRequest" - ResourceLicenseRequest = "licenserequest" - ResourceLicenseRequests = "licenserequests" -) - -// +genclient -// +genclient:nonNamespaced -// +genclient:onlyVerbs=create -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:object:root=true -// +kubebuilder:resource:path=licenserequests,singular=licenserequest,scope=Cluster -type LicenseRequest struct { - metav1.TypeMeta `json:",inline"` - // Request describes the attributes for the graph request. - // +optional - Request *LicenseRequestRequest `json:"request,omitempty"` - // Response describes the attributes for the graph response. - // +optional - Response *LicenseRequestResponse `json:"response,omitempty"` -} - -type LicenseRequestRequest struct { - Features []string `json:"features"` -} - -type LicenseRequestResponse struct { - License string `json:"license"` -} diff --git a/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/license_status_types.go b/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/license_status_types.go deleted file mode 100644 index f22294803..000000000 --- a/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/license_status_types.go +++ /dev/null @@ -1,101 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import ( - "fmt" - - licenseapi "go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -const ( - ResourceKindLicenseStatus = "LicenseStatus" - ResourceLicenseStatus = "licensestatus" - ResourceLicenseStatuses = "licensestatuses" -) - -// LicenseStatusSpec defines the desired state of License -type LicenseStatusSpec struct { - Feature []string `json:"features"` - // Result contains extra details into why an admission request was denied. - // This field IS NOT consulted in any way if "Allowed" is "true". - // +optional - User *UserInfo `json:"user,omitempty"` -} - -// UserInfo holds the information about the user needed to implement the -// user.Info interface. -type UserInfo struct { - // The name that uniquely identifies this user among all active users. - // +optional - Username string `json:"username,omitempty"` - // A unique value that identifies this user across time. If this user is - // deleted and another user by the same name is added, they will have - // different UIDs. - // +optional - UID string `json:"uid,omitempty"` - // The names of groups this user is a part of. - // +optional - Groups []string `json:"groups,omitempty"` - // Any additional information provided by the authenticator. - // +optional - Extra map[string]ExtraValue `json:"extra,omitempty"` -} - -// ExtraValue masks the value so protobuf can generate -// +protobuf.nullable=true -// +protobuf.options.(gogoproto.goproto_stringer)=false -type ExtraValue []string - -func (t ExtraValue) String() string { - return fmt.Sprintf("%v", []string(t)) -} - -// LicenseStatusStatus defines the status of License -type LicenseStatusStatus struct { - Contract *licenseapi.Contract `json:"contract,omitempty"` - License licenseapi.License `json:"license"` -} - -// +genclient -// +genclient:nonNamespaced -// +genclient:onlyVerbs=get,list -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -//+kubebuilder:object:root=true -//+kubebuilder:subresource:status -//+kubebuilder:resource:scope=Cluster - -// LicenseStatus is the Schema for the licensestatuses API -type LicenseStatus struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec LicenseStatusSpec `json:"spec,omitempty"` - Status LicenseStatusStatus `json:"status,omitempty"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -//+kubebuilder:object:root=true - -// LicenseStatusList contains a list of LicenseStatus -type LicenseStatusList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []LicenseStatus `json:"items"` -} diff --git a/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/openapi_generated.go b/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/openapi_generated.go deleted file mode 100644 index 884c0bec6..000000000 --- a/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/openapi_generated.go +++ /dev/null @@ -1,18682 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright AppsCode Inc. and Contributors. - -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. -*/ - -// Code generated by openapi-gen. DO NOT EDIT. - -// This file was autogenerated by openapi-gen. Do not edit it manually! - -package v1alpha1 - -import ( - resource "k8s.io/apimachinery/pkg/api/resource" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - intstr "k8s.io/apimachinery/pkg/util/intstr" - common "k8s.io/kube-openapi/pkg/common" - spec "k8s.io/kube-openapi/pkg/validation/spec" - apiv1 "kmodules.xyz/client-go/api/v1" -) - -func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenAPIDefinition { - return map[string]common.OpenAPIDefinition{ - "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1.LicenseRequest": schema_license_proxyserver_apis_proxyserver_v1alpha1_LicenseRequest(ref), - "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1.LicenseRequestRequest": schema_license_proxyserver_apis_proxyserver_v1alpha1_LicenseRequestRequest(ref), - "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1.LicenseRequestResponse": schema_license_proxyserver_apis_proxyserver_v1alpha1_LicenseRequestResponse(ref), - "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1.LicenseStatus": schema_license_proxyserver_apis_proxyserver_v1alpha1_LicenseStatus(ref), - "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1.LicenseStatusList": schema_license_proxyserver_apis_proxyserver_v1alpha1_LicenseStatusList(ref), - "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1.LicenseStatusSpec": schema_license_proxyserver_apis_proxyserver_v1alpha1_LicenseStatusSpec(ref), - "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1.LicenseStatusStatus": schema_license_proxyserver_apis_proxyserver_v1alpha1_LicenseStatusStatus(ref), - "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1.UserInfo": schema_license_proxyserver_apis_proxyserver_v1alpha1_UserInfo(ref), - "k8s.io/api/apps/v1.ControllerRevision": schema_k8sio_api_apps_v1_ControllerRevision(ref), - "k8s.io/api/apps/v1.ControllerRevisionList": schema_k8sio_api_apps_v1_ControllerRevisionList(ref), - "k8s.io/api/apps/v1.DaemonSet": schema_k8sio_api_apps_v1_DaemonSet(ref), - "k8s.io/api/apps/v1.DaemonSetCondition": schema_k8sio_api_apps_v1_DaemonSetCondition(ref), - "k8s.io/api/apps/v1.DaemonSetList": schema_k8sio_api_apps_v1_DaemonSetList(ref), - "k8s.io/api/apps/v1.DaemonSetSpec": schema_k8sio_api_apps_v1_DaemonSetSpec(ref), - "k8s.io/api/apps/v1.DaemonSetStatus": schema_k8sio_api_apps_v1_DaemonSetStatus(ref), - "k8s.io/api/apps/v1.DaemonSetUpdateStrategy": schema_k8sio_api_apps_v1_DaemonSetUpdateStrategy(ref), - "k8s.io/api/apps/v1.Deployment": schema_k8sio_api_apps_v1_Deployment(ref), - "k8s.io/api/apps/v1.DeploymentCondition": schema_k8sio_api_apps_v1_DeploymentCondition(ref), - "k8s.io/api/apps/v1.DeploymentList": schema_k8sio_api_apps_v1_DeploymentList(ref), - "k8s.io/api/apps/v1.DeploymentSpec": schema_k8sio_api_apps_v1_DeploymentSpec(ref), - "k8s.io/api/apps/v1.DeploymentStatus": schema_k8sio_api_apps_v1_DeploymentStatus(ref), - "k8s.io/api/apps/v1.DeploymentStrategy": schema_k8sio_api_apps_v1_DeploymentStrategy(ref), - "k8s.io/api/apps/v1.ReplicaSet": schema_k8sio_api_apps_v1_ReplicaSet(ref), - "k8s.io/api/apps/v1.ReplicaSetCondition": schema_k8sio_api_apps_v1_ReplicaSetCondition(ref), - "k8s.io/api/apps/v1.ReplicaSetList": schema_k8sio_api_apps_v1_ReplicaSetList(ref), - "k8s.io/api/apps/v1.ReplicaSetSpec": schema_k8sio_api_apps_v1_ReplicaSetSpec(ref), - "k8s.io/api/apps/v1.ReplicaSetStatus": schema_k8sio_api_apps_v1_ReplicaSetStatus(ref), - "k8s.io/api/apps/v1.RollingUpdateDaemonSet": schema_k8sio_api_apps_v1_RollingUpdateDaemonSet(ref), - "k8s.io/api/apps/v1.RollingUpdateDeployment": schema_k8sio_api_apps_v1_RollingUpdateDeployment(ref), - "k8s.io/api/apps/v1.RollingUpdateStatefulSetStrategy": schema_k8sio_api_apps_v1_RollingUpdateStatefulSetStrategy(ref), - "k8s.io/api/apps/v1.StatefulSet": schema_k8sio_api_apps_v1_StatefulSet(ref), - "k8s.io/api/apps/v1.StatefulSetCondition": schema_k8sio_api_apps_v1_StatefulSetCondition(ref), - "k8s.io/api/apps/v1.StatefulSetList": schema_k8sio_api_apps_v1_StatefulSetList(ref), - "k8s.io/api/apps/v1.StatefulSetOrdinals": schema_k8sio_api_apps_v1_StatefulSetOrdinals(ref), - "k8s.io/api/apps/v1.StatefulSetPersistentVolumeClaimRetentionPolicy": schema_k8sio_api_apps_v1_StatefulSetPersistentVolumeClaimRetentionPolicy(ref), - "k8s.io/api/apps/v1.StatefulSetSpec": schema_k8sio_api_apps_v1_StatefulSetSpec(ref), - "k8s.io/api/apps/v1.StatefulSetStatus": schema_k8sio_api_apps_v1_StatefulSetStatus(ref), - "k8s.io/api/apps/v1.StatefulSetUpdateStrategy": schema_k8sio_api_apps_v1_StatefulSetUpdateStrategy(ref), - "k8s.io/api/core/v1.AWSElasticBlockStoreVolumeSource": schema_k8sio_api_core_v1_AWSElasticBlockStoreVolumeSource(ref), - "k8s.io/api/core/v1.Affinity": schema_k8sio_api_core_v1_Affinity(ref), - "k8s.io/api/core/v1.AttachedVolume": schema_k8sio_api_core_v1_AttachedVolume(ref), - "k8s.io/api/core/v1.AvoidPods": schema_k8sio_api_core_v1_AvoidPods(ref), - "k8s.io/api/core/v1.AzureDiskVolumeSource": schema_k8sio_api_core_v1_AzureDiskVolumeSource(ref), - "k8s.io/api/core/v1.AzureFilePersistentVolumeSource": schema_k8sio_api_core_v1_AzureFilePersistentVolumeSource(ref), - "k8s.io/api/core/v1.AzureFileVolumeSource": schema_k8sio_api_core_v1_AzureFileVolumeSource(ref), - "k8s.io/api/core/v1.Binding": schema_k8sio_api_core_v1_Binding(ref), - "k8s.io/api/core/v1.CSIPersistentVolumeSource": schema_k8sio_api_core_v1_CSIPersistentVolumeSource(ref), - "k8s.io/api/core/v1.CSIVolumeSource": schema_k8sio_api_core_v1_CSIVolumeSource(ref), - "k8s.io/api/core/v1.Capabilities": schema_k8sio_api_core_v1_Capabilities(ref), - "k8s.io/api/core/v1.CephFSPersistentVolumeSource": schema_k8sio_api_core_v1_CephFSPersistentVolumeSource(ref), - "k8s.io/api/core/v1.CephFSVolumeSource": schema_k8sio_api_core_v1_CephFSVolumeSource(ref), - "k8s.io/api/core/v1.CinderPersistentVolumeSource": schema_k8sio_api_core_v1_CinderPersistentVolumeSource(ref), - "k8s.io/api/core/v1.CinderVolumeSource": schema_k8sio_api_core_v1_CinderVolumeSource(ref), - "k8s.io/api/core/v1.ClaimSource": schema_k8sio_api_core_v1_ClaimSource(ref), - "k8s.io/api/core/v1.ClientIPConfig": schema_k8sio_api_core_v1_ClientIPConfig(ref), - "k8s.io/api/core/v1.ClusterTrustBundleProjection": schema_k8sio_api_core_v1_ClusterTrustBundleProjection(ref), - "k8s.io/api/core/v1.ComponentCondition": schema_k8sio_api_core_v1_ComponentCondition(ref), - "k8s.io/api/core/v1.ComponentStatus": schema_k8sio_api_core_v1_ComponentStatus(ref), - "k8s.io/api/core/v1.ComponentStatusList": schema_k8sio_api_core_v1_ComponentStatusList(ref), - "k8s.io/api/core/v1.ConfigMap": schema_k8sio_api_core_v1_ConfigMap(ref), - "k8s.io/api/core/v1.ConfigMapEnvSource": schema_k8sio_api_core_v1_ConfigMapEnvSource(ref), - "k8s.io/api/core/v1.ConfigMapKeySelector": schema_k8sio_api_core_v1_ConfigMapKeySelector(ref), - "k8s.io/api/core/v1.ConfigMapList": schema_k8sio_api_core_v1_ConfigMapList(ref), - "k8s.io/api/core/v1.ConfigMapNodeConfigSource": schema_k8sio_api_core_v1_ConfigMapNodeConfigSource(ref), - "k8s.io/api/core/v1.ConfigMapProjection": schema_k8sio_api_core_v1_ConfigMapProjection(ref), - "k8s.io/api/core/v1.ConfigMapVolumeSource": schema_k8sio_api_core_v1_ConfigMapVolumeSource(ref), - "k8s.io/api/core/v1.Container": schema_k8sio_api_core_v1_Container(ref), - "k8s.io/api/core/v1.ContainerImage": schema_k8sio_api_core_v1_ContainerImage(ref), - "k8s.io/api/core/v1.ContainerPort": schema_k8sio_api_core_v1_ContainerPort(ref), - "k8s.io/api/core/v1.ContainerResizePolicy": schema_k8sio_api_core_v1_ContainerResizePolicy(ref), - "k8s.io/api/core/v1.ContainerState": schema_k8sio_api_core_v1_ContainerState(ref), - "k8s.io/api/core/v1.ContainerStateRunning": schema_k8sio_api_core_v1_ContainerStateRunning(ref), - "k8s.io/api/core/v1.ContainerStateTerminated": schema_k8sio_api_core_v1_ContainerStateTerminated(ref), - "k8s.io/api/core/v1.ContainerStateWaiting": schema_k8sio_api_core_v1_ContainerStateWaiting(ref), - "k8s.io/api/core/v1.ContainerStatus": schema_k8sio_api_core_v1_ContainerStatus(ref), - "k8s.io/api/core/v1.DaemonEndpoint": schema_k8sio_api_core_v1_DaemonEndpoint(ref), - "k8s.io/api/core/v1.DownwardAPIProjection": schema_k8sio_api_core_v1_DownwardAPIProjection(ref), - "k8s.io/api/core/v1.DownwardAPIVolumeFile": schema_k8sio_api_core_v1_DownwardAPIVolumeFile(ref), - "k8s.io/api/core/v1.DownwardAPIVolumeSource": schema_k8sio_api_core_v1_DownwardAPIVolumeSource(ref), - "k8s.io/api/core/v1.EmptyDirVolumeSource": schema_k8sio_api_core_v1_EmptyDirVolumeSource(ref), - "k8s.io/api/core/v1.EndpointAddress": schema_k8sio_api_core_v1_EndpointAddress(ref), - "k8s.io/api/core/v1.EndpointPort": schema_k8sio_api_core_v1_EndpointPort(ref), - "k8s.io/api/core/v1.EndpointSubset": schema_k8sio_api_core_v1_EndpointSubset(ref), - "k8s.io/api/core/v1.Endpoints": schema_k8sio_api_core_v1_Endpoints(ref), - "k8s.io/api/core/v1.EndpointsList": schema_k8sio_api_core_v1_EndpointsList(ref), - "k8s.io/api/core/v1.EnvFromSource": schema_k8sio_api_core_v1_EnvFromSource(ref), - "k8s.io/api/core/v1.EnvVar": schema_k8sio_api_core_v1_EnvVar(ref), - "k8s.io/api/core/v1.EnvVarSource": schema_k8sio_api_core_v1_EnvVarSource(ref), - "k8s.io/api/core/v1.EphemeralContainer": schema_k8sio_api_core_v1_EphemeralContainer(ref), - "k8s.io/api/core/v1.EphemeralContainerCommon": schema_k8sio_api_core_v1_EphemeralContainerCommon(ref), - "k8s.io/api/core/v1.EphemeralVolumeSource": schema_k8sio_api_core_v1_EphemeralVolumeSource(ref), - "k8s.io/api/core/v1.Event": schema_k8sio_api_core_v1_Event(ref), - "k8s.io/api/core/v1.EventList": schema_k8sio_api_core_v1_EventList(ref), - "k8s.io/api/core/v1.EventSeries": schema_k8sio_api_core_v1_EventSeries(ref), - "k8s.io/api/core/v1.EventSource": schema_k8sio_api_core_v1_EventSource(ref), - "k8s.io/api/core/v1.ExecAction": schema_k8sio_api_core_v1_ExecAction(ref), - "k8s.io/api/core/v1.FCVolumeSource": schema_k8sio_api_core_v1_FCVolumeSource(ref), - "k8s.io/api/core/v1.FlexPersistentVolumeSource": schema_k8sio_api_core_v1_FlexPersistentVolumeSource(ref), - "k8s.io/api/core/v1.FlexVolumeSource": schema_k8sio_api_core_v1_FlexVolumeSource(ref), - "k8s.io/api/core/v1.FlockerVolumeSource": schema_k8sio_api_core_v1_FlockerVolumeSource(ref), - "k8s.io/api/core/v1.GCEPersistentDiskVolumeSource": schema_k8sio_api_core_v1_GCEPersistentDiskVolumeSource(ref), - "k8s.io/api/core/v1.GRPCAction": schema_k8sio_api_core_v1_GRPCAction(ref), - "k8s.io/api/core/v1.GitRepoVolumeSource": schema_k8sio_api_core_v1_GitRepoVolumeSource(ref), - "k8s.io/api/core/v1.GlusterfsPersistentVolumeSource": schema_k8sio_api_core_v1_GlusterfsPersistentVolumeSource(ref), - "k8s.io/api/core/v1.GlusterfsVolumeSource": schema_k8sio_api_core_v1_GlusterfsVolumeSource(ref), - "k8s.io/api/core/v1.HTTPGetAction": schema_k8sio_api_core_v1_HTTPGetAction(ref), - "k8s.io/api/core/v1.HTTPHeader": schema_k8sio_api_core_v1_HTTPHeader(ref), - "k8s.io/api/core/v1.HostAlias": schema_k8sio_api_core_v1_HostAlias(ref), - "k8s.io/api/core/v1.HostIP": schema_k8sio_api_core_v1_HostIP(ref), - "k8s.io/api/core/v1.HostPathVolumeSource": schema_k8sio_api_core_v1_HostPathVolumeSource(ref), - "k8s.io/api/core/v1.ISCSIPersistentVolumeSource": schema_k8sio_api_core_v1_ISCSIPersistentVolumeSource(ref), - "k8s.io/api/core/v1.ISCSIVolumeSource": schema_k8sio_api_core_v1_ISCSIVolumeSource(ref), - "k8s.io/api/core/v1.KeyToPath": schema_k8sio_api_core_v1_KeyToPath(ref), - "k8s.io/api/core/v1.Lifecycle": schema_k8sio_api_core_v1_Lifecycle(ref), - "k8s.io/api/core/v1.LifecycleHandler": schema_k8sio_api_core_v1_LifecycleHandler(ref), - "k8s.io/api/core/v1.LimitRange": schema_k8sio_api_core_v1_LimitRange(ref), - "k8s.io/api/core/v1.LimitRangeItem": schema_k8sio_api_core_v1_LimitRangeItem(ref), - "k8s.io/api/core/v1.LimitRangeList": schema_k8sio_api_core_v1_LimitRangeList(ref), - "k8s.io/api/core/v1.LimitRangeSpec": schema_k8sio_api_core_v1_LimitRangeSpec(ref), - "k8s.io/api/core/v1.List": schema_k8sio_api_core_v1_List(ref), - "k8s.io/api/core/v1.LoadBalancerIngress": schema_k8sio_api_core_v1_LoadBalancerIngress(ref), - "k8s.io/api/core/v1.LoadBalancerStatus": schema_k8sio_api_core_v1_LoadBalancerStatus(ref), - "k8s.io/api/core/v1.LocalObjectReference": schema_k8sio_api_core_v1_LocalObjectReference(ref), - "k8s.io/api/core/v1.LocalVolumeSource": schema_k8sio_api_core_v1_LocalVolumeSource(ref), - "k8s.io/api/core/v1.ModifyVolumeStatus": schema_k8sio_api_core_v1_ModifyVolumeStatus(ref), - "k8s.io/api/core/v1.NFSVolumeSource": schema_k8sio_api_core_v1_NFSVolumeSource(ref), - "k8s.io/api/core/v1.Namespace": schema_k8sio_api_core_v1_Namespace(ref), - "k8s.io/api/core/v1.NamespaceCondition": schema_k8sio_api_core_v1_NamespaceCondition(ref), - "k8s.io/api/core/v1.NamespaceList": schema_k8sio_api_core_v1_NamespaceList(ref), - "k8s.io/api/core/v1.NamespaceSpec": schema_k8sio_api_core_v1_NamespaceSpec(ref), - "k8s.io/api/core/v1.NamespaceStatus": schema_k8sio_api_core_v1_NamespaceStatus(ref), - "k8s.io/api/core/v1.Node": schema_k8sio_api_core_v1_Node(ref), - "k8s.io/api/core/v1.NodeAddress": schema_k8sio_api_core_v1_NodeAddress(ref), - "k8s.io/api/core/v1.NodeAffinity": schema_k8sio_api_core_v1_NodeAffinity(ref), - "k8s.io/api/core/v1.NodeCondition": schema_k8sio_api_core_v1_NodeCondition(ref), - "k8s.io/api/core/v1.NodeConfigSource": schema_k8sio_api_core_v1_NodeConfigSource(ref), - "k8s.io/api/core/v1.NodeConfigStatus": schema_k8sio_api_core_v1_NodeConfigStatus(ref), - "k8s.io/api/core/v1.NodeDaemonEndpoints": schema_k8sio_api_core_v1_NodeDaemonEndpoints(ref), - "k8s.io/api/core/v1.NodeList": schema_k8sio_api_core_v1_NodeList(ref), - "k8s.io/api/core/v1.NodeProxyOptions": schema_k8sio_api_core_v1_NodeProxyOptions(ref), - "k8s.io/api/core/v1.NodeResources": schema_k8sio_api_core_v1_NodeResources(ref), - "k8s.io/api/core/v1.NodeSelector": schema_k8sio_api_core_v1_NodeSelector(ref), - "k8s.io/api/core/v1.NodeSelectorRequirement": schema_k8sio_api_core_v1_NodeSelectorRequirement(ref), - "k8s.io/api/core/v1.NodeSelectorTerm": schema_k8sio_api_core_v1_NodeSelectorTerm(ref), - "k8s.io/api/core/v1.NodeSpec": schema_k8sio_api_core_v1_NodeSpec(ref), - "k8s.io/api/core/v1.NodeStatus": schema_k8sio_api_core_v1_NodeStatus(ref), - "k8s.io/api/core/v1.NodeSystemInfo": schema_k8sio_api_core_v1_NodeSystemInfo(ref), - "k8s.io/api/core/v1.ObjectFieldSelector": schema_k8sio_api_core_v1_ObjectFieldSelector(ref), - "k8s.io/api/core/v1.ObjectReference": schema_k8sio_api_core_v1_ObjectReference(ref), - "k8s.io/api/core/v1.PersistentVolume": schema_k8sio_api_core_v1_PersistentVolume(ref), - "k8s.io/api/core/v1.PersistentVolumeClaim": schema_k8sio_api_core_v1_PersistentVolumeClaim(ref), - "k8s.io/api/core/v1.PersistentVolumeClaimCondition": schema_k8sio_api_core_v1_PersistentVolumeClaimCondition(ref), - "k8s.io/api/core/v1.PersistentVolumeClaimList": schema_k8sio_api_core_v1_PersistentVolumeClaimList(ref), - "k8s.io/api/core/v1.PersistentVolumeClaimSpec": schema_k8sio_api_core_v1_PersistentVolumeClaimSpec(ref), - "k8s.io/api/core/v1.PersistentVolumeClaimStatus": schema_k8sio_api_core_v1_PersistentVolumeClaimStatus(ref), - "k8s.io/api/core/v1.PersistentVolumeClaimTemplate": schema_k8sio_api_core_v1_PersistentVolumeClaimTemplate(ref), - "k8s.io/api/core/v1.PersistentVolumeClaimVolumeSource": schema_k8sio_api_core_v1_PersistentVolumeClaimVolumeSource(ref), - "k8s.io/api/core/v1.PersistentVolumeList": schema_k8sio_api_core_v1_PersistentVolumeList(ref), - "k8s.io/api/core/v1.PersistentVolumeSource": schema_k8sio_api_core_v1_PersistentVolumeSource(ref), - "k8s.io/api/core/v1.PersistentVolumeSpec": schema_k8sio_api_core_v1_PersistentVolumeSpec(ref), - "k8s.io/api/core/v1.PersistentVolumeStatus": schema_k8sio_api_core_v1_PersistentVolumeStatus(ref), - "k8s.io/api/core/v1.PhotonPersistentDiskVolumeSource": schema_k8sio_api_core_v1_PhotonPersistentDiskVolumeSource(ref), - "k8s.io/api/core/v1.Pod": schema_k8sio_api_core_v1_Pod(ref), - "k8s.io/api/core/v1.PodAffinity": schema_k8sio_api_core_v1_PodAffinity(ref), - "k8s.io/api/core/v1.PodAffinityTerm": schema_k8sio_api_core_v1_PodAffinityTerm(ref), - "k8s.io/api/core/v1.PodAntiAffinity": schema_k8sio_api_core_v1_PodAntiAffinity(ref), - "k8s.io/api/core/v1.PodAttachOptions": schema_k8sio_api_core_v1_PodAttachOptions(ref), - "k8s.io/api/core/v1.PodCondition": schema_k8sio_api_core_v1_PodCondition(ref), - "k8s.io/api/core/v1.PodDNSConfig": schema_k8sio_api_core_v1_PodDNSConfig(ref), - "k8s.io/api/core/v1.PodDNSConfigOption": schema_k8sio_api_core_v1_PodDNSConfigOption(ref), - "k8s.io/api/core/v1.PodExecOptions": schema_k8sio_api_core_v1_PodExecOptions(ref), - "k8s.io/api/core/v1.PodIP": schema_k8sio_api_core_v1_PodIP(ref), - "k8s.io/api/core/v1.PodList": schema_k8sio_api_core_v1_PodList(ref), - "k8s.io/api/core/v1.PodLogOptions": schema_k8sio_api_core_v1_PodLogOptions(ref), - "k8s.io/api/core/v1.PodOS": schema_k8sio_api_core_v1_PodOS(ref), - "k8s.io/api/core/v1.PodPortForwardOptions": schema_k8sio_api_core_v1_PodPortForwardOptions(ref), - "k8s.io/api/core/v1.PodProxyOptions": schema_k8sio_api_core_v1_PodProxyOptions(ref), - "k8s.io/api/core/v1.PodReadinessGate": schema_k8sio_api_core_v1_PodReadinessGate(ref), - "k8s.io/api/core/v1.PodResourceClaim": schema_k8sio_api_core_v1_PodResourceClaim(ref), - "k8s.io/api/core/v1.PodResourceClaimStatus": schema_k8sio_api_core_v1_PodResourceClaimStatus(ref), - "k8s.io/api/core/v1.PodSchedulingGate": schema_k8sio_api_core_v1_PodSchedulingGate(ref), - "k8s.io/api/core/v1.PodSecurityContext": schema_k8sio_api_core_v1_PodSecurityContext(ref), - "k8s.io/api/core/v1.PodSignature": schema_k8sio_api_core_v1_PodSignature(ref), - "k8s.io/api/core/v1.PodSpec": schema_k8sio_api_core_v1_PodSpec(ref), - "k8s.io/api/core/v1.PodStatus": schema_k8sio_api_core_v1_PodStatus(ref), - "k8s.io/api/core/v1.PodStatusResult": schema_k8sio_api_core_v1_PodStatusResult(ref), - "k8s.io/api/core/v1.PodTemplate": schema_k8sio_api_core_v1_PodTemplate(ref), - "k8s.io/api/core/v1.PodTemplateList": schema_k8sio_api_core_v1_PodTemplateList(ref), - "k8s.io/api/core/v1.PodTemplateSpec": schema_k8sio_api_core_v1_PodTemplateSpec(ref), - "k8s.io/api/core/v1.PortStatus": schema_k8sio_api_core_v1_PortStatus(ref), - "k8s.io/api/core/v1.PortworxVolumeSource": schema_k8sio_api_core_v1_PortworxVolumeSource(ref), - "k8s.io/api/core/v1.PreferAvoidPodsEntry": schema_k8sio_api_core_v1_PreferAvoidPodsEntry(ref), - "k8s.io/api/core/v1.PreferredSchedulingTerm": schema_k8sio_api_core_v1_PreferredSchedulingTerm(ref), - "k8s.io/api/core/v1.Probe": schema_k8sio_api_core_v1_Probe(ref), - "k8s.io/api/core/v1.ProbeHandler": schema_k8sio_api_core_v1_ProbeHandler(ref), - "k8s.io/api/core/v1.ProjectedVolumeSource": schema_k8sio_api_core_v1_ProjectedVolumeSource(ref), - "k8s.io/api/core/v1.QuobyteVolumeSource": schema_k8sio_api_core_v1_QuobyteVolumeSource(ref), - "k8s.io/api/core/v1.RBDPersistentVolumeSource": schema_k8sio_api_core_v1_RBDPersistentVolumeSource(ref), - "k8s.io/api/core/v1.RBDVolumeSource": schema_k8sio_api_core_v1_RBDVolumeSource(ref), - "k8s.io/api/core/v1.RangeAllocation": schema_k8sio_api_core_v1_RangeAllocation(ref), - "k8s.io/api/core/v1.ReplicationController": schema_k8sio_api_core_v1_ReplicationController(ref), - "k8s.io/api/core/v1.ReplicationControllerCondition": schema_k8sio_api_core_v1_ReplicationControllerCondition(ref), - "k8s.io/api/core/v1.ReplicationControllerList": schema_k8sio_api_core_v1_ReplicationControllerList(ref), - "k8s.io/api/core/v1.ReplicationControllerSpec": schema_k8sio_api_core_v1_ReplicationControllerSpec(ref), - "k8s.io/api/core/v1.ReplicationControllerStatus": schema_k8sio_api_core_v1_ReplicationControllerStatus(ref), - "k8s.io/api/core/v1.ResourceClaim": schema_k8sio_api_core_v1_ResourceClaim(ref), - "k8s.io/api/core/v1.ResourceFieldSelector": schema_k8sio_api_core_v1_ResourceFieldSelector(ref), - "k8s.io/api/core/v1.ResourceQuota": schema_k8sio_api_core_v1_ResourceQuota(ref), - "k8s.io/api/core/v1.ResourceQuotaList": schema_k8sio_api_core_v1_ResourceQuotaList(ref), - "k8s.io/api/core/v1.ResourceQuotaSpec": schema_k8sio_api_core_v1_ResourceQuotaSpec(ref), - "k8s.io/api/core/v1.ResourceQuotaStatus": schema_k8sio_api_core_v1_ResourceQuotaStatus(ref), - "k8s.io/api/core/v1.ResourceRequirements": schema_k8sio_api_core_v1_ResourceRequirements(ref), - "k8s.io/api/core/v1.SELinuxOptions": schema_k8sio_api_core_v1_SELinuxOptions(ref), - "k8s.io/api/core/v1.ScaleIOPersistentVolumeSource": schema_k8sio_api_core_v1_ScaleIOPersistentVolumeSource(ref), - "k8s.io/api/core/v1.ScaleIOVolumeSource": schema_k8sio_api_core_v1_ScaleIOVolumeSource(ref), - "k8s.io/api/core/v1.ScopeSelector": schema_k8sio_api_core_v1_ScopeSelector(ref), - "k8s.io/api/core/v1.ScopedResourceSelectorRequirement": schema_k8sio_api_core_v1_ScopedResourceSelectorRequirement(ref), - "k8s.io/api/core/v1.SeccompProfile": schema_k8sio_api_core_v1_SeccompProfile(ref), - "k8s.io/api/core/v1.Secret": schema_k8sio_api_core_v1_Secret(ref), - "k8s.io/api/core/v1.SecretEnvSource": schema_k8sio_api_core_v1_SecretEnvSource(ref), - "k8s.io/api/core/v1.SecretKeySelector": schema_k8sio_api_core_v1_SecretKeySelector(ref), - "k8s.io/api/core/v1.SecretList": schema_k8sio_api_core_v1_SecretList(ref), - "k8s.io/api/core/v1.SecretProjection": schema_k8sio_api_core_v1_SecretProjection(ref), - "k8s.io/api/core/v1.SecretReference": schema_k8sio_api_core_v1_SecretReference(ref), - "k8s.io/api/core/v1.SecretVolumeSource": schema_k8sio_api_core_v1_SecretVolumeSource(ref), - "k8s.io/api/core/v1.SecurityContext": schema_k8sio_api_core_v1_SecurityContext(ref), - "k8s.io/api/core/v1.SerializedReference": schema_k8sio_api_core_v1_SerializedReference(ref), - "k8s.io/api/core/v1.Service": schema_k8sio_api_core_v1_Service(ref), - "k8s.io/api/core/v1.ServiceAccount": schema_k8sio_api_core_v1_ServiceAccount(ref), - "k8s.io/api/core/v1.ServiceAccountList": schema_k8sio_api_core_v1_ServiceAccountList(ref), - "k8s.io/api/core/v1.ServiceAccountTokenProjection": schema_k8sio_api_core_v1_ServiceAccountTokenProjection(ref), - "k8s.io/api/core/v1.ServiceList": schema_k8sio_api_core_v1_ServiceList(ref), - "k8s.io/api/core/v1.ServicePort": schema_k8sio_api_core_v1_ServicePort(ref), - "k8s.io/api/core/v1.ServiceProxyOptions": schema_k8sio_api_core_v1_ServiceProxyOptions(ref), - "k8s.io/api/core/v1.ServiceSpec": schema_k8sio_api_core_v1_ServiceSpec(ref), - "k8s.io/api/core/v1.ServiceStatus": schema_k8sio_api_core_v1_ServiceStatus(ref), - "k8s.io/api/core/v1.SessionAffinityConfig": schema_k8sio_api_core_v1_SessionAffinityConfig(ref), - "k8s.io/api/core/v1.SleepAction": schema_k8sio_api_core_v1_SleepAction(ref), - "k8s.io/api/core/v1.StorageOSPersistentVolumeSource": schema_k8sio_api_core_v1_StorageOSPersistentVolumeSource(ref), - "k8s.io/api/core/v1.StorageOSVolumeSource": schema_k8sio_api_core_v1_StorageOSVolumeSource(ref), - "k8s.io/api/core/v1.Sysctl": schema_k8sio_api_core_v1_Sysctl(ref), - "k8s.io/api/core/v1.TCPSocketAction": schema_k8sio_api_core_v1_TCPSocketAction(ref), - "k8s.io/api/core/v1.Taint": schema_k8sio_api_core_v1_Taint(ref), - "k8s.io/api/core/v1.Toleration": schema_k8sio_api_core_v1_Toleration(ref), - "k8s.io/api/core/v1.TopologySelectorLabelRequirement": schema_k8sio_api_core_v1_TopologySelectorLabelRequirement(ref), - "k8s.io/api/core/v1.TopologySelectorTerm": schema_k8sio_api_core_v1_TopologySelectorTerm(ref), - "k8s.io/api/core/v1.TopologySpreadConstraint": schema_k8sio_api_core_v1_TopologySpreadConstraint(ref), - "k8s.io/api/core/v1.TypedLocalObjectReference": schema_k8sio_api_core_v1_TypedLocalObjectReference(ref), - "k8s.io/api/core/v1.TypedObjectReference": schema_k8sio_api_core_v1_TypedObjectReference(ref), - "k8s.io/api/core/v1.Volume": schema_k8sio_api_core_v1_Volume(ref), - "k8s.io/api/core/v1.VolumeDevice": schema_k8sio_api_core_v1_VolumeDevice(ref), - "k8s.io/api/core/v1.VolumeMount": schema_k8sio_api_core_v1_VolumeMount(ref), - "k8s.io/api/core/v1.VolumeNodeAffinity": schema_k8sio_api_core_v1_VolumeNodeAffinity(ref), - "k8s.io/api/core/v1.VolumeProjection": schema_k8sio_api_core_v1_VolumeProjection(ref), - "k8s.io/api/core/v1.VolumeResourceRequirements": schema_k8sio_api_core_v1_VolumeResourceRequirements(ref), - "k8s.io/api/core/v1.VolumeSource": schema_k8sio_api_core_v1_VolumeSource(ref), - "k8s.io/api/core/v1.VsphereVirtualDiskVolumeSource": schema_k8sio_api_core_v1_VsphereVirtualDiskVolumeSource(ref), - "k8s.io/api/core/v1.WeightedPodAffinityTerm": schema_k8sio_api_core_v1_WeightedPodAffinityTerm(ref), - "k8s.io/api/core/v1.WindowsSecurityContextOptions": schema_k8sio_api_core_v1_WindowsSecurityContextOptions(ref), - "k8s.io/api/rbac/v1.AggregationRule": schema_k8sio_api_rbac_v1_AggregationRule(ref), - "k8s.io/api/rbac/v1.ClusterRole": schema_k8sio_api_rbac_v1_ClusterRole(ref), - "k8s.io/api/rbac/v1.ClusterRoleBinding": schema_k8sio_api_rbac_v1_ClusterRoleBinding(ref), - "k8s.io/api/rbac/v1.ClusterRoleBindingList": schema_k8sio_api_rbac_v1_ClusterRoleBindingList(ref), - "k8s.io/api/rbac/v1.ClusterRoleList": schema_k8sio_api_rbac_v1_ClusterRoleList(ref), - "k8s.io/api/rbac/v1.PolicyRule": schema_k8sio_api_rbac_v1_PolicyRule(ref), - "k8s.io/api/rbac/v1.Role": schema_k8sio_api_rbac_v1_Role(ref), - "k8s.io/api/rbac/v1.RoleBinding": schema_k8sio_api_rbac_v1_RoleBinding(ref), - "k8s.io/api/rbac/v1.RoleBindingList": schema_k8sio_api_rbac_v1_RoleBindingList(ref), - "k8s.io/api/rbac/v1.RoleList": schema_k8sio_api_rbac_v1_RoleList(ref), - "k8s.io/api/rbac/v1.RoleRef": schema_k8sio_api_rbac_v1_RoleRef(ref), - "k8s.io/api/rbac/v1.Subject": schema_k8sio_api_rbac_v1_Subject(ref), - "k8s.io/apimachinery/pkg/api/resource.Quantity": schema_apimachinery_pkg_api_resource_Quantity(ref), - "k8s.io/apimachinery/pkg/api/resource.int64Amount": schema_apimachinery_pkg_api_resource_int64Amount(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.APIGroup": schema_pkg_apis_meta_v1_APIGroup(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.APIGroupList": schema_pkg_apis_meta_v1_APIGroupList(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.APIResource": schema_pkg_apis_meta_v1_APIResource(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.APIResourceList": schema_pkg_apis_meta_v1_APIResourceList(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.APIVersions": schema_pkg_apis_meta_v1_APIVersions(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.ApplyOptions": schema_pkg_apis_meta_v1_ApplyOptions(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.Condition": schema_pkg_apis_meta_v1_Condition(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.CreateOptions": schema_pkg_apis_meta_v1_CreateOptions(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.DeleteOptions": schema_pkg_apis_meta_v1_DeleteOptions(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.Duration": schema_pkg_apis_meta_v1_Duration(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.FieldsV1": schema_pkg_apis_meta_v1_FieldsV1(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.GetOptions": schema_pkg_apis_meta_v1_GetOptions(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.GroupKind": schema_pkg_apis_meta_v1_GroupKind(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.GroupResource": schema_pkg_apis_meta_v1_GroupResource(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.GroupVersion": schema_pkg_apis_meta_v1_GroupVersion(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.GroupVersionForDiscovery": schema_pkg_apis_meta_v1_GroupVersionForDiscovery(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.GroupVersionKind": schema_pkg_apis_meta_v1_GroupVersionKind(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.GroupVersionResource": schema_pkg_apis_meta_v1_GroupVersionResource(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.InternalEvent": schema_pkg_apis_meta_v1_InternalEvent(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector": schema_pkg_apis_meta_v1_LabelSelector(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelectorRequirement": schema_pkg_apis_meta_v1_LabelSelectorRequirement(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.List": schema_pkg_apis_meta_v1_List(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta": schema_pkg_apis_meta_v1_ListMeta(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.ListOptions": schema_pkg_apis_meta_v1_ListOptions(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.ManagedFieldsEntry": schema_pkg_apis_meta_v1_ManagedFieldsEntry(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.MicroTime": schema_pkg_apis_meta_v1_MicroTime(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta": schema_pkg_apis_meta_v1_ObjectMeta(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.OwnerReference": schema_pkg_apis_meta_v1_OwnerReference(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.PartialObjectMetadata": schema_pkg_apis_meta_v1_PartialObjectMetadata(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.PartialObjectMetadataList": schema_pkg_apis_meta_v1_PartialObjectMetadataList(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.Patch": schema_pkg_apis_meta_v1_Patch(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.PatchOptions": schema_pkg_apis_meta_v1_PatchOptions(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.Preconditions": schema_pkg_apis_meta_v1_Preconditions(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.RootPaths": schema_pkg_apis_meta_v1_RootPaths(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.ServerAddressByClientCIDR": schema_pkg_apis_meta_v1_ServerAddressByClientCIDR(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.Status": schema_pkg_apis_meta_v1_Status(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.StatusCause": schema_pkg_apis_meta_v1_StatusCause(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.StatusDetails": schema_pkg_apis_meta_v1_StatusDetails(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.Table": schema_pkg_apis_meta_v1_Table(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.TableColumnDefinition": schema_pkg_apis_meta_v1_TableColumnDefinition(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.TableOptions": schema_pkg_apis_meta_v1_TableOptions(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.TableRow": schema_pkg_apis_meta_v1_TableRow(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.TableRowCondition": schema_pkg_apis_meta_v1_TableRowCondition(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.Time": schema_pkg_apis_meta_v1_Time(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.Timestamp": schema_pkg_apis_meta_v1_Timestamp(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.TypeMeta": schema_pkg_apis_meta_v1_TypeMeta(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.UpdateOptions": schema_pkg_apis_meta_v1_UpdateOptions(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.WatchEvent": schema_pkg_apis_meta_v1_WatchEvent(ref), - "k8s.io/apimachinery/pkg/runtime.RawExtension": schema_k8sio_apimachinery_pkg_runtime_RawExtension(ref), - "k8s.io/apimachinery/pkg/runtime.TypeMeta": schema_k8sio_apimachinery_pkg_runtime_TypeMeta(ref), - "k8s.io/apimachinery/pkg/runtime.Unknown": schema_k8sio_apimachinery_pkg_runtime_Unknown(ref), - "k8s.io/apimachinery/pkg/util/intstr.IntOrString": schema_apimachinery_pkg_util_intstr_IntOrString(ref), - "k8s.io/apimachinery/pkg/version.Info": schema_k8sio_apimachinery_pkg_version_Info(ref), - "kmodules.xyz/client-go/api/v1.CAPIClusterInfo": schema_kmodulesxyz_client_go_api_v1_CAPIClusterInfo(ref), - "kmodules.xyz/client-go/api/v1.CertificatePrivateKey": schema_kmodulesxyz_client_go_api_v1_CertificatePrivateKey(ref), - "kmodules.xyz/client-go/api/v1.CertificateSpec": schema_kmodulesxyz_client_go_api_v1_CertificateSpec(ref), - "kmodules.xyz/client-go/api/v1.ClusterMetadata": schema_kmodulesxyz_client_go_api_v1_ClusterMetadata(ref), - "kmodules.xyz/client-go/api/v1.Condition": schema_kmodulesxyz_client_go_api_v1_Condition(ref), - "kmodules.xyz/client-go/api/v1.HealthCheckSpec": schema_kmodulesxyz_client_go_api_v1_HealthCheckSpec(ref), - "kmodules.xyz/client-go/api/v1.ImageInfo": schema_kmodulesxyz_client_go_api_v1_ImageInfo(ref), - "kmodules.xyz/client-go/api/v1.Lineage": schema_kmodulesxyz_client_go_api_v1_Lineage(ref), - "kmodules.xyz/client-go/api/v1.ObjectID": schema_kmodulesxyz_client_go_api_v1_ObjectID(ref), - "kmodules.xyz/client-go/api/v1.ObjectInfo": schema_kmodulesxyz_client_go_api_v1_ObjectInfo(ref), - "kmodules.xyz/client-go/api/v1.ObjectReference": schema_kmodulesxyz_client_go_api_v1_ObjectReference(ref), - "kmodules.xyz/client-go/api/v1.PullCredentials": schema_kmodulesxyz_client_go_api_v1_PullCredentials(ref), - "kmodules.xyz/client-go/api/v1.ReadonlyHealthCheckSpec": schema_kmodulesxyz_client_go_api_v1_ReadonlyHealthCheckSpec(ref), - "kmodules.xyz/client-go/api/v1.ResourceID": schema_kmodulesxyz_client_go_api_v1_ResourceID(ref), - "kmodules.xyz/client-go/api/v1.TLSConfig": schema_kmodulesxyz_client_go_api_v1_TLSConfig(ref), - "kmodules.xyz/client-go/api/v1.TimeOfDay": schema_kmodulesxyz_client_go_api_v1_TimeOfDay(ref), - "kmodules.xyz/client-go/api/v1.TypedObjectReference": schema_kmodulesxyz_client_go_api_v1_TypedObjectReference(ref), - "kmodules.xyz/client-go/api/v1.X509Subject": schema_kmodulesxyz_client_go_api_v1_X509Subject(ref), - "kmodules.xyz/client-go/api/v1.stringSetMerger": schema_kmodulesxyz_client_go_api_v1_stringSetMerger(ref), - } -} - -func schema_license_proxyserver_apis_proxyserver_v1alpha1_LicenseRequest(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "request": { - SchemaProps: spec.SchemaProps{ - Description: "Request describes the attributes for the graph request.", - Ref: ref("go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1.LicenseRequestRequest"), - }, - }, - "response": { - SchemaProps: spec.SchemaProps{ - Description: "Response describes the attributes for the graph response.", - Ref: ref("go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1.LicenseRequestResponse"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1.LicenseRequestRequest", "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1.LicenseRequestResponse"}, - } -} - -func schema_license_proxyserver_apis_proxyserver_v1alpha1_LicenseRequestRequest(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "features": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"features"}, - }, - }, - } -} - -func schema_license_proxyserver_apis_proxyserver_v1alpha1_LicenseRequestResponse(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "license": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"license"}, - }, - }, - } -} - -func schema_license_proxyserver_apis_proxyserver_v1alpha1_LicenseStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "LicenseStatus is the Schema for the licensestatuses API", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1.LicenseStatusSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1.LicenseStatusStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1.LicenseStatusSpec", "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1.LicenseStatusStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_license_proxyserver_apis_proxyserver_v1alpha1_LicenseStatusList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "LicenseStatusList contains a list of LicenseStatus", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1.LicenseStatus"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1.LicenseStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_license_proxyserver_apis_proxyserver_v1alpha1_LicenseStatusSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "LicenseStatusSpec defines the desired state of License", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "features": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "user": { - SchemaProps: spec.SchemaProps{ - Description: "Result contains extra details into why an admission request was denied. This field IS NOT consulted in any way if \"Allowed\" is \"true\".", - Ref: ref("go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1.UserInfo"), - }, - }, - }, - Required: []string{"features"}, - }, - }, - Dependencies: []string{ - "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1.UserInfo"}, - } -} - -func schema_license_proxyserver_apis_proxyserver_v1alpha1_LicenseStatusStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "LicenseStatusStatus defines the status of License", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "contract": { - SchemaProps: spec.SchemaProps{ - Ref: ref("go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1.Contract"), - }, - }, - "license": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1.License"), - }, - }, - }, - Required: []string{"license"}, - }, - }, - Dependencies: []string{ - "go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1.Contract", "go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1.License"}, - } -} - -func schema_license_proxyserver_apis_proxyserver_v1alpha1_UserInfo(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "UserInfo holds the information about the user needed to implement the user.Info interface.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "username": { - SchemaProps: spec.SchemaProps{ - Description: "The name that uniquely identifies this user among all active users.", - Type: []string{"string"}, - Format: "", - }, - }, - "uid": { - SchemaProps: spec.SchemaProps{ - Description: "A unique value that identifies this user across time. If this user is deleted and another user by the same name is added, they will have different UIDs.", - Type: []string{"string"}, - Format: "", - }, - }, - "groups": { - SchemaProps: spec.SchemaProps{ - Description: "The names of groups this user is a part of.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "extra": { - SchemaProps: spec.SchemaProps{ - Description: "Any additional information provided by the authenticator.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_apps_v1_ControllerRevision(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ControllerRevision implements an immutable snapshot of state data. Clients are responsible for serializing and deserializing the objects that contain their internal state. Once a ControllerRevision has been successfully created, it can not be updated. The API Server will fail validation of all requests that attempt to mutate the Data field. ControllerRevisions may, however, be deleted. Note that, due to its use by both the DaemonSet and StatefulSet controllers for update and rollback, this object is beta. However, it may be subject to name and representation changes in future releases, and clients should not depend on its stability. It is primarily for internal use by controllers.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "data": { - SchemaProps: spec.SchemaProps{ - Description: "Data is the serialized representation of the state.", - Ref: ref("k8s.io/apimachinery/pkg/runtime.RawExtension"), - }, - }, - "revision": { - SchemaProps: spec.SchemaProps{ - Description: "Revision indicates the revision of the state represented by Data.", - Default: 0, - Type: []string{"integer"}, - Format: "int64", - }, - }, - }, - Required: []string{"revision"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "k8s.io/apimachinery/pkg/runtime.RawExtension"}, - } -} - -func schema_k8sio_api_apps_v1_ControllerRevisionList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ControllerRevisionList is a resource containing a list of ControllerRevision objects.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is the list of ControllerRevisions", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/apps/v1.ControllerRevision"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/apps/v1.ControllerRevision", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_apps_v1_DaemonSet(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "DaemonSet represents the configuration of a daemon set.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "The desired behavior of this daemon set. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/apps/v1.DaemonSetSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "The current status of this daemon set. This data may be out of date by some window of time. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/apps/v1.DaemonSetStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/apps/v1.DaemonSetSpec", "k8s.io/api/apps/v1.DaemonSetStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_apps_v1_DaemonSetCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "DaemonSetCondition describes the state of a DaemonSet at a certain point.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of DaemonSet condition.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status of the condition, one of True, False, Unknown.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "lastTransitionTime": { - SchemaProps: spec.SchemaProps{ - Description: "Last time the condition transitioned from one status to another.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "The reason for the condition's last transition.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "A human readable message indicating details about the transition.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_apps_v1_DaemonSetList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "DaemonSetList is a collection of daemon sets.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "A list of daemon sets.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/apps/v1.DaemonSet"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/apps/v1.DaemonSet", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_apps_v1_DaemonSetSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "DaemonSetSpec is the specification of a daemon set.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "selector": { - SchemaProps: spec.SchemaProps{ - Description: "A label query over pods that are managed by the daemon set. Must match in order to be controlled. It must match the pod template's labels. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), - }, - }, - "template": { - SchemaProps: spec.SchemaProps{ - Description: "An object that describes the pod that will be created. The DaemonSet will create exactly one copy of this pod on every node that matches the template's node selector (or on every node if no node selector is specified). The only allowed template.spec.restartPolicy value is \"Always\". More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#pod-template", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodTemplateSpec"), - }, - }, - "updateStrategy": { - SchemaProps: spec.SchemaProps{ - Description: "An update strategy to replace existing DaemonSet pods with new pods.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/apps/v1.DaemonSetUpdateStrategy"), - }, - }, - "minReadySeconds": { - SchemaProps: spec.SchemaProps{ - Description: "The minimum number of seconds for which a newly created DaemonSet pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready).", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "revisionHistoryLimit": { - SchemaProps: spec.SchemaProps{ - Description: "The number of old history to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 10.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - Required: []string{"selector", "template"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/apps/v1.DaemonSetUpdateStrategy", "k8s.io/api/core/v1.PodTemplateSpec", "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"}, - } -} - -func schema_k8sio_api_apps_v1_DaemonSetStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "DaemonSetStatus represents the current status of a daemon set.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "currentNumberScheduled": { - SchemaProps: spec.SchemaProps{ - Description: "The number of nodes that are running at least 1 daemon pod and are supposed to run the daemon pod. More info: https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "numberMisscheduled": { - SchemaProps: spec.SchemaProps{ - Description: "The number of nodes that are running the daemon pod, but are not supposed to run the daemon pod. More info: https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "desiredNumberScheduled": { - SchemaProps: spec.SchemaProps{ - Description: "The total number of nodes that should be running the daemon pod (including nodes correctly running the daemon pod). More info: https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "numberReady": { - SchemaProps: spec.SchemaProps{ - Description: "numberReady is the number of nodes that should be running the daemon pod and have one or more of the daemon pod running with a Ready Condition.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "observedGeneration": { - SchemaProps: spec.SchemaProps{ - Description: "The most recent generation observed by the daemon set controller.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "updatedNumberScheduled": { - SchemaProps: spec.SchemaProps{ - Description: "The total number of nodes that are running updated daemon pod", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "numberAvailable": { - SchemaProps: spec.SchemaProps{ - Description: "The number of nodes that should be running the daemon pod and have one or more of the daemon pod running and available (ready for at least spec.minReadySeconds)", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "numberUnavailable": { - SchemaProps: spec.SchemaProps{ - Description: "The number of nodes that should be running the daemon pod and have none of the daemon pod running and available (ready for at least spec.minReadySeconds)", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "collisionCount": { - SchemaProps: spec.SchemaProps{ - Description: "Count of hash collisions for the DaemonSet. The DaemonSet controller uses this field as a collision avoidance mechanism when it needs to create the name for the newest ControllerRevision.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "conditions": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Represents the latest available observations of a DaemonSet's current state.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/apps/v1.DaemonSetCondition"), - }, - }, - }, - }, - }, - }, - Required: []string{"currentNumberScheduled", "numberMisscheduled", "desiredNumberScheduled", "numberReady"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/apps/v1.DaemonSetCondition"}, - } -} - -func schema_k8sio_api_apps_v1_DaemonSetUpdateStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "DaemonSetUpdateStrategy is a struct used to control the update strategy for a DaemonSet.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of daemon set update. Can be \"RollingUpdate\" or \"OnDelete\". Default is RollingUpdate.\n\nPossible enum values:\n - `\"OnDelete\"` Replace the old daemons only when it's killed\n - `\"RollingUpdate\"` Replace the old daemons by new ones using rolling update i.e replace them on each node one after the other.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"OnDelete", "RollingUpdate"}, - }, - }, - "rollingUpdate": { - SchemaProps: spec.SchemaProps{ - Description: "Rolling update config params. Present only if type = \"RollingUpdate\".", - Ref: ref("k8s.io/api/apps/v1.RollingUpdateDaemonSet"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/apps/v1.RollingUpdateDaemonSet"}, - } -} - -func schema_k8sio_api_apps_v1_Deployment(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Deployment enables declarative updates for Pods and ReplicaSets.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Specification of the desired behavior of the Deployment.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/apps/v1.DeploymentSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Most recently observed status of the Deployment.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/apps/v1.DeploymentStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/apps/v1.DeploymentSpec", "k8s.io/api/apps/v1.DeploymentStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_apps_v1_DeploymentCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "DeploymentCondition describes the state of a deployment at a certain point.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of deployment condition.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status of the condition, one of True, False, Unknown.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "lastUpdateTime": { - SchemaProps: spec.SchemaProps{ - Description: "The last time this condition was updated.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "lastTransitionTime": { - SchemaProps: spec.SchemaProps{ - Description: "Last time the condition transitioned from one status to another.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "The reason for the condition's last transition.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "A human readable message indicating details about the transition.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_apps_v1_DeploymentList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "DeploymentList is a list of Deployments.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is the list of Deployments.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/apps/v1.Deployment"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/apps/v1.Deployment", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_apps_v1_DeploymentSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "DeploymentSpec is the specification of the desired behavior of the Deployment.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "replicas": { - SchemaProps: spec.SchemaProps{ - Description: "Number of desired pods. This is a pointer to distinguish between explicit zero and not specified. Defaults to 1.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "selector": { - SchemaProps: spec.SchemaProps{ - Description: "Label selector for pods. Existing ReplicaSets whose pods are selected by this will be the ones affected by this deployment. It must match the pod template's labels.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), - }, - }, - "template": { - SchemaProps: spec.SchemaProps{ - Description: "Template describes the pods that will be created. The only allowed template.spec.restartPolicy value is \"Always\".", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodTemplateSpec"), - }, - }, - "strategy": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-strategy": "retainKeys", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "The deployment strategy to use to replace existing pods with new ones.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/apps/v1.DeploymentStrategy"), - }, - }, - "minReadySeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready)", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "revisionHistoryLimit": { - SchemaProps: spec.SchemaProps{ - Description: "The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 10.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "paused": { - SchemaProps: spec.SchemaProps{ - Description: "Indicates that the deployment is paused.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "progressDeadlineSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "The maximum time in seconds for a deployment to make progress before it is considered to be failed. The deployment controller will continue to process failed deployments and a condition with a ProgressDeadlineExceeded reason will be surfaced in the deployment status. Note that progress will not be estimated during the time a deployment is paused. Defaults to 600s.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - Required: []string{"selector", "template"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/apps/v1.DeploymentStrategy", "k8s.io/api/core/v1.PodTemplateSpec", "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"}, - } -} - -func schema_k8sio_api_apps_v1_DeploymentStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "DeploymentStatus is the most recently observed status of the Deployment.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "observedGeneration": { - SchemaProps: spec.SchemaProps{ - Description: "The generation observed by the deployment controller.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "replicas": { - SchemaProps: spec.SchemaProps{ - Description: "Total number of non-terminated pods targeted by this deployment (their labels match the selector).", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "updatedReplicas": { - SchemaProps: spec.SchemaProps{ - Description: "Total number of non-terminated pods targeted by this deployment that have the desired template spec.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "readyReplicas": { - SchemaProps: spec.SchemaProps{ - Description: "readyReplicas is the number of pods targeted by this Deployment with a Ready Condition.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "availableReplicas": { - SchemaProps: spec.SchemaProps{ - Description: "Total number of available pods (ready for at least minReadySeconds) targeted by this deployment.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "unavailableReplicas": { - SchemaProps: spec.SchemaProps{ - Description: "Total number of unavailable pods targeted by this deployment. This is the total number of pods that are still required for the deployment to have 100% available capacity. They may either be pods that are running but not yet available or pods that still have not been created.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "conditions": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Represents the latest available observations of a deployment's current state.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/apps/v1.DeploymentCondition"), - }, - }, - }, - }, - }, - "collisionCount": { - SchemaProps: spec.SchemaProps{ - Description: "Count of hash collisions for the Deployment. The Deployment controller uses this field as a collision avoidance mechanism when it needs to create the name for the newest ReplicaSet.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/apps/v1.DeploymentCondition"}, - } -} - -func schema_k8sio_api_apps_v1_DeploymentStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "DeploymentStrategy describes how to replace existing pods with new ones.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of deployment. Can be \"Recreate\" or \"RollingUpdate\". Default is RollingUpdate.\n\nPossible enum values:\n - `\"Recreate\"` Kill all existing pods before creating new ones.\n - `\"RollingUpdate\"` Replace the old ReplicaSets by new one using rolling update i.e gradually scale down the old ReplicaSets and scale up the new one.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Recreate", "RollingUpdate"}, - }, - }, - "rollingUpdate": { - SchemaProps: spec.SchemaProps{ - Description: "Rolling update config params. Present only if DeploymentStrategyType = RollingUpdate.", - Ref: ref("k8s.io/api/apps/v1.RollingUpdateDeployment"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/apps/v1.RollingUpdateDeployment"}, - } -} - -func schema_k8sio_api_apps_v1_ReplicaSet(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ReplicaSet ensures that a specified number of pod replicas are running at any given time.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "If the Labels of a ReplicaSet are empty, they are defaulted to be the same as the Pod(s) that the ReplicaSet manages. Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Spec defines the specification of the desired behavior of the ReplicaSet. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/apps/v1.ReplicaSetSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status is the most recently observed status of the ReplicaSet. This data may be out of date by some window of time. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/apps/v1.ReplicaSetStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/apps/v1.ReplicaSetSpec", "k8s.io/api/apps/v1.ReplicaSetStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_apps_v1_ReplicaSetCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ReplicaSetCondition describes the state of a replica set at a certain point.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of replica set condition.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status of the condition, one of True, False, Unknown.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "lastTransitionTime": { - SchemaProps: spec.SchemaProps{ - Description: "The last time the condition transitioned from one status to another.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "The reason for the condition's last transition.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "A human readable message indicating details about the transition.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_apps_v1_ReplicaSetList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ReplicaSetList is a collection of ReplicaSets.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of ReplicaSets. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/apps/v1.ReplicaSet"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/apps/v1.ReplicaSet", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_apps_v1_ReplicaSetSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ReplicaSetSpec is the specification of a ReplicaSet.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "replicas": { - SchemaProps: spec.SchemaProps{ - Description: "Replicas is the number of desired replicas. This is a pointer to distinguish between explicit zero and unspecified. Defaults to 1. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller/#what-is-a-replicationcontroller", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "minReadySeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready)", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "selector": { - SchemaProps: spec.SchemaProps{ - Description: "Selector is a label query over pods that should match the replica count. Label keys and values that must match in order to be controlled by this replica set. It must match the pod template's labels. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), - }, - }, - "template": { - SchemaProps: spec.SchemaProps{ - Description: "Template is the object that describes the pod that will be created if insufficient replicas are detected. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#pod-template", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodTemplateSpec"), - }, - }, - }, - Required: []string{"selector"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodTemplateSpec", "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"}, - } -} - -func schema_k8sio_api_apps_v1_ReplicaSetStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ReplicaSetStatus represents the current status of a ReplicaSet.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "replicas": { - SchemaProps: spec.SchemaProps{ - Description: "Replicas is the most recently observed number of replicas. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller/#what-is-a-replicationcontroller", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "fullyLabeledReplicas": { - SchemaProps: spec.SchemaProps{ - Description: "The number of pods that have labels matching the labels of the pod template of the replicaset.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "readyReplicas": { - SchemaProps: spec.SchemaProps{ - Description: "readyReplicas is the number of pods targeted by this ReplicaSet with a Ready Condition.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "availableReplicas": { - SchemaProps: spec.SchemaProps{ - Description: "The number of available replicas (ready for at least minReadySeconds) for this replica set.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "observedGeneration": { - SchemaProps: spec.SchemaProps{ - Description: "ObservedGeneration reflects the generation of the most recently observed ReplicaSet.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "conditions": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Represents the latest available observations of a replica set's current state.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/apps/v1.ReplicaSetCondition"), - }, - }, - }, - }, - }, - }, - Required: []string{"replicas"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/apps/v1.ReplicaSetCondition"}, - } -} - -func schema_k8sio_api_apps_v1_RollingUpdateDaemonSet(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Spec to control the desired behavior of daemon set rolling update.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "maxUnavailable": { - SchemaProps: spec.SchemaProps{ - Description: "The maximum number of DaemonSet pods that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of total number of DaemonSet pods at the start of the update (ex: 10%). Absolute number is calculated from percentage by rounding up. This cannot be 0 if MaxSurge is 0 Default value is 1. Example: when this is set to 30%, at most 30% of the total number of nodes that should be running the daemon pod (i.e. status.desiredNumberScheduled) can have their pods stopped for an update at any given time. The update starts by stopping at most 30% of those DaemonSet pods and then brings up new DaemonSet pods in their place. Once the new pods are available, it then proceeds onto other DaemonSet pods, thus ensuring that at least 70% of original number of DaemonSet pods are available at all times during the update.", - Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), - }, - }, - "maxSurge": { - SchemaProps: spec.SchemaProps{ - Description: "The maximum number of nodes with an existing available DaemonSet pod that can have an updated DaemonSet pod during during an update. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number is calculated from percentage by rounding up to a minimum of 1. Default value is 0. Example: when this is set to 30%, at most 30% of the total number of nodes that should be running the daemon pod (i.e. status.desiredNumberScheduled) can have their a new pod created before the old pod is marked as deleted. The update starts by launching new pods on 30% of nodes. Once an updated pod is available (Ready for at least minReadySeconds) the old DaemonSet pod on that node is marked deleted. If the old pod becomes unavailable for any reason (Ready transitions to false, is evicted, or is drained) an updated pod is immediatedly created on that node without considering surge limits. Allowing surge implies the possibility that the resources consumed by the daemonset on any given node can double if the readiness check fails, and so resource intensive daemonsets should take into account that they may cause evictions during disruption.", - Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/util/intstr.IntOrString"}, - } -} - -func schema_k8sio_api_apps_v1_RollingUpdateDeployment(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Spec to control the desired behavior of rolling update.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "maxUnavailable": { - SchemaProps: spec.SchemaProps{ - Description: "The maximum number of pods that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). Absolute number is calculated from percentage by rounding down. This can not be 0 if MaxSurge is 0. Defaults to 25%. Example: when this is set to 30%, the old ReplicaSet can be scaled down to 70% of desired pods immediately when the rolling update starts. Once new pods are ready, old ReplicaSet can be scaled down further, followed by scaling up the new ReplicaSet, ensuring that the total number of pods available at all times during the update is at least 70% of desired pods.", - Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), - }, - }, - "maxSurge": { - SchemaProps: spec.SchemaProps{ - Description: "The maximum number of pods that can be scheduled above the desired number of pods. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number is calculated from percentage by rounding up. Defaults to 25%. Example: when this is set to 30%, the new ReplicaSet can be scaled up immediately when the rolling update starts, such that the total number of old and new pods do not exceed 130% of desired pods. Once old pods have been killed, new ReplicaSet can be scaled up further, ensuring that total number of pods running at any time during the update is at most 130% of desired pods.", - Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/util/intstr.IntOrString"}, - } -} - -func schema_k8sio_api_apps_v1_RollingUpdateStatefulSetStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "RollingUpdateStatefulSetStrategy is used to communicate parameter for RollingUpdateStatefulSetStrategyType.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "partition": { - SchemaProps: spec.SchemaProps{ - Description: "Partition indicates the ordinal at which the StatefulSet should be partitioned for updates. During a rolling update, all pods from ordinal Replicas-1 to Partition are updated. All pods from ordinal Partition-1 to 0 remain untouched. This is helpful in being able to do a canary based deployment. The default value is 0.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "maxUnavailable": { - SchemaProps: spec.SchemaProps{ - Description: "The maximum number of pods that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). Absolute number is calculated from percentage by rounding up. This can not be 0. Defaults to 1. This field is alpha-level and is only honored by servers that enable the MaxUnavailableStatefulSet feature. The field applies to all pods in the range 0 to Replicas-1. That means if there is any unavailable pod in the range 0 to Replicas-1, it will be counted towards MaxUnavailable.", - Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/util/intstr.IntOrString"}, - } -} - -func schema_k8sio_api_apps_v1_StatefulSet(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "StatefulSet represents a set of pods with consistent identities. Identities are defined as:\n - Network: A single stable DNS and hostname.\n - Storage: As many VolumeClaims as requested.\n\nThe StatefulSet guarantees that a given network identity will always map to the same storage identity.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Spec defines the desired identities of pods in this set.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/apps/v1.StatefulSetSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status is the current status of Pods in this StatefulSet. This data may be out of date by some window of time.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/apps/v1.StatefulSetStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/apps/v1.StatefulSetSpec", "k8s.io/api/apps/v1.StatefulSetStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_apps_v1_StatefulSetCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "StatefulSetCondition describes the state of a statefulset at a certain point.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of statefulset condition.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status of the condition, one of True, False, Unknown.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "lastTransitionTime": { - SchemaProps: spec.SchemaProps{ - Description: "Last time the condition transitioned from one status to another.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "The reason for the condition's last transition.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "A human readable message indicating details about the transition.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_apps_v1_StatefulSetList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "StatefulSetList is a collection of StatefulSets.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is the list of stateful sets.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/apps/v1.StatefulSet"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/apps/v1.StatefulSet", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_apps_v1_StatefulSetOrdinals(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "StatefulSetOrdinals describes the policy used for replica ordinal assignment in this StatefulSet.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "start": { - SchemaProps: spec.SchemaProps{ - Description: "start is the number representing the first replica's index. It may be used to number replicas from an alternate index (eg: 1-indexed) over the default 0-indexed names, or to orchestrate progressive movement of replicas from one StatefulSet to another. If set, replica indices will be in the range:\n [.spec.ordinals.start, .spec.ordinals.start + .spec.replicas).\nIf unset, defaults to 0. Replica indices will be in the range:\n [0, .spec.replicas).", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_apps_v1_StatefulSetPersistentVolumeClaimRetentionPolicy(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "StatefulSetPersistentVolumeClaimRetentionPolicy describes the policy used for PVCs created from the StatefulSet VolumeClaimTemplates.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "whenDeleted": { - SchemaProps: spec.SchemaProps{ - Description: "WhenDeleted specifies what happens to PVCs created from StatefulSet VolumeClaimTemplates when the StatefulSet is deleted. The default policy of `Retain` causes PVCs to not be affected by StatefulSet deletion. The `Delete` policy causes those PVCs to be deleted.", - Type: []string{"string"}, - Format: "", - }, - }, - "whenScaled": { - SchemaProps: spec.SchemaProps{ - Description: "WhenScaled specifies what happens to PVCs created from StatefulSet VolumeClaimTemplates when the StatefulSet is scaled down. The default policy of `Retain` causes PVCs to not be affected by a scaledown. The `Delete` policy causes the associated PVCs for any excess pods above the replica count to be deleted.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_apps_v1_StatefulSetSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A StatefulSetSpec is the specification of a StatefulSet.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "replicas": { - SchemaProps: spec.SchemaProps{ - Description: "replicas is the desired number of replicas of the given Template. These are replicas in the sense that they are instantiations of the same Template, but individual replicas also have a consistent identity. If unspecified, defaults to 1.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "selector": { - SchemaProps: spec.SchemaProps{ - Description: "selector is a label query over pods that should match the replica count. It must match the pod template's labels. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), - }, - }, - "template": { - SchemaProps: spec.SchemaProps{ - Description: "template is the object that describes the pod that will be created if insufficient replicas are detected. Each pod stamped out by the StatefulSet will fulfill this Template, but have a unique identity from the rest of the StatefulSet. Each pod will be named with the format -. For example, a pod in a StatefulSet named \"web\" with index number \"3\" would be named \"web-3\". The only allowed template.spec.restartPolicy value is \"Always\".", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodTemplateSpec"), - }, - }, - "volumeClaimTemplates": { - SchemaProps: spec.SchemaProps{ - Description: "volumeClaimTemplates is a list of claims that pods are allowed to reference. The StatefulSet controller is responsible for mapping network identities to claims in a way that maintains the identity of a pod. Every claim in this list must have at least one matching (by name) volumeMount in one container in the template. A claim in this list takes precedence over any volumes in the template, with the same name.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PersistentVolumeClaim"), - }, - }, - }, - }, - }, - "serviceName": { - SchemaProps: spec.SchemaProps{ - Description: "serviceName is the name of the service that governs this StatefulSet. This service must exist before the StatefulSet, and is responsible for the network identity of the set. Pods get DNS/hostnames that follow the pattern: pod-specific-string.serviceName.default.svc.cluster.local where \"pod-specific-string\" is managed by the StatefulSet controller.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "podManagementPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "podManagementPolicy controls how pods are created during initial scale up, when replacing pods on nodes, or when scaling down. The default policy is `OrderedReady`, where pods are created in increasing order (pod-0, then pod-1, etc) and the controller will wait until each pod is ready before continuing. When scaling down, the pods are removed in the opposite order. The alternative policy is `Parallel` which will create pods in parallel to match the desired scale without waiting, and on scale down will delete all pods at once.\n\nPossible enum values:\n - `\"OrderedReady\"` will create pods in strictly increasing order on scale up and strictly decreasing order on scale down, progressing only when the previous pod is ready or terminated. At most one pod will be changed at any time.\n - `\"Parallel\"` will create and delete pods as soon as the stateful set replica count is changed, and will not wait for pods to be ready or complete termination.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"OrderedReady", "Parallel"}, - }, - }, - "updateStrategy": { - SchemaProps: spec.SchemaProps{ - Description: "updateStrategy indicates the StatefulSetUpdateStrategy that will be employed to update Pods in the StatefulSet when a revision is made to Template.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/apps/v1.StatefulSetUpdateStrategy"), - }, - }, - "revisionHistoryLimit": { - SchemaProps: spec.SchemaProps{ - Description: "revisionHistoryLimit is the maximum number of revisions that will be maintained in the StatefulSet's revision history. The revision history consists of all revisions not represented by a currently applied StatefulSetSpec version. The default value is 10.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "minReadySeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Minimum number of seconds for which a newly created pod should be ready without any of its container crashing for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready)", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "persistentVolumeClaimRetentionPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "persistentVolumeClaimRetentionPolicy describes the lifecycle of persistent volume claims created from volumeClaimTemplates. By default, all persistent volume claims are created as needed and retained until manually deleted. This policy allows the lifecycle to be altered, for example by deleting persistent volume claims when their stateful set is deleted, or when their pod is scaled down. This requires the StatefulSetAutoDeletePVC feature gate to be enabled, which is alpha. +optional", - Ref: ref("k8s.io/api/apps/v1.StatefulSetPersistentVolumeClaimRetentionPolicy"), - }, - }, - "ordinals": { - SchemaProps: spec.SchemaProps{ - Description: "ordinals controls the numbering of replica indices in a StatefulSet. The default ordinals behavior assigns a \"0\" index to the first replica and increments the index by one for each additional replica requested. Using the ordinals field requires the StatefulSetStartOrdinal feature gate to be enabled, which is beta.", - Ref: ref("k8s.io/api/apps/v1.StatefulSetOrdinals"), - }, - }, - }, - Required: []string{"selector", "template", "serviceName"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/apps/v1.StatefulSetOrdinals", "k8s.io/api/apps/v1.StatefulSetPersistentVolumeClaimRetentionPolicy", "k8s.io/api/apps/v1.StatefulSetUpdateStrategy", "k8s.io/api/core/v1.PersistentVolumeClaim", "k8s.io/api/core/v1.PodTemplateSpec", "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"}, - } -} - -func schema_k8sio_api_apps_v1_StatefulSetStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "StatefulSetStatus represents the current state of a StatefulSet.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "observedGeneration": { - SchemaProps: spec.SchemaProps{ - Description: "observedGeneration is the most recent generation observed for this StatefulSet. It corresponds to the StatefulSet's generation, which is updated on mutation by the API Server.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "replicas": { - SchemaProps: spec.SchemaProps{ - Description: "replicas is the number of Pods created by the StatefulSet controller.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "readyReplicas": { - SchemaProps: spec.SchemaProps{ - Description: "readyReplicas is the number of pods created for this StatefulSet with a Ready Condition.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "currentReplicas": { - SchemaProps: spec.SchemaProps{ - Description: "currentReplicas is the number of Pods created by the StatefulSet controller from the StatefulSet version indicated by currentRevision.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "updatedReplicas": { - SchemaProps: spec.SchemaProps{ - Description: "updatedReplicas is the number of Pods created by the StatefulSet controller from the StatefulSet version indicated by updateRevision.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "currentRevision": { - SchemaProps: spec.SchemaProps{ - Description: "currentRevision, if not empty, indicates the version of the StatefulSet used to generate Pods in the sequence [0,currentReplicas).", - Type: []string{"string"}, - Format: "", - }, - }, - "updateRevision": { - SchemaProps: spec.SchemaProps{ - Description: "updateRevision, if not empty, indicates the version of the StatefulSet used to generate Pods in the sequence [replicas-updatedReplicas,replicas)", - Type: []string{"string"}, - Format: "", - }, - }, - "collisionCount": { - SchemaProps: spec.SchemaProps{ - Description: "collisionCount is the count of hash collisions for the StatefulSet. The StatefulSet controller uses this field as a collision avoidance mechanism when it needs to create the name for the newest ControllerRevision.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "conditions": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Represents the latest available observations of a statefulset's current state.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/apps/v1.StatefulSetCondition"), - }, - }, - }, - }, - }, - "availableReplicas": { - SchemaProps: spec.SchemaProps{ - Description: "Total number of available pods (ready for at least minReadySeconds) targeted by this statefulset.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - Required: []string{"replicas"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/apps/v1.StatefulSetCondition"}, - } -} - -func schema_k8sio_api_apps_v1_StatefulSetUpdateStrategy(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "StatefulSetUpdateStrategy indicates the strategy that the StatefulSet controller will use to perform updates. It includes any additional parameters necessary to perform the update for the indicated strategy.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type indicates the type of the StatefulSetUpdateStrategy. Default is RollingUpdate.\n\nPossible enum values:\n - `\"OnDelete\"` triggers the legacy behavior. Version tracking and ordered rolling restarts are disabled. Pods are recreated from the StatefulSetSpec when they are manually deleted. When a scale operation is performed with this strategy,specification version indicated by the StatefulSet's currentRevision.\n - `\"RollingUpdate\"` indicates that update will be applied to all Pods in the StatefulSet with respect to the StatefulSet ordering constraints. When a scale operation is performed with this strategy, new Pods will be created from the specification version indicated by the StatefulSet's updateRevision.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"OnDelete", "RollingUpdate"}, - }, - }, - "rollingUpdate": { - SchemaProps: spec.SchemaProps{ - Description: "RollingUpdate is used to communicate parameters when Type is RollingUpdateStatefulSetStrategyType.", - Ref: ref("k8s.io/api/apps/v1.RollingUpdateStatefulSetStrategy"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/apps/v1.RollingUpdateStatefulSetStrategy"}, - } -} - -func schema_k8sio_api_core_v1_AWSElasticBlockStoreVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Persistent Disk resource in AWS.\n\nAn AWS EBS disk must exist before mounting to a container. The disk must also be in the same AWS zone as the kubelet. An AWS EBS disk can only be mounted as read/write once. AWS EBS volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "volumeID": { - SchemaProps: spec.SchemaProps{ - Description: "volumeID is unique ID of the persistent disk resource in AWS (Amazon EBS volume). More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore", - Type: []string{"string"}, - Format: "", - }, - }, - "partition": { - SchemaProps: spec.SchemaProps{ - Description: "partition is the partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as \"1\". Similarly, the volume partition for /dev/sda is \"0\" (or you can leave the property empty).", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly value true will force the readOnly setting in VolumeMounts. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"volumeID"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_Affinity(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Affinity is a group of affinity scheduling rules.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "nodeAffinity": { - SchemaProps: spec.SchemaProps{ - Description: "Describes node affinity scheduling rules for the pod.", - Ref: ref("k8s.io/api/core/v1.NodeAffinity"), - }, - }, - "podAffinity": { - SchemaProps: spec.SchemaProps{ - Description: "Describes pod affinity scheduling rules (e.g. co-locate this pod in the same node, zone, etc. as some other pod(s)).", - Ref: ref("k8s.io/api/core/v1.PodAffinity"), - }, - }, - "podAntiAffinity": { - SchemaProps: spec.SchemaProps{ - Description: "Describes pod anti-affinity scheduling rules (e.g. avoid putting this pod in the same node, zone, etc. as some other pod(s)).", - Ref: ref("k8s.io/api/core/v1.PodAntiAffinity"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NodeAffinity", "k8s.io/api/core/v1.PodAffinity", "k8s.io/api/core/v1.PodAntiAffinity"}, - } -} - -func schema_k8sio_api_core_v1_AttachedVolume(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "AttachedVolume describes a volume attached to a node", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the attached volume", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "devicePath": { - SchemaProps: spec.SchemaProps{ - Description: "DevicePath represents the device path where the volume should be available", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name", "devicePath"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_AvoidPods(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "AvoidPods describes pods that should avoid this node. This is the value for a Node annotation with key scheduler.alpha.kubernetes.io/preferAvoidPods and will eventually become a field of NodeStatus.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "preferAvoidPods": { - SchemaProps: spec.SchemaProps{ - Description: "Bounded-sized list of signatures of pods that should avoid this node, sorted in timestamp order from oldest to newest. Size of the slice is unspecified.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PreferAvoidPodsEntry"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PreferAvoidPodsEntry"}, - } -} - -func schema_k8sio_api_core_v1_AzureDiskVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "AzureDisk represents an Azure Data Disk mount on the host and bind mount to the pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "diskName": { - SchemaProps: spec.SchemaProps{ - Description: "diskName is the Name of the data disk in the blob storage", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "diskURI": { - SchemaProps: spec.SchemaProps{ - Description: "diskURI is the URI of data disk in the blob storage", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "cachingMode": { - SchemaProps: spec.SchemaProps{ - Description: "cachingMode is the Host Caching mode: None, Read Only, Read Write.\n\nPossible enum values:\n - `\"None\"`\n - `\"ReadOnly\"`\n - `\"ReadWrite\"`", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"None", "ReadOnly", "ReadWrite"}, - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "kind expected values are Shared: multiple blob disks per storage account Dedicated: single blob disk per storage account Managed: azure managed data disk (only in managed availability set). defaults to shared\n\nPossible enum values:\n - `\"Dedicated\"`\n - `\"Managed\"`\n - `\"Shared\"`", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Dedicated", "Managed", "Shared"}, - }, - }, - }, - Required: []string{"diskName", "diskURI"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_AzureFilePersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "AzureFile represents an Azure File Service mount on the host and bind mount to the pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "secretName": { - SchemaProps: spec.SchemaProps{ - Description: "secretName is the name of secret that contains Azure Storage Account Name and Key", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "shareName": { - SchemaProps: spec.SchemaProps{ - Description: "shareName is the azure Share Name", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "secretNamespace": { - SchemaProps: spec.SchemaProps{ - Description: "secretNamespace is the namespace of the secret that contains Azure Storage Account Name and Key default is the same as the Pod", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"secretName", "shareName"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_AzureFileVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "AzureFile represents an Azure File Service mount on the host and bind mount to the pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "secretName": { - SchemaProps: spec.SchemaProps{ - Description: "secretName is the name of secret that contains Azure Storage Account Name and Key", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "shareName": { - SchemaProps: spec.SchemaProps{ - Description: "shareName is the azure share Name", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"secretName", "shareName"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_Binding(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Binding ties one object to another; for example, a pod is bound to a node by a scheduler. Deprecated in 1.7, please use the bindings subresource of pods instead.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "target": { - SchemaProps: spec.SchemaProps{ - Description: "The target object that you want to bind to the standard object.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ObjectReference"), - }, - }, - }, - Required: []string{"target"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ObjectReference", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_CSIPersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents storage that is managed by an external CSI volume driver (Beta feature)", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "driver": { - SchemaProps: spec.SchemaProps{ - Description: "driver is the name of the driver to use for this volume. Required.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeHandle": { - SchemaProps: spec.SchemaProps{ - Description: "volumeHandle is the unique volume name returned by the CSI volume plugin’s CreateVolume to refer to the volume on all subsequent calls. Required.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly value to pass to ControllerPublishVolumeRequest. Defaults to false (read/write).", - Type: []string{"boolean"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\".", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeAttributes": { - SchemaProps: spec.SchemaProps{ - Description: "volumeAttributes of the volume to publish.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "controllerPublishSecretRef": { - SchemaProps: spec.SchemaProps{ - Description: "controllerPublishSecretRef is a reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI ControllerPublishVolume and ControllerUnpublishVolume calls. This field is optional, and may be empty if no secret is required. If the secret object contains more than one secret, all secrets are passed.", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - "nodeStageSecretRef": { - SchemaProps: spec.SchemaProps{ - Description: "nodeStageSecretRef is a reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI NodeStageVolume and NodeStageVolume and NodeUnstageVolume calls. This field is optional, and may be empty if no secret is required. If the secret object contains more than one secret, all secrets are passed.", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - "nodePublishSecretRef": { - SchemaProps: spec.SchemaProps{ - Description: "nodePublishSecretRef is a reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI NodePublishVolume and NodeUnpublishVolume calls. This field is optional, and may be empty if no secret is required. If the secret object contains more than one secret, all secrets are passed.", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - "controllerExpandSecretRef": { - SchemaProps: spec.SchemaProps{ - Description: "controllerExpandSecretRef is a reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI ControllerExpandVolume call. This field is optional, and may be empty if no secret is required. If the secret object contains more than one secret, all secrets are passed.", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - "nodeExpandSecretRef": { - SchemaProps: spec.SchemaProps{ - Description: "nodeExpandSecretRef is a reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI NodeExpandVolume call. This field is optional, may be omitted if no secret is required. If the secret object contains more than one secret, all secrets are passed.", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - }, - Required: []string{"driver", "volumeHandle"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.SecretReference"}, - } -} - -func schema_k8sio_api_core_v1_CSIVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a source location of a volume to mount, managed by an external CSI driver", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "driver": { - SchemaProps: spec.SchemaProps{ - Description: "driver is the name of the CSI driver that handles this volume. Consult with your admin for the correct name as registered in the cluster.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly specifies a read-only configuration for the volume. Defaults to false (read/write).", - Type: []string{"boolean"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType to mount. Ex. \"ext4\", \"xfs\", \"ntfs\". If not provided, the empty value is passed to the associated CSI driver which will determine the default filesystem to apply.", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeAttributes": { - SchemaProps: spec.SchemaProps{ - Description: "volumeAttributes stores driver-specific properties that are passed to the CSI driver. Consult your driver's documentation for supported values.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "nodePublishSecretRef": { - SchemaProps: spec.SchemaProps{ - Description: "nodePublishSecretRef is a reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI NodePublishVolume and NodeUnpublishVolume calls. This field is optional, and may be empty if no secret is required. If the secret object contains more than one secret, all secret references are passed.", - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - }, - Required: []string{"driver"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LocalObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_Capabilities(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Adds and removes POSIX capabilities from running containers.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "add": { - SchemaProps: spec.SchemaProps{ - Description: "Added capabilities", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "drop": { - SchemaProps: spec.SchemaProps{ - Description: "Removed capabilities", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_CephFSPersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Ceph Filesystem mount that lasts the lifetime of a pod Cephfs volumes do not support ownership management or SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "monitors": { - SchemaProps: spec.SchemaProps{ - Description: "monitors is Required: Monitors is a collection of Ceph monitors More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "path is Optional: Used as the mounted root, rather than the full Ceph tree, default is /", - Type: []string{"string"}, - Format: "", - }, - }, - "user": { - SchemaProps: spec.SchemaProps{ - Description: "user is Optional: User is the rados user name, default is admin More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - Type: []string{"string"}, - Format: "", - }, - }, - "secretFile": { - SchemaProps: spec.SchemaProps{ - Description: "secretFile is Optional: SecretFile is the path to key ring for User, default is /etc/ceph/user.secret More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - Type: []string{"string"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef is Optional: SecretRef is reference to the authentication secret for User, default is empty. More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly is Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"monitors"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.SecretReference"}, - } -} - -func schema_k8sio_api_core_v1_CephFSVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Ceph Filesystem mount that lasts the lifetime of a pod Cephfs volumes do not support ownership management or SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "monitors": { - SchemaProps: spec.SchemaProps{ - Description: "monitors is Required: Monitors is a collection of Ceph monitors More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "path is Optional: Used as the mounted root, rather than the full Ceph tree, default is /", - Type: []string{"string"}, - Format: "", - }, - }, - "user": { - SchemaProps: spec.SchemaProps{ - Description: "user is optional: User is the rados user name, default is admin More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - Type: []string{"string"}, - Format: "", - }, - }, - "secretFile": { - SchemaProps: spec.SchemaProps{ - Description: "secretFile is Optional: SecretFile is the path to key ring for User, default is /etc/ceph/user.secret More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - Type: []string{"string"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef is Optional: SecretRef is reference to the authentication secret for User, default is empty. More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly is Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"monitors"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LocalObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_CinderPersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a cinder volume resource in Openstack. A Cinder volume must exist before mounting to a container. The volume must also be in the same region as the kubelet. Cinder volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "volumeID": { - SchemaProps: spec.SchemaProps{ - Description: "volumeID used to identify the volume in cinder. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType Filesystem type to mount. Must be a filesystem type supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly is Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - Type: []string{"boolean"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef is Optional: points to a secret object containing parameters used to connect to OpenStack.", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - }, - Required: []string{"volumeID"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.SecretReference"}, - } -} - -func schema_k8sio_api_core_v1_CinderVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a cinder volume resource in Openstack. A Cinder volume must exist before mounting to a container. The volume must also be in the same region as the kubelet. Cinder volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "volumeID": { - SchemaProps: spec.SchemaProps{ - Description: "volumeID used to identify the volume in cinder. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - Type: []string{"boolean"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef is optional: points to a secret object containing parameters used to connect to OpenStack.", - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - }, - Required: []string{"volumeID"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LocalObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_ClaimSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ClaimSource describes a reference to a ResourceClaim.\n\nExactly one of these fields should be set. Consumers of this type must treat an empty object as if it has an unknown value.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "resourceClaimName": { - SchemaProps: spec.SchemaProps{ - Description: "ResourceClaimName is the name of a ResourceClaim object in the same namespace as this pod.", - Type: []string{"string"}, - Format: "", - }, - }, - "resourceClaimTemplateName": { - SchemaProps: spec.SchemaProps{ - Description: "ResourceClaimTemplateName is the name of a ResourceClaimTemplate object in the same namespace as this pod.\n\nThe template will be used to create a new ResourceClaim, which will be bound to this pod. When this pod is deleted, the ResourceClaim will also be deleted. The pod name and resource name, along with a generated component, will be used to form a unique name for the ResourceClaim, which will be recorded in pod.status.resourceClaimStatuses.\n\nThis field is immutable and no changes will be made to the corresponding ResourceClaim by the control plane after creating the ResourceClaim.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ClientIPConfig(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ClientIPConfig represents the configurations of Client IP based session affinity.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "timeoutSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "timeoutSeconds specifies the seconds of ClientIP type session sticky time. The value must be >0 && <=86400(for 1 day) if ServiceAffinity == \"ClientIP\". Default value is 10800(for 3 hours).", - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ClusterTrustBundleProjection(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ClusterTrustBundleProjection describes how to select a set of ClusterTrustBundle objects and project their contents into the pod filesystem.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Select a single ClusterTrustBundle by object name. Mutually-exclusive with signerName and labelSelector.", - Type: []string{"string"}, - Format: "", - }, - }, - "signerName": { - SchemaProps: spec.SchemaProps{ - Description: "Select all ClusterTrustBundles that match this signer name. Mutually-exclusive with name. The contents of all selected ClusterTrustBundles will be unified and deduplicated.", - Type: []string{"string"}, - Format: "", - }, - }, - "labelSelector": { - SchemaProps: spec.SchemaProps{ - Description: "Select all ClusterTrustBundles that match this label selector. Only has effect if signerName is set. Mutually-exclusive with name. If unset, interpreted as \"match nothing\". If set but empty, interpreted as \"match everything\".", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), - }, - }, - "optional": { - SchemaProps: spec.SchemaProps{ - Description: "If true, don't block pod startup if the referenced ClusterTrustBundle(s) aren't available. If using name, then the named ClusterTrustBundle is allowed not to exist. If using signerName, then the combination of signerName and labelSelector is allowed to match zero ClusterTrustBundles.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "Relative path from the volume root to write the bundle.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"path"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"}, - } -} - -func schema_k8sio_api_core_v1_ComponentCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Information about the condition of a component.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of condition for a component. Valid value: \"Healthy\"", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status of the condition for a component. Valid values for \"Healthy\": \"True\", \"False\", or \"Unknown\".", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "Message about the condition for a component. For example, information about a health check.", - Type: []string{"string"}, - Format: "", - }, - }, - "error": { - SchemaProps: spec.SchemaProps{ - Description: "Condition error code for a component. For example, a health check error code.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ComponentStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ComponentStatus (and ComponentStatusList) holds the cluster validation info. Deprecated: This API is deprecated in v1.19+", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "conditions": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of component conditions observed", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ComponentCondition"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ComponentCondition", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_ComponentStatusList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Status of all the conditions for the component as a list of ComponentStatus objects. Deprecated: This API is deprecated in v1.19+", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of ComponentStatus objects.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ComponentStatus"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ComponentStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_ConfigMap(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ConfigMap holds configuration data for pods to consume.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "immutable": { - SchemaProps: spec.SchemaProps{ - Description: "Immutable, if set to true, ensures that data stored in the ConfigMap cannot be updated (only object metadata can be modified). If not set to true, the field can be modified at any time. Defaulted to nil.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "data": { - SchemaProps: spec.SchemaProps{ - Description: "Data contains the configuration data. Each key must consist of alphanumeric characters, '-', '_' or '.'. Values with non-UTF-8 byte sequences must use the BinaryData field. The keys stored in Data must not overlap with the keys in the BinaryData field, this is enforced during validation process.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "binaryData": { - SchemaProps: spec.SchemaProps{ - Description: "BinaryData contains the binary data. Each key must consist of alphanumeric characters, '-', '_' or '.'. BinaryData can contain byte sequences that are not in the UTF-8 range. The keys stored in BinaryData must not overlap with the ones in the Data field, this is enforced during validation process. Using this field will require 1.10+ apiserver and kubelet.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "byte", - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_ConfigMapEnvSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ConfigMapEnvSource selects a ConfigMap to populate the environment variables with.\n\nThe contents of the target ConfigMap's Data field will represent the key-value pairs as environment variables.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Type: []string{"string"}, - Format: "", - }, - }, - "optional": { - SchemaProps: spec.SchemaProps{ - Description: "Specify whether the ConfigMap must be defined", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ConfigMapKeySelector(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Selects a key from a ConfigMap.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Type: []string{"string"}, - Format: "", - }, - }, - "key": { - SchemaProps: spec.SchemaProps{ - Description: "The key to select.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "optional": { - SchemaProps: spec.SchemaProps{ - Description: "Specify whether the ConfigMap or its key must be defined", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"key"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ConfigMapList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ConfigMapList is a resource containing a list of ConfigMap objects.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is the list of ConfigMaps.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ConfigMap"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ConfigMap", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_ConfigMapNodeConfigSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ConfigMapNodeConfigSource contains the information to reference a ConfigMap as a config source for the Node. This API is deprecated since 1.22: https://git.k8s.io/enhancements/keps/sig-node/281-dynamic-kubelet-configuration", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "namespace": { - SchemaProps: spec.SchemaProps{ - Description: "Namespace is the metadata.namespace of the referenced ConfigMap. This field is required in all cases.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name is the metadata.name of the referenced ConfigMap. This field is required in all cases.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "uid": { - SchemaProps: spec.SchemaProps{ - Description: "UID is the metadata.UID of the referenced ConfigMap. This field is forbidden in Node.Spec, and required in Node.Status.", - Type: []string{"string"}, - Format: "", - }, - }, - "resourceVersion": { - SchemaProps: spec.SchemaProps{ - Description: "ResourceVersion is the metadata.ResourceVersion of the referenced ConfigMap. This field is forbidden in Node.Spec, and required in Node.Status.", - Type: []string{"string"}, - Format: "", - }, - }, - "kubeletConfigKey": { - SchemaProps: spec.SchemaProps{ - Description: "KubeletConfigKey declares which key of the referenced ConfigMap corresponds to the KubeletConfiguration structure This field is required in all cases.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"namespace", "name", "kubeletConfigKey"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ConfigMapProjection(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Adapts a ConfigMap into a projected volume.\n\nThe contents of the target ConfigMap's Data field will be presented in a projected volume as files using the keys in the Data field as the file names, unless the items element is populated with specific mappings of keys to paths. Note that this is identical to a configmap volume source without the default mode.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Type: []string{"string"}, - Format: "", - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "items if unspecified, each key-value pair in the Data field of the referenced ConfigMap will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the ConfigMap, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.KeyToPath"), - }, - }, - }, - }, - }, - "optional": { - SchemaProps: spec.SchemaProps{ - Description: "optional specify whether the ConfigMap or its keys must be defined", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.KeyToPath"}, - } -} - -func schema_k8sio_api_core_v1_ConfigMapVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Adapts a ConfigMap into a volume.\n\nThe contents of the target ConfigMap's Data field will be presented in a volume as files using the keys in the Data field as the file names, unless the items element is populated with specific mappings of keys to paths. ConfigMap volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Type: []string{"string"}, - Format: "", - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "items if unspecified, each key-value pair in the Data field of the referenced ConfigMap will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the ConfigMap, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.KeyToPath"), - }, - }, - }, - }, - }, - "defaultMode": { - SchemaProps: spec.SchemaProps{ - Description: "defaultMode is optional: mode bits used to set permissions on created files by default. Must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "optional": { - SchemaProps: spec.SchemaProps{ - Description: "optional specify whether the ConfigMap or its keys must be defined", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.KeyToPath"}, - } -} - -func schema_k8sio_api_core_v1_Container(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A single application container that you want to run within a pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the container specified as a DNS_LABEL. Each container in a pod must have a unique name (DNS_LABEL). Cannot be updated.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "image": { - SchemaProps: spec.SchemaProps{ - Description: "Container image name. More info: https://kubernetes.io/docs/concepts/containers/images This field is optional to allow higher level config management to default or override container images in workload controllers like Deployments and StatefulSets.", - Type: []string{"string"}, - Format: "", - }, - }, - "command": { - SchemaProps: spec.SchemaProps{ - Description: "Entrypoint array. Not executed within a shell. The container image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "args": { - SchemaProps: spec.SchemaProps{ - Description: "Arguments to the entrypoint. The container image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "workingDir": { - SchemaProps: spec.SchemaProps{ - Description: "Container's working directory. If not specified, the container runtime's default will be used, which might be configured in the container image. Cannot be updated.", - Type: []string{"string"}, - Format: "", - }, - }, - "ports": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "containerPort", - "protocol", - }, - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "containerPort", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of ports to expose from the container. Not specifying a port here DOES NOT prevent that port from being exposed. Any port which is listening on the default \"0.0.0.0\" address inside a container will be accessible from the network. Modifying this array with strategic merge patch may corrupt the data. For more information See https://github.com/kubernetes/kubernetes/issues/108255. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerPort"), - }, - }, - }, - }, - }, - "envFrom": { - SchemaProps: spec.SchemaProps{ - Description: "List of sources to populate environment variables in the container. The keys defined within a source must be a C_IDENTIFIER. All invalid keys will be reported as an event when the container is starting. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EnvFromSource"), - }, - }, - }, - }, - }, - "env": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of environment variables to set in the container. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EnvVar"), - }, - }, - }, - }, - }, - "resources": { - SchemaProps: spec.SchemaProps{ - Description: "Compute Resources required by this container. Cannot be updated. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ResourceRequirements"), - }, - }, - "resizePolicy": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Resources resize policy for the container.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerResizePolicy"), - }, - }, - }, - }, - }, - "restartPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "RestartPolicy defines the restart behavior of individual containers in a pod. This field may only be set for init containers, and the only allowed value is \"Always\". For non-init containers or when this field is not specified, the restart behavior is defined by the Pod's restart policy and the container type. Setting the RestartPolicy as \"Always\" for the init container will have the following effect: this init container will be continually restarted on exit until all regular containers have terminated. Once all regular containers have completed, all init containers with restartPolicy \"Always\" will be shut down. This lifecycle differs from normal init containers and is often referred to as a \"sidecar\" container. Although this init container still starts in the init container sequence, it does not wait for the container to complete before proceeding to the next init container. Instead, the next init container starts immediately after this init container is started, or after any startupProbe has successfully completed.", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeMounts": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "mountPath", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Pod volumes to mount into the container's filesystem. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.VolumeMount"), - }, - }, - }, - }, - }, - "volumeDevices": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "devicePath", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "volumeDevices is the list of block devices to be used by the container.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.VolumeDevice"), - }, - }, - }, - }, - }, - "livenessProbe": { - SchemaProps: spec.SchemaProps{ - Description: "Periodic probe of container liveness. Container will be restarted if the probe fails. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "readinessProbe": { - SchemaProps: spec.SchemaProps{ - Description: "Periodic probe of container service readiness. Container will be removed from service endpoints if the probe fails. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "startupProbe": { - SchemaProps: spec.SchemaProps{ - Description: "StartupProbe indicates that the Pod has successfully initialized. If specified, no other probes are executed until this completes successfully. If this probe fails, the Pod will be restarted, just as if the livenessProbe failed. This can be used to provide different probe parameters at the beginning of a Pod's lifecycle, when it might take a long time to load data or warm a cache, than during steady-state operation. This cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "lifecycle": { - SchemaProps: spec.SchemaProps{ - Description: "Actions that the management system should take in response to container lifecycle events. Cannot be updated.", - Ref: ref("k8s.io/api/core/v1.Lifecycle"), - }, - }, - "terminationMessagePath": { - SchemaProps: spec.SchemaProps{ - Description: "Optional: Path at which the file to which the container's termination message will be written is mounted into the container's filesystem. Message written is intended to be brief final status, such as an assertion failure message. Will be truncated by the node if greater than 4096 bytes. The total message length across all containers will be limited to 12kb. Defaults to /dev/termination-log. Cannot be updated.", - Type: []string{"string"}, - Format: "", - }, - }, - "terminationMessagePolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Indicate how the termination message should be populated. File will use the contents of terminationMessagePath to populate the container status message on both success and failure. FallbackToLogsOnError will use the last chunk of container log output if the termination message file is empty and the container exited with an error. The log output is limited to 2048 bytes or 80 lines, whichever is smaller. Defaults to File. Cannot be updated.\n\nPossible enum values:\n - `\"FallbackToLogsOnError\"` will read the most recent contents of the container logs for the container status message when the container exits with an error and the terminationMessagePath has no contents.\n - `\"File\"` is the default behavior and will set the container status message to the contents of the container's terminationMessagePath when the container exits.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"FallbackToLogsOnError", "File"}, - }, - }, - "imagePullPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More info: https://kubernetes.io/docs/concepts/containers/images#updating-images\n\nPossible enum values:\n - `\"Always\"` means that kubelet always attempts to pull the latest image. Container will fail If the pull fails.\n - `\"IfNotPresent\"` means that kubelet pulls if the image isn't present on disk. Container will fail if the image isn't present and the pull fails.\n - `\"Never\"` means that kubelet never pulls an image, but only uses a local image. Container will fail if the image isn't present", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Always", "IfNotPresent", "Never"}, - }, - }, - "securityContext": { - SchemaProps: spec.SchemaProps{ - Description: "SecurityContext defines the security options the container should be run with. If set, the fields of SecurityContext override the equivalent fields of PodSecurityContext. More info: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/", - Ref: ref("k8s.io/api/core/v1.SecurityContext"), - }, - }, - "stdin": { - SchemaProps: spec.SchemaProps{ - Description: "Whether this container should allocate a buffer for stdin in the container runtime. If this is not set, reads from stdin in the container will always result in EOF. Default is false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "stdinOnce": { - SchemaProps: spec.SchemaProps{ - Description: "Whether the container runtime should close the stdin channel after it has been opened by a single attach. When stdin is true the stdin stream will remain open across multiple attach sessions. If stdinOnce is set to true, stdin is opened on container start, is empty until the first client attaches to stdin, and then remains open and accepts data until the client disconnects, at which time stdin is closed and remains closed until the container is restarted. If this flag is false, a container processes that reads from stdin will never receive an EOF. Default is false", - Type: []string{"boolean"}, - Format: "", - }, - }, - "tty": { - SchemaProps: spec.SchemaProps{ - Description: "Whether this container should allocate a TTY for itself, also requires 'stdin' to be true. Default is false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"name"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ContainerPort", "k8s.io/api/core/v1.ContainerResizePolicy", "k8s.io/api/core/v1.EnvFromSource", "k8s.io/api/core/v1.EnvVar", "k8s.io/api/core/v1.Lifecycle", "k8s.io/api/core/v1.Probe", "k8s.io/api/core/v1.ResourceRequirements", "k8s.io/api/core/v1.SecurityContext", "k8s.io/api/core/v1.VolumeDevice", "k8s.io/api/core/v1.VolumeMount"}, - } -} - -func schema_k8sio_api_core_v1_ContainerImage(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Describe a container image", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "names": { - SchemaProps: spec.SchemaProps{ - Description: "Names by which this image is known. e.g. [\"kubernetes.example/hyperkube:v1.0.7\", \"cloud-vendor.registry.example/cloud-vendor/hyperkube:v1.0.7\"]", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "sizeBytes": { - SchemaProps: spec.SchemaProps{ - Description: "The size of the image in bytes.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ContainerPort(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ContainerPort represents a network port in a single container.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, this must be an IANA_SVC_NAME and unique within the pod. Each named port in a pod must have a unique name. Name for the port that can be referred to by services.", - Type: []string{"string"}, - Format: "", - }, - }, - "hostPort": { - SchemaProps: spec.SchemaProps{ - Description: "Number of port to expose on the host. If specified, this must be a valid port number, 0 < x < 65536. If HostNetwork is specified, this must match ContainerPort. Most containers do not need this.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "containerPort": { - SchemaProps: spec.SchemaProps{ - Description: "Number of port to expose on the pod's IP address. This must be a valid port number, 0 < x < 65536.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "protocol": { - SchemaProps: spec.SchemaProps{ - Description: "Protocol for port. Must be UDP, TCP, or SCTP. Defaults to \"TCP\".\n\nPossible enum values:\n - `\"SCTP\"` is the SCTP protocol.\n - `\"TCP\"` is the TCP protocol.\n - `\"UDP\"` is the UDP protocol.", - Default: "TCP", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"SCTP", "TCP", "UDP"}, - }, - }, - "hostIP": { - SchemaProps: spec.SchemaProps{ - Description: "What host IP to bind the external port to.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"containerPort"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ContainerResizePolicy(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ContainerResizePolicy represents resource resize policy for the container.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "resourceName": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the resource to which this resource resize policy applies. Supported values: cpu, memory.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "restartPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Restart policy to apply when specified resource is resized. If not specified, it defaults to NotRequired.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"resourceName", "restartPolicy"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ContainerState(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ContainerState holds a possible state of container. Only one of its members may be specified. If none of them is specified, the default one is ContainerStateWaiting.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "waiting": { - SchemaProps: spec.SchemaProps{ - Description: "Details about a waiting container", - Ref: ref("k8s.io/api/core/v1.ContainerStateWaiting"), - }, - }, - "running": { - SchemaProps: spec.SchemaProps{ - Description: "Details about a running container", - Ref: ref("k8s.io/api/core/v1.ContainerStateRunning"), - }, - }, - "terminated": { - SchemaProps: spec.SchemaProps{ - Description: "Details about a terminated container", - Ref: ref("k8s.io/api/core/v1.ContainerStateTerminated"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ContainerStateRunning", "k8s.io/api/core/v1.ContainerStateTerminated", "k8s.io/api/core/v1.ContainerStateWaiting"}, - } -} - -func schema_k8sio_api_core_v1_ContainerStateRunning(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ContainerStateRunning is a running state of a container.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "startedAt": { - SchemaProps: spec.SchemaProps{ - Description: "Time at which the container was last (re-)started", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_ContainerStateTerminated(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ContainerStateTerminated is a terminated state of a container.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "exitCode": { - SchemaProps: spec.SchemaProps{ - Description: "Exit status from the last termination of the container", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "signal": { - SchemaProps: spec.SchemaProps{ - Description: "Signal from the last termination of the container", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "(brief) reason from the last termination of the container", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "Message regarding the last termination of the container", - Type: []string{"string"}, - Format: "", - }, - }, - "startedAt": { - SchemaProps: spec.SchemaProps{ - Description: "Time at which previous execution of the container started", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "finishedAt": { - SchemaProps: spec.SchemaProps{ - Description: "Time at which the container last terminated", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "containerID": { - SchemaProps: spec.SchemaProps{ - Description: "Container's ID in the format '://'", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"exitCode"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_ContainerStateWaiting(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ContainerStateWaiting is a waiting state of a container.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "(brief) reason the container is not yet running.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "Message regarding why the container is not yet running.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ContainerStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ContainerStatus contains details for the current status of this container.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name is a DNS_LABEL representing the unique name of the container. Each container in a pod must have a unique name across all container types. Cannot be updated.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "state": { - SchemaProps: spec.SchemaProps{ - Description: "State holds details about the container's current condition.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerState"), - }, - }, - "lastState": { - SchemaProps: spec.SchemaProps{ - Description: "LastTerminationState holds the last termination state of the container to help debug container crashes and restarts. This field is not populated if the container is still running and RestartCount is 0.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerState"), - }, - }, - "ready": { - SchemaProps: spec.SchemaProps{ - Description: "Ready specifies whether the container is currently passing its readiness check. The value will change as readiness probes keep executing. If no readiness probes are specified, this field defaults to true once the container is fully started (see Started field).\n\nThe value is typically used to determine whether a container is ready to accept traffic.", - Default: false, - Type: []string{"boolean"}, - Format: "", - }, - }, - "restartCount": { - SchemaProps: spec.SchemaProps{ - Description: "RestartCount holds the number of times the container has been restarted. Kubelet makes an effort to always increment the value, but there are cases when the state may be lost due to node restarts and then the value may be reset to 0. The value is never negative.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "image": { - SchemaProps: spec.SchemaProps{ - Description: "Image is the name of container image that the container is running. The container image may not match the image used in the PodSpec, as it may have been resolved by the runtime. More info: https://kubernetes.io/docs/concepts/containers/images.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "imageID": { - SchemaProps: spec.SchemaProps{ - Description: "ImageID is the image ID of the container's image. The image ID may not match the image ID of the image used in the PodSpec, as it may have been resolved by the runtime.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "containerID": { - SchemaProps: spec.SchemaProps{ - Description: "ContainerID is the ID of the container in the format '://'. Where type is a container runtime identifier, returned from Version call of CRI API (for example \"containerd\").", - Type: []string{"string"}, - Format: "", - }, - }, - "started": { - SchemaProps: spec.SchemaProps{ - Description: "Started indicates whether the container has finished its postStart lifecycle hook and passed its startup probe. Initialized as false, becomes true after startupProbe is considered successful. Resets to false when the container is restarted, or if kubelet loses state temporarily. In both cases, startup probes will run again. Is always true when no startupProbe is defined and container is running and has passed the postStart lifecycle hook. The null value must be treated the same as false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "allocatedResources": { - SchemaProps: spec.SchemaProps{ - Description: "AllocatedResources represents the compute resources allocated for this container by the node. Kubelet sets this value to Container.Resources.Requests upon successful pod admission and after successfully admitting desired pod resize.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "resources": { - SchemaProps: spec.SchemaProps{ - Description: "Resources represents the compute resource requests and limits that have been successfully enacted on the running container after it has been started or has been successfully resized.", - Ref: ref("k8s.io/api/core/v1.ResourceRequirements"), - }, - }, - }, - Required: []string{"name", "ready", "restartCount", "image", "imageID"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ContainerState", "k8s.io/api/core/v1.ResourceRequirements", "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_DaemonEndpoint(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "DaemonEndpoint contains information about a single Daemon endpoint.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "Port": { - SchemaProps: spec.SchemaProps{ - Description: "Port number of the given endpoint.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - Required: []string{"Port"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_DownwardAPIProjection(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents downward API info for projecting into a projected volume. Note that this is identical to a downwardAPI volume source without the default mode.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is a list of DownwardAPIVolume file", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.DownwardAPIVolumeFile"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.DownwardAPIVolumeFile"}, - } -} - -func schema_k8sio_api_core_v1_DownwardAPIVolumeFile(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "DownwardAPIVolumeFile represents information to create the file containing the pod field", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "path": { - SchemaProps: spec.SchemaProps{ - Description: "Required: Path is the relative path name of the file to be created. Must not be absolute or contain the '..' path. Must be utf-8 encoded. The first item of the relative path must not start with '..'", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fieldRef": { - SchemaProps: spec.SchemaProps{ - Description: "Required: Selects a field of the pod: only annotations, labels, name and namespace are supported.", - Ref: ref("k8s.io/api/core/v1.ObjectFieldSelector"), - }, - }, - "resourceFieldRef": { - SchemaProps: spec.SchemaProps{ - Description: "Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, requests.cpu and requests.memory) are currently supported.", - Ref: ref("k8s.io/api/core/v1.ResourceFieldSelector"), - }, - }, - "mode": { - SchemaProps: spec.SchemaProps{ - Description: "Optional: mode bits used to set permissions on this file, must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - Required: []string{"path"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ObjectFieldSelector", "k8s.io/api/core/v1.ResourceFieldSelector"}, - } -} - -func schema_k8sio_api_core_v1_DownwardAPIVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "DownwardAPIVolumeSource represents a volume containing downward API info. Downward API volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is a list of downward API volume file", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.DownwardAPIVolumeFile"), - }, - }, - }, - }, - }, - "defaultMode": { - SchemaProps: spec.SchemaProps{ - Description: "Optional: mode bits to use on created files by default. Must be a Optional: mode bits used to set permissions on created files by default. Must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.DownwardAPIVolumeFile"}, - } -} - -func schema_k8sio_api_core_v1_EmptyDirVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents an empty directory for a pod. Empty directory volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "medium": { - SchemaProps: spec.SchemaProps{ - Description: "medium represents what type of storage medium should back this directory. The default is \"\" which means to use the node's default medium. Must be an empty string (default) or Memory. More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir", - Type: []string{"string"}, - Format: "", - }, - }, - "sizeLimit": { - SchemaProps: spec.SchemaProps{ - Description: "sizeLimit is the total amount of local storage required for this EmptyDir volume. The size limit is also applicable for memory medium. The maximum usage on memory medium EmptyDir would be the minimum value between the SizeLimit specified here and the sum of memory limits of all containers in a pod. The default is nil which means that the limit is undefined. More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir", - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_EndpointAddress(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EndpointAddress is a tuple that describes single IP address.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "ip": { - SchemaProps: spec.SchemaProps{ - Description: "The IP of this endpoint. May not be loopback (127.0.0.0/8 or ::1), link-local (169.254.0.0/16 or fe80::/10), or link-local multicast (224.0.0.0/24 or ff02::/16).", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "hostname": { - SchemaProps: spec.SchemaProps{ - Description: "The Hostname of this endpoint", - Type: []string{"string"}, - Format: "", - }, - }, - "nodeName": { - SchemaProps: spec.SchemaProps{ - Description: "Optional: Node hosting this endpoint. This can be used to determine endpoints local to a node.", - Type: []string{"string"}, - Format: "", - }, - }, - "targetRef": { - SchemaProps: spec.SchemaProps{ - Description: "Reference to object providing the endpoint.", - Ref: ref("k8s.io/api/core/v1.ObjectReference"), - }, - }, - }, - Required: []string{"ip"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_EndpointPort(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EndpointPort is a tuple that describes a single port.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "The name of this port. This must match the 'name' field in the corresponding ServicePort. Must be a DNS_LABEL. Optional only if one port is defined.", - Type: []string{"string"}, - Format: "", - }, - }, - "port": { - SchemaProps: spec.SchemaProps{ - Description: "The port number of the endpoint.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "protocol": { - SchemaProps: spec.SchemaProps{ - Description: "The IP protocol for this port. Must be UDP, TCP, or SCTP. Default is TCP.\n\nPossible enum values:\n - `\"SCTP\"` is the SCTP protocol.\n - `\"TCP\"` is the TCP protocol.\n - `\"UDP\"` is the UDP protocol.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"SCTP", "TCP", "UDP"}, - }, - }, - "appProtocol": { - SchemaProps: spec.SchemaProps{ - Description: "The application protocol for this port. This is used as a hint for implementations to offer richer behavior for protocols that they understand. This field follows standard Kubernetes label syntax. Valid values are either:\n\n* Un-prefixed protocol names - reserved for IANA standard service names (as per RFC-6335 and https://www.iana.org/assignments/service-names).\n\n* Kubernetes-defined prefixed names:\n * 'kubernetes.io/h2c' - HTTP/2 prior knowledge over cleartext as described in https://www.rfc-editor.org/rfc/rfc9113.html#name-starting-http-2-with-prior-\n * 'kubernetes.io/ws' - WebSocket over cleartext as described in https://www.rfc-editor.org/rfc/rfc6455\n * 'kubernetes.io/wss' - WebSocket over TLS as described in https://www.rfc-editor.org/rfc/rfc6455\n\n* Other protocols should use implementation-defined prefixed names such as mycompany.com/my-custom-protocol.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"port"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_EndpointSubset(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EndpointSubset is a group of addresses with a common set of ports. The expanded set of endpoints is the Cartesian product of Addresses x Ports. For example, given:\n\n\t{\n\t Addresses: [{\"ip\": \"10.10.1.1\"}, {\"ip\": \"10.10.2.2\"}],\n\t Ports: [{\"name\": \"a\", \"port\": 8675}, {\"name\": \"b\", \"port\": 309}]\n\t}\n\nThe resulting set of endpoints can be viewed as:\n\n\ta: [ 10.10.1.1:8675, 10.10.2.2:8675 ],\n\tb: [ 10.10.1.1:309, 10.10.2.2:309 ]", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "addresses": { - SchemaProps: spec.SchemaProps{ - Description: "IP addresses which offer the related ports that are marked as ready. These endpoints should be considered safe for load balancers and clients to utilize.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EndpointAddress"), - }, - }, - }, - }, - }, - "notReadyAddresses": { - SchemaProps: spec.SchemaProps{ - Description: "IP addresses which offer the related ports but are not currently marked as ready because they have not yet finished starting, have recently failed a readiness check, or have recently failed a liveness check.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EndpointAddress"), - }, - }, - }, - }, - }, - "ports": { - SchemaProps: spec.SchemaProps{ - Description: "Port numbers available on the related IP addresses.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EndpointPort"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.EndpointAddress", "k8s.io/api/core/v1.EndpointPort"}, - } -} - -func schema_k8sio_api_core_v1_Endpoints(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Endpoints is a collection of endpoints that implement the actual service. Example:\n\n\t Name: \"mysvc\",\n\t Subsets: [\n\t {\n\t Addresses: [{\"ip\": \"10.10.1.1\"}, {\"ip\": \"10.10.2.2\"}],\n\t Ports: [{\"name\": \"a\", \"port\": 8675}, {\"name\": \"b\", \"port\": 309}]\n\t },\n\t {\n\t Addresses: [{\"ip\": \"10.10.3.3\"}],\n\t Ports: [{\"name\": \"a\", \"port\": 93}, {\"name\": \"b\", \"port\": 76}]\n\t },\n\t]", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "subsets": { - SchemaProps: spec.SchemaProps{ - Description: "The set of all endpoints is the union of all subsets. Addresses are placed into subsets according to the IPs they share. A single address with multiple ports, some of which are ready and some of which are not (because they come from different containers) will result in the address being displayed in different subsets for the different ports. No address will appear in both Addresses and NotReadyAddresses in the same subset. Sets of addresses and ports that comprise a service.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EndpointSubset"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.EndpointSubset", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_EndpointsList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EndpointsList is a list of endpoints.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of endpoints.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Endpoints"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.Endpoints", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_EnvFromSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EnvFromSource represents the source of a set of ConfigMaps", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "prefix": { - SchemaProps: spec.SchemaProps{ - Description: "An optional identifier to prepend to each key in the ConfigMap. Must be a C_IDENTIFIER.", - Type: []string{"string"}, - Format: "", - }, - }, - "configMapRef": { - SchemaProps: spec.SchemaProps{ - Description: "The ConfigMap to select from", - Ref: ref("k8s.io/api/core/v1.ConfigMapEnvSource"), - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "The Secret to select from", - Ref: ref("k8s.io/api/core/v1.SecretEnvSource"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ConfigMapEnvSource", "k8s.io/api/core/v1.SecretEnvSource"}, - } -} - -func schema_k8sio_api_core_v1_EnvVar(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EnvVar represents an environment variable present in a Container.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the environment variable. Must be a C_IDENTIFIER.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "value": { - SchemaProps: spec.SchemaProps{ - Description: "Variable references $(VAR_NAME) are expanded using the previously defined environment variables in the container and any service environment variables. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Defaults to \"\".", - Type: []string{"string"}, - Format: "", - }, - }, - "valueFrom": { - SchemaProps: spec.SchemaProps{ - Description: "Source for the environment variable's value. Cannot be used if value is not empty.", - Ref: ref("k8s.io/api/core/v1.EnvVarSource"), - }, - }, - }, - Required: []string{"name"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.EnvVarSource"}, - } -} - -func schema_k8sio_api_core_v1_EnvVarSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EnvVarSource represents a source for the value of an EnvVar.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "fieldRef": { - SchemaProps: spec.SchemaProps{ - Description: "Selects a field of the pod: supports metadata.name, metadata.namespace, `metadata.labels['']`, `metadata.annotations['']`, spec.nodeName, spec.serviceAccountName, status.hostIP, status.podIP, status.podIPs.", - Ref: ref("k8s.io/api/core/v1.ObjectFieldSelector"), - }, - }, - "resourceFieldRef": { - SchemaProps: spec.SchemaProps{ - Description: "Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, limits.ephemeral-storage, requests.cpu, requests.memory and requests.ephemeral-storage) are currently supported.", - Ref: ref("k8s.io/api/core/v1.ResourceFieldSelector"), - }, - }, - "configMapKeyRef": { - SchemaProps: spec.SchemaProps{ - Description: "Selects a key of a ConfigMap.", - Ref: ref("k8s.io/api/core/v1.ConfigMapKeySelector"), - }, - }, - "secretKeyRef": { - SchemaProps: spec.SchemaProps{ - Description: "Selects a key of a secret in the pod's namespace", - Ref: ref("k8s.io/api/core/v1.SecretKeySelector"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ConfigMapKeySelector", "k8s.io/api/core/v1.ObjectFieldSelector", "k8s.io/api/core/v1.ResourceFieldSelector", "k8s.io/api/core/v1.SecretKeySelector"}, - } -} - -func schema_k8sio_api_core_v1_EphemeralContainer(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "An EphemeralContainer is a temporary container that you may add to an existing Pod for user-initiated activities such as debugging. Ephemeral containers have no resource or scheduling guarantees, and they will not be restarted when they exit or when a Pod is removed or restarted. The kubelet may evict a Pod if an ephemeral container causes the Pod to exceed its resource allocation.\n\nTo add an ephemeral container, use the ephemeralcontainers subresource of an existing Pod. Ephemeral containers may not be removed or restarted.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the ephemeral container specified as a DNS_LABEL. This name must be unique among all containers, init containers and ephemeral containers.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "image": { - SchemaProps: spec.SchemaProps{ - Description: "Container image name. More info: https://kubernetes.io/docs/concepts/containers/images", - Type: []string{"string"}, - Format: "", - }, - }, - "command": { - SchemaProps: spec.SchemaProps{ - Description: "Entrypoint array. Not executed within a shell. The image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "args": { - SchemaProps: spec.SchemaProps{ - Description: "Arguments to the entrypoint. The image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "workingDir": { - SchemaProps: spec.SchemaProps{ - Description: "Container's working directory. If not specified, the container runtime's default will be used, which might be configured in the container image. Cannot be updated.", - Type: []string{"string"}, - Format: "", - }, - }, - "ports": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "containerPort", - "protocol", - }, - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "containerPort", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Ports are not allowed for ephemeral containers.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerPort"), - }, - }, - }, - }, - }, - "envFrom": { - SchemaProps: spec.SchemaProps{ - Description: "List of sources to populate environment variables in the container. The keys defined within a source must be a C_IDENTIFIER. All invalid keys will be reported as an event when the container is starting. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EnvFromSource"), - }, - }, - }, - }, - }, - "env": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of environment variables to set in the container. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EnvVar"), - }, - }, - }, - }, - }, - "resources": { - SchemaProps: spec.SchemaProps{ - Description: "Resources are not allowed for ephemeral containers. Ephemeral containers use spare resources already allocated to the pod.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ResourceRequirements"), - }, - }, - "resizePolicy": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Resources resize policy for the container.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerResizePolicy"), - }, - }, - }, - }, - }, - "restartPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Restart policy for the container to manage the restart behavior of each container within a pod. This may only be set for init containers. You cannot set this field on ephemeral containers.", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeMounts": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "mountPath", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Pod volumes to mount into the container's filesystem. Subpath mounts are not allowed for ephemeral containers. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.VolumeMount"), - }, - }, - }, - }, - }, - "volumeDevices": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "devicePath", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "volumeDevices is the list of block devices to be used by the container.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.VolumeDevice"), - }, - }, - }, - }, - }, - "livenessProbe": { - SchemaProps: spec.SchemaProps{ - Description: "Probes are not allowed for ephemeral containers.", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "readinessProbe": { - SchemaProps: spec.SchemaProps{ - Description: "Probes are not allowed for ephemeral containers.", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "startupProbe": { - SchemaProps: spec.SchemaProps{ - Description: "Probes are not allowed for ephemeral containers.", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "lifecycle": { - SchemaProps: spec.SchemaProps{ - Description: "Lifecycle is not allowed for ephemeral containers.", - Ref: ref("k8s.io/api/core/v1.Lifecycle"), - }, - }, - "terminationMessagePath": { - SchemaProps: spec.SchemaProps{ - Description: "Optional: Path at which the file to which the container's termination message will be written is mounted into the container's filesystem. Message written is intended to be brief final status, such as an assertion failure message. Will be truncated by the node if greater than 4096 bytes. The total message length across all containers will be limited to 12kb. Defaults to /dev/termination-log. Cannot be updated.", - Type: []string{"string"}, - Format: "", - }, - }, - "terminationMessagePolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Indicate how the termination message should be populated. File will use the contents of terminationMessagePath to populate the container status message on both success and failure. FallbackToLogsOnError will use the last chunk of container log output if the termination message file is empty and the container exited with an error. The log output is limited to 2048 bytes or 80 lines, whichever is smaller. Defaults to File. Cannot be updated.\n\nPossible enum values:\n - `\"FallbackToLogsOnError\"` will read the most recent contents of the container logs for the container status message when the container exits with an error and the terminationMessagePath has no contents.\n - `\"File\"` is the default behavior and will set the container status message to the contents of the container's terminationMessagePath when the container exits.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"FallbackToLogsOnError", "File"}, - }, - }, - "imagePullPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More info: https://kubernetes.io/docs/concepts/containers/images#updating-images\n\nPossible enum values:\n - `\"Always\"` means that kubelet always attempts to pull the latest image. Container will fail If the pull fails.\n - `\"IfNotPresent\"` means that kubelet pulls if the image isn't present on disk. Container will fail if the image isn't present and the pull fails.\n - `\"Never\"` means that kubelet never pulls an image, but only uses a local image. Container will fail if the image isn't present", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Always", "IfNotPresent", "Never"}, - }, - }, - "securityContext": { - SchemaProps: spec.SchemaProps{ - Description: "Optional: SecurityContext defines the security options the ephemeral container should be run with. If set, the fields of SecurityContext override the equivalent fields of PodSecurityContext.", - Ref: ref("k8s.io/api/core/v1.SecurityContext"), - }, - }, - "stdin": { - SchemaProps: spec.SchemaProps{ - Description: "Whether this container should allocate a buffer for stdin in the container runtime. If this is not set, reads from stdin in the container will always result in EOF. Default is false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "stdinOnce": { - SchemaProps: spec.SchemaProps{ - Description: "Whether the container runtime should close the stdin channel after it has been opened by a single attach. When stdin is true the stdin stream will remain open across multiple attach sessions. If stdinOnce is set to true, stdin is opened on container start, is empty until the first client attaches to stdin, and then remains open and accepts data until the client disconnects, at which time stdin is closed and remains closed until the container is restarted. If this flag is false, a container processes that reads from stdin will never receive an EOF. Default is false", - Type: []string{"boolean"}, - Format: "", - }, - }, - "tty": { - SchemaProps: spec.SchemaProps{ - Description: "Whether this container should allocate a TTY for itself, also requires 'stdin' to be true. Default is false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "targetContainerName": { - SchemaProps: spec.SchemaProps{ - Description: "If set, the name of the container from PodSpec that this ephemeral container targets. The ephemeral container will be run in the namespaces (IPC, PID, etc) of this container. If not set then the ephemeral container uses the namespaces configured in the Pod spec.\n\nThe container runtime must implement support for this feature. If the runtime does not support namespace targeting then the result of setting this field is undefined.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ContainerPort", "k8s.io/api/core/v1.ContainerResizePolicy", "k8s.io/api/core/v1.EnvFromSource", "k8s.io/api/core/v1.EnvVar", "k8s.io/api/core/v1.Lifecycle", "k8s.io/api/core/v1.Probe", "k8s.io/api/core/v1.ResourceRequirements", "k8s.io/api/core/v1.SecurityContext", "k8s.io/api/core/v1.VolumeDevice", "k8s.io/api/core/v1.VolumeMount"}, - } -} - -func schema_k8sio_api_core_v1_EphemeralContainerCommon(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EphemeralContainerCommon is a copy of all fields in Container to be inlined in EphemeralContainer. This separate type allows easy conversion from EphemeralContainer to Container and allows separate documentation for the fields of EphemeralContainer. When a new field is added to Container it must be added here as well.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the ephemeral container specified as a DNS_LABEL. This name must be unique among all containers, init containers and ephemeral containers.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "image": { - SchemaProps: spec.SchemaProps{ - Description: "Container image name. More info: https://kubernetes.io/docs/concepts/containers/images", - Type: []string{"string"}, - Format: "", - }, - }, - "command": { - SchemaProps: spec.SchemaProps{ - Description: "Entrypoint array. Not executed within a shell. The image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "args": { - SchemaProps: spec.SchemaProps{ - Description: "Arguments to the entrypoint. The image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "workingDir": { - SchemaProps: spec.SchemaProps{ - Description: "Container's working directory. If not specified, the container runtime's default will be used, which might be configured in the container image. Cannot be updated.", - Type: []string{"string"}, - Format: "", - }, - }, - "ports": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "containerPort", - "protocol", - }, - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "containerPort", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Ports are not allowed for ephemeral containers.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerPort"), - }, - }, - }, - }, - }, - "envFrom": { - SchemaProps: spec.SchemaProps{ - Description: "List of sources to populate environment variables in the container. The keys defined within a source must be a C_IDENTIFIER. All invalid keys will be reported as an event when the container is starting. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EnvFromSource"), - }, - }, - }, - }, - }, - "env": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of environment variables to set in the container. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EnvVar"), - }, - }, - }, - }, - }, - "resources": { - SchemaProps: spec.SchemaProps{ - Description: "Resources are not allowed for ephemeral containers. Ephemeral containers use spare resources already allocated to the pod.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ResourceRequirements"), - }, - }, - "resizePolicy": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Resources resize policy for the container.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerResizePolicy"), - }, - }, - }, - }, - }, - "restartPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Restart policy for the container to manage the restart behavior of each container within a pod. This may only be set for init containers. You cannot set this field on ephemeral containers.", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeMounts": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "mountPath", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Pod volumes to mount into the container's filesystem. Subpath mounts are not allowed for ephemeral containers. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.VolumeMount"), - }, - }, - }, - }, - }, - "volumeDevices": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "devicePath", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "volumeDevices is the list of block devices to be used by the container.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.VolumeDevice"), - }, - }, - }, - }, - }, - "livenessProbe": { - SchemaProps: spec.SchemaProps{ - Description: "Probes are not allowed for ephemeral containers.", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "readinessProbe": { - SchemaProps: spec.SchemaProps{ - Description: "Probes are not allowed for ephemeral containers.", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "startupProbe": { - SchemaProps: spec.SchemaProps{ - Description: "Probes are not allowed for ephemeral containers.", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "lifecycle": { - SchemaProps: spec.SchemaProps{ - Description: "Lifecycle is not allowed for ephemeral containers.", - Ref: ref("k8s.io/api/core/v1.Lifecycle"), - }, - }, - "terminationMessagePath": { - SchemaProps: spec.SchemaProps{ - Description: "Optional: Path at which the file to which the container's termination message will be written is mounted into the container's filesystem. Message written is intended to be brief final status, such as an assertion failure message. Will be truncated by the node if greater than 4096 bytes. The total message length across all containers will be limited to 12kb. Defaults to /dev/termination-log. Cannot be updated.", - Type: []string{"string"}, - Format: "", - }, - }, - "terminationMessagePolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Indicate how the termination message should be populated. File will use the contents of terminationMessagePath to populate the container status message on both success and failure. FallbackToLogsOnError will use the last chunk of container log output if the termination message file is empty and the container exited with an error. The log output is limited to 2048 bytes or 80 lines, whichever is smaller. Defaults to File. Cannot be updated.\n\nPossible enum values:\n - `\"FallbackToLogsOnError\"` will read the most recent contents of the container logs for the container status message when the container exits with an error and the terminationMessagePath has no contents.\n - `\"File\"` is the default behavior and will set the container status message to the contents of the container's terminationMessagePath when the container exits.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"FallbackToLogsOnError", "File"}, - }, - }, - "imagePullPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More info: https://kubernetes.io/docs/concepts/containers/images#updating-images\n\nPossible enum values:\n - `\"Always\"` means that kubelet always attempts to pull the latest image. Container will fail If the pull fails.\n - `\"IfNotPresent\"` means that kubelet pulls if the image isn't present on disk. Container will fail if the image isn't present and the pull fails.\n - `\"Never\"` means that kubelet never pulls an image, but only uses a local image. Container will fail if the image isn't present", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Always", "IfNotPresent", "Never"}, - }, - }, - "securityContext": { - SchemaProps: spec.SchemaProps{ - Description: "Optional: SecurityContext defines the security options the ephemeral container should be run with. If set, the fields of SecurityContext override the equivalent fields of PodSecurityContext.", - Ref: ref("k8s.io/api/core/v1.SecurityContext"), - }, - }, - "stdin": { - SchemaProps: spec.SchemaProps{ - Description: "Whether this container should allocate a buffer for stdin in the container runtime. If this is not set, reads from stdin in the container will always result in EOF. Default is false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "stdinOnce": { - SchemaProps: spec.SchemaProps{ - Description: "Whether the container runtime should close the stdin channel after it has been opened by a single attach. When stdin is true the stdin stream will remain open across multiple attach sessions. If stdinOnce is set to true, stdin is opened on container start, is empty until the first client attaches to stdin, and then remains open and accepts data until the client disconnects, at which time stdin is closed and remains closed until the container is restarted. If this flag is false, a container processes that reads from stdin will never receive an EOF. Default is false", - Type: []string{"boolean"}, - Format: "", - }, - }, - "tty": { - SchemaProps: spec.SchemaProps{ - Description: "Whether this container should allocate a TTY for itself, also requires 'stdin' to be true. Default is false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"name"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ContainerPort", "k8s.io/api/core/v1.ContainerResizePolicy", "k8s.io/api/core/v1.EnvFromSource", "k8s.io/api/core/v1.EnvVar", "k8s.io/api/core/v1.Lifecycle", "k8s.io/api/core/v1.Probe", "k8s.io/api/core/v1.ResourceRequirements", "k8s.io/api/core/v1.SecurityContext", "k8s.io/api/core/v1.VolumeDevice", "k8s.io/api/core/v1.VolumeMount"}, - } -} - -func schema_k8sio_api_core_v1_EphemeralVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents an ephemeral volume that is handled by a normal storage driver.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "volumeClaimTemplate": { - SchemaProps: spec.SchemaProps{ - Description: "Will be used to create a stand-alone PVC to provision the volume. The pod in which this EphemeralVolumeSource is embedded will be the owner of the PVC, i.e. the PVC will be deleted together with the pod. The name of the PVC will be `-` where `` is the name from the `PodSpec.Volumes` array entry. Pod validation will reject the pod if the concatenated name is not valid for a PVC (for example, too long).\n\nAn existing PVC with that name that is not owned by the pod will *not* be used for the pod to avoid using an unrelated volume by mistake. Starting the pod is then blocked until the unrelated PVC is removed. If such a pre-created PVC is meant to be used by the pod, the PVC has to updated with an owner reference to the pod once the pod exists. Normally this should not be necessary, but it may be useful when manually reconstructing a broken cluster.\n\nThis field is read-only and no changes will be made by Kubernetes to the PVC after it has been created.\n\nRequired, must not be nil.", - Ref: ref("k8s.io/api/core/v1.PersistentVolumeClaimTemplate"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PersistentVolumeClaimTemplate"}, - } -} - -func schema_k8sio_api_core_v1_Event(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Event is a report of an event somewhere in the cluster. Events have a limited retention time and triggers and messages may evolve with time. Event consumers should not rely on the timing of an event with a given Reason reflecting a consistent underlying trigger, or the continued existence of events with that Reason. Events should be treated as informative, best-effort, supplemental data.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "involvedObject": { - SchemaProps: spec.SchemaProps{ - Description: "The object that this event is about.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ObjectReference"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "This should be a short, machine understandable string that gives the reason for the transition into the object's current status.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "A human-readable description of the status of this operation.", - Type: []string{"string"}, - Format: "", - }, - }, - "source": { - SchemaProps: spec.SchemaProps{ - Description: "The component reporting this event. Should be a short machine understandable string.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EventSource"), - }, - }, - "firstTimestamp": { - SchemaProps: spec.SchemaProps{ - Description: "The time at which the event was first recorded. (Time of server receipt is in TypeMeta.)", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "lastTimestamp": { - SchemaProps: spec.SchemaProps{ - Description: "The time at which the most recent occurrence of this event was recorded.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "count": { - SchemaProps: spec.SchemaProps{ - Description: "The number of times this event has occurred.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of this event (Normal, Warning), new types could be added in the future", - Type: []string{"string"}, - Format: "", - }, - }, - "eventTime": { - SchemaProps: spec.SchemaProps{ - Description: "Time when this Event was first observed.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.MicroTime"), - }, - }, - "series": { - SchemaProps: spec.SchemaProps{ - Description: "Data about the Event series this event represents or nil if it's a singleton Event.", - Ref: ref("k8s.io/api/core/v1.EventSeries"), - }, - }, - "action": { - SchemaProps: spec.SchemaProps{ - Description: "What action was taken/failed regarding to the Regarding object.", - Type: []string{"string"}, - Format: "", - }, - }, - "related": { - SchemaProps: spec.SchemaProps{ - Description: "Optional secondary object for more complex actions.", - Ref: ref("k8s.io/api/core/v1.ObjectReference"), - }, - }, - "reportingComponent": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the controller that emitted this Event, e.g. `kubernetes.io/kubelet`.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "reportingInstance": { - SchemaProps: spec.SchemaProps{ - Description: "ID of the controller instance, e.g. `kubelet-xyzf`.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"metadata", "involvedObject"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.EventSeries", "k8s.io/api/core/v1.EventSource", "k8s.io/api/core/v1.ObjectReference", "k8s.io/apimachinery/pkg/apis/meta/v1.MicroTime", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_EventList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EventList is a list of events.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of events", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Event"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.Event", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_EventSeries(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EventSeries contain information on series of events, i.e. thing that was/is happening continuously for some time.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "count": { - SchemaProps: spec.SchemaProps{ - Description: "Number of occurrences in this series up to the last heartbeat time", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "lastObservedTime": { - SchemaProps: spec.SchemaProps{ - Description: "Time of the last occurrence observed", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.MicroTime"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.MicroTime"}, - } -} - -func schema_k8sio_api_core_v1_EventSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EventSource contains information for an event.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "component": { - SchemaProps: spec.SchemaProps{ - Description: "Component from which the event is generated.", - Type: []string{"string"}, - Format: "", - }, - }, - "host": { - SchemaProps: spec.SchemaProps{ - Description: "Node name on which the event is generated.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ExecAction(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ExecAction describes a \"run in container\" action.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "command": { - SchemaProps: spec.SchemaProps{ - Description: "Command is the command line to execute inside the container, the working directory for the command is root ('/') in the container's filesystem. The command is simply exec'd, it is not run inside a shell, so traditional shell instructions ('|', etc) won't work. To use a shell, you need to explicitly call out to that shell. Exit status of 0 is treated as live/healthy and non-zero is unhealthy.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_FCVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Fibre Channel volume. Fibre Channel volumes can only be mounted as read/write once. Fibre Channel volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "targetWWNs": { - SchemaProps: spec.SchemaProps{ - Description: "targetWWNs is Optional: FC target worldwide names (WWNs)", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "lun": { - SchemaProps: spec.SchemaProps{ - Description: "lun is Optional: FC target lun number", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly is Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "wwids": { - SchemaProps: spec.SchemaProps{ - Description: "wwids Optional: FC volume world wide identifiers (wwids) Either wwids or combination of targetWWNs and lun must be set, but not both simultaneously.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_FlexPersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "FlexPersistentVolumeSource represents a generic persistent volume resource that is provisioned/attached using an exec based plugin.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "driver": { - SchemaProps: spec.SchemaProps{ - Description: "driver is the name of the driver to use for this volume.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". The default filesystem depends on FlexVolume script.", - Type: []string{"string"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef is Optional: SecretRef is reference to the secret object containing sensitive information to pass to the plugin scripts. This may be empty if no secret object is specified. If the secret object contains more than one secret, all secrets are passed to the plugin scripts.", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly is Optional: defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "options": { - SchemaProps: spec.SchemaProps{ - Description: "options is Optional: this field holds extra command options if any.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"driver"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.SecretReference"}, - } -} - -func schema_k8sio_api_core_v1_FlexVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "FlexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "driver": { - SchemaProps: spec.SchemaProps{ - Description: "driver is the name of the driver to use for this volume.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". The default filesystem depends on FlexVolume script.", - Type: []string{"string"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef is Optional: secretRef is reference to the secret object containing sensitive information to pass to the plugin scripts. This may be empty if no secret object is specified. If the secret object contains more than one secret, all secrets are passed to the plugin scripts.", - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly is Optional: defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "options": { - SchemaProps: spec.SchemaProps{ - Description: "options is Optional: this field holds extra command options if any.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"driver"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LocalObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_FlockerVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Flocker volume mounted by the Flocker agent. One and only one of datasetName and datasetUUID should be set. Flocker volumes do not support ownership management or SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "datasetName": { - SchemaProps: spec.SchemaProps{ - Description: "datasetName is Name of the dataset stored as metadata -> name on the dataset for Flocker should be considered as deprecated", - Type: []string{"string"}, - Format: "", - }, - }, - "datasetUUID": { - SchemaProps: spec.SchemaProps{ - Description: "datasetUUID is the UUID of the dataset. This is unique identifier of a Flocker dataset", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_GCEPersistentDiskVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Persistent Disk resource in Google Compute Engine.\n\nA GCE PD must exist before mounting to a container. The disk must also be in the same GCE project and zone as the kubelet. A GCE PD can only be mounted as read/write once or read-only many times. GCE PDs support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "pdName": { - SchemaProps: spec.SchemaProps{ - Description: "pdName is unique name of the PD resource in GCE. Used to identify the disk in GCE. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", - Type: []string{"string"}, - Format: "", - }, - }, - "partition": { - SchemaProps: spec.SchemaProps{ - Description: "partition is the partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as \"1\". Similarly, the volume partition for /dev/sda is \"0\" (or you can leave the property empty). More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"pdName"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_GRPCAction(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "port": { - SchemaProps: spec.SchemaProps{ - Description: "Port number of the gRPC service. Number must be in the range 1 to 65535.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "service": { - SchemaProps: spec.SchemaProps{ - Description: "Service is the name of the service to place in the gRPC HealthCheckRequest (see https://github.com/grpc/grpc/blob/master/doc/health-checking.md).\n\nIf this is not specified, the default behavior is defined by gRPC.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"port"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_GitRepoVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a volume that is populated with the contents of a git repository. Git repo volumes do not support ownership management. Git repo volumes support SELinux relabeling.\n\nDEPRECATED: GitRepo is deprecated. To provision a container with a git repo, mount an EmptyDir into an InitContainer that clones the repo using git, then mount the EmptyDir into the Pod's container.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "repository": { - SchemaProps: spec.SchemaProps{ - Description: "repository is the URL", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "revision": { - SchemaProps: spec.SchemaProps{ - Description: "revision is the commit hash for the specified revision.", - Type: []string{"string"}, - Format: "", - }, - }, - "directory": { - SchemaProps: spec.SchemaProps{ - Description: "directory is the target directory name. Must not contain or start with '..'. If '.' is supplied, the volume directory will be the git repository. Otherwise, if specified, the volume will contain the git repository in the subdirectory with the given name.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"repository"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_GlusterfsPersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Glusterfs mount that lasts the lifetime of a pod. Glusterfs volumes do not support ownership management or SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "endpoints": { - SchemaProps: spec.SchemaProps{ - Description: "endpoints is the endpoint name that details Glusterfs topology. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "path is the Glusterfs volume path. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly here will force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod", - Type: []string{"boolean"}, - Format: "", - }, - }, - "endpointsNamespace": { - SchemaProps: spec.SchemaProps{ - Description: "endpointsNamespace is the namespace that contains Glusterfs endpoint. If this field is empty, the EndpointNamespace defaults to the same namespace as the bound PVC. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"endpoints", "path"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_GlusterfsVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Glusterfs mount that lasts the lifetime of a pod. Glusterfs volumes do not support ownership management or SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "endpoints": { - SchemaProps: spec.SchemaProps{ - Description: "endpoints is the endpoint name that details Glusterfs topology. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "path is the Glusterfs volume path. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly here will force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"endpoints", "path"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_HTTPGetAction(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "HTTPGetAction describes an action based on HTTP Get requests.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "path": { - SchemaProps: spec.SchemaProps{ - Description: "Path to access on the HTTP server.", - Type: []string{"string"}, - Format: "", - }, - }, - "port": { - SchemaProps: spec.SchemaProps{ - Description: "Name or number of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.", - Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), - }, - }, - "host": { - SchemaProps: spec.SchemaProps{ - Description: "Host name to connect to, defaults to the pod IP. You probably want to set \"Host\" in httpHeaders instead.", - Type: []string{"string"}, - Format: "", - }, - }, - "scheme": { - SchemaProps: spec.SchemaProps{ - Description: "Scheme to use for connecting to the host. Defaults to HTTP.\n\nPossible enum values:\n - `\"HTTP\"` means that the scheme used will be http://\n - `\"HTTPS\"` means that the scheme used will be https://", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"HTTP", "HTTPS"}, - }, - }, - "httpHeaders": { - SchemaProps: spec.SchemaProps{ - Description: "Custom headers to set in the request. HTTP allows repeated headers.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.HTTPHeader"), - }, - }, - }, - }, - }, - }, - Required: []string{"port"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.HTTPHeader", "k8s.io/apimachinery/pkg/util/intstr.IntOrString"}, - } -} - -func schema_k8sio_api_core_v1_HTTPHeader(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "HTTPHeader describes a custom header to be used in HTTP probes", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "The header field name. This will be canonicalized upon output, so case-variant names will be understood as the same header.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "value": { - SchemaProps: spec.SchemaProps{ - Description: "The header field value", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name", "value"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_HostAlias(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "HostAlias holds the mapping between IP and hostnames that will be injected as an entry in the pod's hosts file.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "ip": { - SchemaProps: spec.SchemaProps{ - Description: "IP address of the host file entry.", - Type: []string{"string"}, - Format: "", - }, - }, - "hostnames": { - SchemaProps: spec.SchemaProps{ - Description: "Hostnames for the above IP address.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_HostIP(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "HostIP represents a single IP address allocated to the host.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "ip": { - SchemaProps: spec.SchemaProps{ - Description: "IP is the IP address assigned to the host", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_HostPathVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a host path mapped into a pod. Host path volumes do not support ownership management or SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "path": { - SchemaProps: spec.SchemaProps{ - Description: "path of the directory on the host. If the path is a symlink, it will follow the link to the real path. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "type": { - SchemaProps: spec.SchemaProps{ - Description: "type for HostPath Volume Defaults to \"\" More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath\n\nPossible enum values:\n - `\"\"` For backwards compatible, leave it empty if unset\n - `\"BlockDevice\"` A block device must exist at the given path\n - `\"CharDevice\"` A character device must exist at the given path\n - `\"Directory\"` A directory must exist at the given path\n - `\"DirectoryOrCreate\"` If nothing exists at the given path, an empty directory will be created there as needed with file mode 0755, having the same group and ownership with Kubelet.\n - `\"File\"` A file must exist at the given path\n - `\"FileOrCreate\"` If nothing exists at the given path, an empty file will be created there as needed with file mode 0644, having the same group and ownership with Kubelet.\n - `\"Socket\"` A UNIX socket must exist at the given path", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"", "BlockDevice", "CharDevice", "Directory", "DirectoryOrCreate", "File", "FileOrCreate", "Socket"}, - }, - }, - }, - Required: []string{"path"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ISCSIPersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ISCSIPersistentVolumeSource represents an ISCSI disk. ISCSI volumes can only be mounted as read/write once. ISCSI volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "targetPortal": { - SchemaProps: spec.SchemaProps{ - Description: "targetPortal is iSCSI Target Portal. The Portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260).", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "iqn": { - SchemaProps: spec.SchemaProps{ - Description: "iqn is Target iSCSI Qualified Name.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "lun": { - SchemaProps: spec.SchemaProps{ - Description: "lun is iSCSI Target Lun number.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "iscsiInterface": { - SchemaProps: spec.SchemaProps{ - Description: "iscsiInterface is the interface Name that uses an iSCSI transport. Defaults to 'default' (tcp).", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#iscsi", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "portals": { - SchemaProps: spec.SchemaProps{ - Description: "portals is the iSCSI Target Portal List. The Portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260).", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "chapAuthDiscovery": { - SchemaProps: spec.SchemaProps{ - Description: "chapAuthDiscovery defines whether support iSCSI Discovery CHAP authentication", - Type: []string{"boolean"}, - Format: "", - }, - }, - "chapAuthSession": { - SchemaProps: spec.SchemaProps{ - Description: "chapAuthSession defines whether support iSCSI Session CHAP authentication", - Type: []string{"boolean"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef is the CHAP Secret for iSCSI target and initiator authentication", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - "initiatorName": { - SchemaProps: spec.SchemaProps{ - Description: "initiatorName is the custom iSCSI Initiator Name. If initiatorName is specified with iscsiInterface simultaneously, new iSCSI interface : will be created for the connection.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"targetPortal", "iqn", "lun"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.SecretReference"}, - } -} - -func schema_k8sio_api_core_v1_ISCSIVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents an ISCSI disk. ISCSI volumes can only be mounted as read/write once. ISCSI volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "targetPortal": { - SchemaProps: spec.SchemaProps{ - Description: "targetPortal is iSCSI Target Portal. The Portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260).", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "iqn": { - SchemaProps: spec.SchemaProps{ - Description: "iqn is the target iSCSI Qualified Name.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "lun": { - SchemaProps: spec.SchemaProps{ - Description: "lun represents iSCSI Target Lun number.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "iscsiInterface": { - SchemaProps: spec.SchemaProps{ - Description: "iscsiInterface is the interface Name that uses an iSCSI transport. Defaults to 'default' (tcp).", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#iscsi", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "portals": { - SchemaProps: spec.SchemaProps{ - Description: "portals is the iSCSI Target Portal List. The portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260).", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "chapAuthDiscovery": { - SchemaProps: spec.SchemaProps{ - Description: "chapAuthDiscovery defines whether support iSCSI Discovery CHAP authentication", - Type: []string{"boolean"}, - Format: "", - }, - }, - "chapAuthSession": { - SchemaProps: spec.SchemaProps{ - Description: "chapAuthSession defines whether support iSCSI Session CHAP authentication", - Type: []string{"boolean"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef is the CHAP Secret for iSCSI target and initiator authentication", - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - "initiatorName": { - SchemaProps: spec.SchemaProps{ - Description: "initiatorName is the custom iSCSI Initiator Name. If initiatorName is specified with iscsiInterface simultaneously, new iSCSI interface : will be created for the connection.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"targetPortal", "iqn", "lun"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LocalObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_KeyToPath(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Maps a string key to a path within a volume.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "key": { - SchemaProps: spec.SchemaProps{ - Description: "key is the key to project.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "path is the relative path of the file to map the key to. May not be an absolute path. May not contain the path element '..'. May not start with the string '..'.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "mode": { - SchemaProps: spec.SchemaProps{ - Description: "mode is Optional: mode bits used to set permissions on this file. Must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - Required: []string{"key", "path"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_Lifecycle(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Lifecycle describes actions that the management system should take in response to container lifecycle events. For the PostStart and PreStop lifecycle handlers, management of the container blocks until the action is complete, unless the container process fails, in which case the handler is aborted.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "postStart": { - SchemaProps: spec.SchemaProps{ - Description: "PostStart is called immediately after a container is created. If the handler fails, the container is terminated and restarted according to its restart policy. Other management of the container blocks until the hook completes. More info: https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks", - Ref: ref("k8s.io/api/core/v1.LifecycleHandler"), - }, - }, - "preStop": { - SchemaProps: spec.SchemaProps{ - Description: "PreStop is called immediately before a container is terminated due to an API request or management event such as liveness/startup probe failure, preemption, resource contention, etc. The handler is not called if the container crashes or exits. The Pod's termination grace period countdown begins before the PreStop hook is executed. Regardless of the outcome of the handler, the container will eventually terminate within the Pod's termination grace period (unless delayed by finalizers). Other management of the container blocks until the hook completes or until the termination grace period is reached. More info: https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks", - Ref: ref("k8s.io/api/core/v1.LifecycleHandler"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LifecycleHandler"}, - } -} - -func schema_k8sio_api_core_v1_LifecycleHandler(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "LifecycleHandler defines a specific action that should be taken in a lifecycle hook. One and only one of the fields, except TCPSocket must be specified.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "exec": { - SchemaProps: spec.SchemaProps{ - Description: "Exec specifies the action to take.", - Ref: ref("k8s.io/api/core/v1.ExecAction"), - }, - }, - "httpGet": { - SchemaProps: spec.SchemaProps{ - Description: "HTTPGet specifies the http request to perform.", - Ref: ref("k8s.io/api/core/v1.HTTPGetAction"), - }, - }, - "tcpSocket": { - SchemaProps: spec.SchemaProps{ - Description: "Deprecated. TCPSocket is NOT supported as a LifecycleHandler and kept for the backward compatibility. There are no validation of this field and lifecycle hooks will fail in runtime when tcp handler is specified.", - Ref: ref("k8s.io/api/core/v1.TCPSocketAction"), - }, - }, - "sleep": { - SchemaProps: spec.SchemaProps{ - Description: "Sleep represents the duration that the container should sleep before being terminated.", - Ref: ref("k8s.io/api/core/v1.SleepAction"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ExecAction", "k8s.io/api/core/v1.HTTPGetAction", "k8s.io/api/core/v1.SleepAction", "k8s.io/api/core/v1.TCPSocketAction"}, - } -} - -func schema_k8sio_api_core_v1_LimitRange(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "LimitRange sets resource usage limits for each kind of resource in a Namespace.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Spec defines the limits enforced. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.LimitRangeSpec"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LimitRangeSpec", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_LimitRangeItem(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "LimitRangeItem defines a min/max usage limit for any resource that matches on kind.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of resource that this limit applies to.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "max": { - SchemaProps: spec.SchemaProps{ - Description: "Max usage constraints on this kind by resource name.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "min": { - SchemaProps: spec.SchemaProps{ - Description: "Min usage constraints on this kind by resource name.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "default": { - SchemaProps: spec.SchemaProps{ - Description: "Default resource requirement limit value by resource name if resource limit is omitted.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "defaultRequest": { - SchemaProps: spec.SchemaProps{ - Description: "DefaultRequest is the default resource requirement request value by resource name if resource request is omitted.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "maxLimitRequestRatio": { - SchemaProps: spec.SchemaProps{ - Description: "MaxLimitRequestRatio if specified, the named resource must have a request and limit that are both non-zero where limit divided by request is less than or equal to the enumerated value; this represents the max burst for the named resource.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - }, - Required: []string{"type"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_LimitRangeList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "LimitRangeList is a list of LimitRange items.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is a list of LimitRange objects. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.LimitRange"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LimitRange", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_LimitRangeSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "LimitRangeSpec defines a min/max usage limit for resources that match on kind.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "limits": { - SchemaProps: spec.SchemaProps{ - Description: "Limits is the list of LimitRangeItem objects that are enforced.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.LimitRangeItem"), - }, - }, - }, - }, - }, - }, - Required: []string{"limits"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LimitRangeItem"}, - } -} - -func schema_k8sio_api_core_v1_List(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "List holds a list of objects, which may not be known by the server.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of objects", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/runtime.RawExtension"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "k8s.io/apimachinery/pkg/runtime.RawExtension"}, - } -} - -func schema_k8sio_api_core_v1_LoadBalancerIngress(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "LoadBalancerIngress represents the status of a load-balancer ingress point: traffic intended for the service should be sent to an ingress point.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "ip": { - SchemaProps: spec.SchemaProps{ - Description: "IP is set for load-balancer ingress points that are IP based (typically GCE or OpenStack load-balancers)", - Type: []string{"string"}, - Format: "", - }, - }, - "hostname": { - SchemaProps: spec.SchemaProps{ - Description: "Hostname is set for load-balancer ingress points that are DNS based (typically AWS load-balancers)", - Type: []string{"string"}, - Format: "", - }, - }, - "ipMode": { - SchemaProps: spec.SchemaProps{ - Description: "IPMode specifies how the load-balancer IP behaves, and may only be specified when the ip field is specified. Setting this to \"VIP\" indicates that traffic is delivered to the node with the destination set to the load-balancer's IP and port. Setting this to \"Proxy\" indicates that traffic is delivered to the node or pod with the destination set to the node's IP and node port or the pod's IP and port. Service implementations may use this information to adjust traffic routing.", - Type: []string{"string"}, - Format: "", - }, - }, - "ports": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Ports is a list of records of service ports If used, every port defined in the service should have an entry in it", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PortStatus"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PortStatus"}, - } -} - -func schema_k8sio_api_core_v1_LoadBalancerStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "LoadBalancerStatus represents the status of a load-balancer.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "ingress": { - SchemaProps: spec.SchemaProps{ - Description: "Ingress is a list containing ingress points for the load-balancer. Traffic intended for the service should be sent to these ingress points.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.LoadBalancerIngress"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LoadBalancerIngress"}, - } -} - -func schema_k8sio_api_core_v1_LocalObjectReference(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "LocalObjectReference contains enough information to let you locate the referenced object inside the same namespace.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_LocalVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Local represents directly-attached storage with node affinity (Beta feature)", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "path": { - SchemaProps: spec.SchemaProps{ - Description: "path of the full path to the volume on the node. It can be either a directory or block device (disk, partition, ...).", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type to mount. It applies only when the Path is a block device. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". The default value is to auto-select a filesystem if unspecified.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"path"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ModifyVolumeStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ModifyVolumeStatus represents the status object of ControllerModifyVolume operation", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "targetVolumeAttributesClassName": { - SchemaProps: spec.SchemaProps{ - Description: "targetVolumeAttributesClassName is the name of the VolumeAttributesClass the PVC currently being reconciled", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "status is the status of the ControllerModifyVolume operation. It can be in any of following states:\n - Pending\n Pending indicates that the PersistentVolumeClaim cannot be modified due to unmet requirements, such as\n the specified VolumeAttributesClass not existing.\n - InProgress\n InProgress indicates that the volume is being modified.\n - Infeasible\n Infeasible indicates that the request has been rejected as invalid by the CSI driver. To\n\t resolve the error, a valid VolumeAttributesClass needs to be specified.\nNote: New statuses can be added in the future. Consumers should check for unknown statuses and fail appropriately.\n\nPossible enum values:\n - `\"InProgress\"` InProgress indicates that the volume is being modified\n - `\"Infeasible\"` Infeasible indicates that the request has been rejected as invalid by the CSI driver. To resolve the error, a valid VolumeAttributesClass needs to be specified\n - `\"Pending\"` Pending indicates that the PersistentVolumeClaim cannot be modified due to unmet requirements, such as the specified VolumeAttributesClass not existing", - Default: "", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"InProgress", "Infeasible", "Pending"}, - }, - }, - }, - Required: []string{"status"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_NFSVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents an NFS mount that lasts the lifetime of a pod. NFS volumes do not support ownership management or SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "server": { - SchemaProps: spec.SchemaProps{ - Description: "server is the hostname or IP address of the NFS server. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "path that is exported by the NFS server. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly here will force the NFS export to be mounted with read-only permissions. Defaults to false. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"server", "path"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_Namespace(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Namespace provides a scope for Names. Use of multiple namespaces is optional.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Spec defines the behavior of the Namespace. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NamespaceSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status describes the current status of a Namespace. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NamespaceStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NamespaceSpec", "k8s.io/api/core/v1.NamespaceStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_NamespaceCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NamespaceCondition contains details about state of namespace.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of namespace controller condition.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status of the condition, one of True, False, Unknown.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "lastTransitionTime": { - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_NamespaceList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NamespaceList is a list of Namespaces.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is the list of Namespace objects in the list. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Namespace"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.Namespace", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_NamespaceSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NamespaceSpec describes the attributes on a Namespace.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "finalizers": { - SchemaProps: spec.SchemaProps{ - Description: "Finalizers is an opaque list of values that must be empty to permanently remove object from storage. More info: https://kubernetes.io/docs/tasks/administer-cluster/namespaces/", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_NamespaceStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NamespaceStatus is information about the current status of a Namespace.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "phase": { - SchemaProps: spec.SchemaProps{ - Description: "Phase is the current lifecycle phase of the namespace. More info: https://kubernetes.io/docs/tasks/administer-cluster/namespaces/\n\nPossible enum values:\n - `\"Active\"` means the namespace is available for use in the system\n - `\"Terminating\"` means the namespace is undergoing graceful termination", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Active", "Terminating"}, - }, - }, - "conditions": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Represents the latest available observations of a namespace's current state.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NamespaceCondition"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NamespaceCondition"}, - } -} - -func schema_k8sio_api_core_v1_Node(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Node is a worker node in Kubernetes. Each node will have a unique identifier in the cache (i.e. in etcd).", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Spec defines the behavior of a node. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NodeSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Most recently observed status of the node. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NodeStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NodeSpec", "k8s.io/api/core/v1.NodeStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_NodeAddress(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeAddress contains information for the node's address.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Node address type, one of Hostname, ExternalIP or InternalIP.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "address": { - SchemaProps: spec.SchemaProps{ - Description: "The node address.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "address"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_NodeAffinity(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Node affinity is a group of node affinity scheduling rules.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "requiredDuringSchedulingIgnoredDuringExecution": { - SchemaProps: spec.SchemaProps{ - Description: "If the affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to an update), the system may or may not try to eventually evict the pod from its node.", - Ref: ref("k8s.io/api/core/v1.NodeSelector"), - }, - }, - "preferredDuringSchedulingIgnoredDuringExecution": { - SchemaProps: spec.SchemaProps{ - Description: "The scheduler will prefer to schedule pods to nodes that satisfy the affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding \"weight\" to the sum if the node matches the corresponding matchExpressions; the node(s) with the highest sum are the most preferred.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PreferredSchedulingTerm"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NodeSelector", "k8s.io/api/core/v1.PreferredSchedulingTerm"}, - } -} - -func schema_k8sio_api_core_v1_NodeCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeCondition contains condition information for a node.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of node condition.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status of the condition, one of True, False, Unknown.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "lastHeartbeatTime": { - SchemaProps: spec.SchemaProps{ - Description: "Last time we got an update on a given condition.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "lastTransitionTime": { - SchemaProps: spec.SchemaProps{ - Description: "Last time the condition transit from one status to another.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "(brief) reason for the condition's last transition.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "Human readable message indicating details about last transition.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_NodeConfigSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeConfigSource specifies a source of node configuration. Exactly one subfield (excluding metadata) must be non-nil. This API is deprecated since 1.22", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "configMap": { - SchemaProps: spec.SchemaProps{ - Description: "ConfigMap is a reference to a Node's ConfigMap", - Ref: ref("k8s.io/api/core/v1.ConfigMapNodeConfigSource"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ConfigMapNodeConfigSource"}, - } -} - -func schema_k8sio_api_core_v1_NodeConfigStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeConfigStatus describes the status of the config assigned by Node.Spec.ConfigSource.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "assigned": { - SchemaProps: spec.SchemaProps{ - Description: "Assigned reports the checkpointed config the node will try to use. When Node.Spec.ConfigSource is updated, the node checkpoints the associated config payload to local disk, along with a record indicating intended config. The node refers to this record to choose its config checkpoint, and reports this record in Assigned. Assigned only updates in the status after the record has been checkpointed to disk. When the Kubelet is restarted, it tries to make the Assigned config the Active config by loading and validating the checkpointed payload identified by Assigned.", - Ref: ref("k8s.io/api/core/v1.NodeConfigSource"), - }, - }, - "active": { - SchemaProps: spec.SchemaProps{ - Description: "Active reports the checkpointed config the node is actively using. Active will represent either the current version of the Assigned config, or the current LastKnownGood config, depending on whether attempting to use the Assigned config results in an error.", - Ref: ref("k8s.io/api/core/v1.NodeConfigSource"), - }, - }, - "lastKnownGood": { - SchemaProps: spec.SchemaProps{ - Description: "LastKnownGood reports the checkpointed config the node will fall back to when it encounters an error attempting to use the Assigned config. The Assigned config becomes the LastKnownGood config when the node determines that the Assigned config is stable and correct. This is currently implemented as a 10-minute soak period starting when the local record of Assigned config is updated. If the Assigned config is Active at the end of this period, it becomes the LastKnownGood. Note that if Spec.ConfigSource is reset to nil (use local defaults), the LastKnownGood is also immediately reset to nil, because the local default config is always assumed good. You should not make assumptions about the node's method of determining config stability and correctness, as this may change or become configurable in the future.", - Ref: ref("k8s.io/api/core/v1.NodeConfigSource"), - }, - }, - "error": { - SchemaProps: spec.SchemaProps{ - Description: "Error describes any problems reconciling the Spec.ConfigSource to the Active config. Errors may occur, for example, attempting to checkpoint Spec.ConfigSource to the local Assigned record, attempting to checkpoint the payload associated with Spec.ConfigSource, attempting to load or validate the Assigned config, etc. Errors may occur at different points while syncing config. Earlier errors (e.g. download or checkpointing errors) will not result in a rollback to LastKnownGood, and may resolve across Kubelet retries. Later errors (e.g. loading or validating a checkpointed config) will result in a rollback to LastKnownGood. In the latter case, it is usually possible to resolve the error by fixing the config assigned in Spec.ConfigSource. You can find additional information for debugging by searching the error message in the Kubelet log. Error is a human-readable description of the error state; machines can check whether or not Error is empty, but should not rely on the stability of the Error text across Kubelet versions.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NodeConfigSource"}, - } -} - -func schema_k8sio_api_core_v1_NodeDaemonEndpoints(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeDaemonEndpoints lists ports opened by daemons running on the Node.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kubeletEndpoint": { - SchemaProps: spec.SchemaProps{ - Description: "Endpoint on which Kubelet is listening.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.DaemonEndpoint"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.DaemonEndpoint"}, - } -} - -func schema_k8sio_api_core_v1_NodeList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeList is the whole list of all Nodes which have been registered with master.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of nodes", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Node"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.Node", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_NodeProxyOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeProxyOptions is the query options to a Node's proxy call.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "Path is the URL path to use for the current proxy request to node.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_NodeResources(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeResources is an object for conveying resource information about a node. see https://kubernetes.io/docs/concepts/architecture/nodes/#capacity for more details.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "Capacity": { - SchemaProps: spec.SchemaProps{ - Description: "Capacity represents the available resources of a node", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - }, - Required: []string{"Capacity"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_NodeSelector(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A node selector represents the union of the results of one or more label queries over a set of nodes; that is, it represents the OR of the selectors represented by the node selector terms.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "nodeSelectorTerms": { - SchemaProps: spec.SchemaProps{ - Description: "Required. A list of node selector terms. The terms are ORed.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NodeSelectorTerm"), - }, - }, - }, - }, - }, - }, - Required: []string{"nodeSelectorTerms"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NodeSelectorTerm"}, - } -} - -func schema_k8sio_api_core_v1_NodeSelectorRequirement(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A node selector requirement is a selector that contains values, a key, and an operator that relates the key and values.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "key": { - SchemaProps: spec.SchemaProps{ - Description: "The label key that the selector applies to.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "operator": { - SchemaProps: spec.SchemaProps{ - Description: "Represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt.\n\nPossible enum values:\n - `\"DoesNotExist\"`\n - `\"Exists\"`\n - `\"Gt\"`\n - `\"In\"`\n - `\"Lt\"`\n - `\"NotIn\"`", - Default: "", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"DoesNotExist", "Exists", "Gt", "In", "Lt", "NotIn"}, - }, - }, - "values": { - SchemaProps: spec.SchemaProps{ - Description: "An array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. If the operator is Gt or Lt, the values array must have a single element, which will be interpreted as an integer. This array is replaced during a strategic merge patch.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"key", "operator"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_NodeSelectorTerm(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A null or empty node selector term matches no objects. The requirements of them are ANDed. The TopologySelectorTerm type implements a subset of the NodeSelectorTerm.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "matchExpressions": { - SchemaProps: spec.SchemaProps{ - Description: "A list of node selector requirements by node's labels.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NodeSelectorRequirement"), - }, - }, - }, - }, - }, - "matchFields": { - SchemaProps: spec.SchemaProps{ - Description: "A list of node selector requirements by node's fields.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NodeSelectorRequirement"), - }, - }, - }, - }, - }, - }, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NodeSelectorRequirement"}, - } -} - -func schema_k8sio_api_core_v1_NodeSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeSpec describes the attributes that a node is created with.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "podCIDR": { - SchemaProps: spec.SchemaProps{ - Description: "PodCIDR represents the pod IP range assigned to the node.", - Type: []string{"string"}, - Format: "", - }, - }, - "podCIDRs": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "podCIDRs represents the IP ranges assigned to the node for usage by Pods on that node. If this field is specified, the 0th entry must match the podCIDR field. It may contain at most 1 value for each of IPv4 and IPv6.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "providerID": { - SchemaProps: spec.SchemaProps{ - Description: "ID of the node assigned by the cloud provider in the format: ://", - Type: []string{"string"}, - Format: "", - }, - }, - "unschedulable": { - SchemaProps: spec.SchemaProps{ - Description: "Unschedulable controls node schedulability of new pods. By default, node is schedulable. More info: https://kubernetes.io/docs/concepts/nodes/node/#manual-node-administration", - Type: []string{"boolean"}, - Format: "", - }, - }, - "taints": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, the node's taints.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Taint"), - }, - }, - }, - }, - }, - "configSource": { - SchemaProps: spec.SchemaProps{ - Description: "Deprecated: Previously used to specify the source of the node's configuration for the DynamicKubeletConfig feature. This feature is removed.", - Ref: ref("k8s.io/api/core/v1.NodeConfigSource"), - }, - }, - "externalID": { - SchemaProps: spec.SchemaProps{ - Description: "Deprecated. Not all kubelets will set this field. Remove field after 1.13. see: https://issues.k8s.io/61966", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NodeConfigSource", "k8s.io/api/core/v1.Taint"}, - } -} - -func schema_k8sio_api_core_v1_NodeStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeStatus is information about the current status of a node.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "capacity": { - SchemaProps: spec.SchemaProps{ - Description: "Capacity represents the total resources of a node. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#capacity", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "allocatable": { - SchemaProps: spec.SchemaProps{ - Description: "Allocatable represents the resources of a node that are available for scheduling. Defaults to Capacity.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "phase": { - SchemaProps: spec.SchemaProps{ - Description: "NodePhase is the recently observed lifecycle phase of the node. More info: https://kubernetes.io/docs/concepts/nodes/node/#phase The field is never populated, and now is deprecated.\n\nPossible enum values:\n - `\"Pending\"` means the node has been created/added by the system, but not configured.\n - `\"Running\"` means the node has been configured and has Kubernetes components running.\n - `\"Terminated\"` means the node has been removed from the cluster.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Pending", "Running", "Terminated"}, - }, - }, - "conditions": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Conditions is an array of current observed node conditions. More info: https://kubernetes.io/docs/concepts/nodes/node/#condition", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NodeCondition"), - }, - }, - }, - }, - }, - "addresses": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of addresses reachable to the node. Queried from cloud provider, if available. More info: https://kubernetes.io/docs/concepts/nodes/node/#addresses Note: This field is declared as mergeable, but the merge key is not sufficiently unique, which can cause data corruption when it is merged. Callers should instead use a full-replacement patch. See https://pr.k8s.io/79391 for an example. Consumers should assume that addresses can change during the lifetime of a Node. However, there are some exceptions where this may not be possible, such as Pods that inherit a Node's address in its own status or consumers of the downward API (status.hostIP).", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NodeAddress"), - }, - }, - }, - }, - }, - "daemonEndpoints": { - SchemaProps: spec.SchemaProps{ - Description: "Endpoints of daemons running on the Node.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NodeDaemonEndpoints"), - }, - }, - "nodeInfo": { - SchemaProps: spec.SchemaProps{ - Description: "Set of ids/uuids to uniquely identify the node. More info: https://kubernetes.io/docs/concepts/nodes/node/#info", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NodeSystemInfo"), - }, - }, - "images": { - SchemaProps: spec.SchemaProps{ - Description: "List of container images on this node", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerImage"), - }, - }, - }, - }, - }, - "volumesInUse": { - SchemaProps: spec.SchemaProps{ - Description: "List of attachable volumes in use (mounted) by the node.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "volumesAttached": { - SchemaProps: spec.SchemaProps{ - Description: "List of volumes that are attached to the node.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.AttachedVolume"), - }, - }, - }, - }, - }, - "config": { - SchemaProps: spec.SchemaProps{ - Description: "Status of the config assigned to the node via the dynamic Kubelet config feature.", - Ref: ref("k8s.io/api/core/v1.NodeConfigStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.AttachedVolume", "k8s.io/api/core/v1.ContainerImage", "k8s.io/api/core/v1.NodeAddress", "k8s.io/api/core/v1.NodeCondition", "k8s.io/api/core/v1.NodeConfigStatus", "k8s.io/api/core/v1.NodeDaemonEndpoints", "k8s.io/api/core/v1.NodeSystemInfo", "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_NodeSystemInfo(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeSystemInfo is a set of ids/uuids to uniquely identify the node.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "machineID": { - SchemaProps: spec.SchemaProps{ - Description: "MachineID reported by the node. For unique machine identification in the cluster this field is preferred. Learn more from man(5) machine-id: http://man7.org/linux/man-pages/man5/machine-id.5.html", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "systemUUID": { - SchemaProps: spec.SchemaProps{ - Description: "SystemUUID reported by the node. For unique machine identification MachineID is preferred. This field is specific to Red Hat hosts https://access.redhat.com/documentation/en-us/red_hat_subscription_management/1/html/rhsm/uuid", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "bootID": { - SchemaProps: spec.SchemaProps{ - Description: "Boot ID reported by the node.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "kernelVersion": { - SchemaProps: spec.SchemaProps{ - Description: "Kernel Version reported by the node from 'uname -r' (e.g. 3.16.0-0.bpo.4-amd64).", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "osImage": { - SchemaProps: spec.SchemaProps{ - Description: "OS Image reported by the node from /etc/os-release (e.g. Debian GNU/Linux 7 (wheezy)).", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "containerRuntimeVersion": { - SchemaProps: spec.SchemaProps{ - Description: "ContainerRuntime Version reported by the node through runtime remote API (e.g. containerd://1.4.2).", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "kubeletVersion": { - SchemaProps: spec.SchemaProps{ - Description: "Kubelet Version reported by the node.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "kubeProxyVersion": { - SchemaProps: spec.SchemaProps{ - Description: "KubeProxy Version reported by the node.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "operatingSystem": { - SchemaProps: spec.SchemaProps{ - Description: "The Operating System reported by the node", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "architecture": { - SchemaProps: spec.SchemaProps{ - Description: "The Architecture reported by the node", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"machineID", "systemUUID", "bootID", "kernelVersion", "osImage", "containerRuntimeVersion", "kubeletVersion", "kubeProxyVersion", "operatingSystem", "architecture"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ObjectFieldSelector(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ObjectFieldSelector selects an APIVersioned field of an object.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "Version of the schema the FieldPath is written in terms of, defaults to \"v1\".", - Type: []string{"string"}, - Format: "", - }, - }, - "fieldPath": { - SchemaProps: spec.SchemaProps{ - Description: "Path of the field to select in the specified API version.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"fieldPath"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ObjectReference(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ObjectReference contains enough information to let you inspect or modify the referred object.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "namespace": { - SchemaProps: spec.SchemaProps{ - Description: "Namespace of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/", - Type: []string{"string"}, - Format: "", - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Type: []string{"string"}, - Format: "", - }, - }, - "uid": { - SchemaProps: spec.SchemaProps{ - Description: "UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#uids", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "API version of the referent.", - Type: []string{"string"}, - Format: "", - }, - }, - "resourceVersion": { - SchemaProps: spec.SchemaProps{ - Description: "Specific resourceVersion to which this reference is made, if any. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency", - Type: []string{"string"}, - Format: "", - }, - }, - "fieldPath": { - SchemaProps: spec.SchemaProps{ - Description: "If referring to a piece of an object instead of an entire object, this string should contain a valid JSON/Go field access statement, such as desiredState.manifest.containers[2]. For example, if the object reference is to a container within a pod, this would take on a value like: \"spec.containers{name}\" (where \"name\" refers to the name of the container that triggered the event) or if no container name is specified \"spec.containers[2]\" (container with index 2 in this pod). This syntax is chosen only to have some well-defined way of referencing a part of an object.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PersistentVolume(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolume (PV) is a storage resource provisioned by an administrator. It is analogous to a node. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "spec defines a specification of a persistent volume owned by the cluster. Provisioned by an administrator. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistent-volumes", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PersistentVolumeSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "status represents the current information/status for the persistent volume. Populated by the system. Read-only. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistent-volumes", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PersistentVolumeStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PersistentVolumeSpec", "k8s.io/api/core/v1.PersistentVolumeStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeClaim(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeClaim is a user's request for and claim to a persistent volume", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "spec defines the desired characteristics of a volume requested by a pod author. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PersistentVolumeClaimSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "status represents the current information/status of a persistent volume claim. Read-only. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PersistentVolumeClaimStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PersistentVolumeClaimSpec", "k8s.io/api/core/v1.PersistentVolumeClaimStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeClaimCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeClaimCondition contains details about state of pvc", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "lastProbeTime": { - SchemaProps: spec.SchemaProps{ - Description: "lastProbeTime is the time we probed the condition.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "lastTransitionTime": { - SchemaProps: spec.SchemaProps{ - Description: "lastTransitionTime is the time the condition transitioned from one status to another.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "reason is a unique, this should be a short, machine understandable string that gives the reason for condition's last transition. If it reports \"ResizeStarted\" that means the underlying persistent volume is being resized.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "message is the human-readable message indicating details about last transition.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeClaimList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeClaimList is a list of PersistentVolumeClaim items.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "items is a list of persistent volume claims. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PersistentVolumeClaim"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PersistentVolumeClaim", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeClaimSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeClaimSpec describes the common attributes of storage devices and allows a Source for provider-specific attributes", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "accessModes": { - SchemaProps: spec.SchemaProps{ - Description: "accessModes contains the desired access modes the volume should have. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#access-modes-1", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "selector": { - SchemaProps: spec.SchemaProps{ - Description: "selector is a label query over volumes to consider for binding.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), - }, - }, - "resources": { - SchemaProps: spec.SchemaProps{ - Description: "resources represents the minimum resources the volume should have. If RecoverVolumeExpansionFailure feature is enabled users are allowed to specify resource requirements that are lower than previous value but must still be higher than capacity recorded in the status field of the claim. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#resources", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.VolumeResourceRequirements"), - }, - }, - "volumeName": { - SchemaProps: spec.SchemaProps{ - Description: "volumeName is the binding reference to the PersistentVolume backing this claim.", - Type: []string{"string"}, - Format: "", - }, - }, - "storageClassName": { - SchemaProps: spec.SchemaProps{ - Description: "storageClassName is the name of the StorageClass required by the claim. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#class-1", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeMode": { - SchemaProps: spec.SchemaProps{ - Description: "volumeMode defines what type of volume is required by the claim. Value of Filesystem is implied when not included in claim spec.\n\nPossible enum values:\n - `\"Block\"` means the volume will not be formatted with a filesystem and will remain a raw block device.\n - `\"Filesystem\"` means the volume will be or is formatted with a filesystem.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Block", "Filesystem"}, - }, - }, - "dataSource": { - SchemaProps: spec.SchemaProps{ - Description: "dataSource field can be used to specify either: * An existing VolumeSnapshot object (snapshot.storage.k8s.io/VolumeSnapshot) * An existing PVC (PersistentVolumeClaim) If the provisioner or an external controller can support the specified data source, it will create a new volume based on the contents of the specified data source. When the AnyVolumeDataSource feature gate is enabled, dataSource contents will be copied to dataSourceRef, and dataSourceRef contents will be copied to dataSource when dataSourceRef.namespace is not specified. If the namespace is specified, then dataSourceRef will not be copied to dataSource.", - Ref: ref("k8s.io/api/core/v1.TypedLocalObjectReference"), - }, - }, - "dataSourceRef": { - SchemaProps: spec.SchemaProps{ - Description: "dataSourceRef specifies the object from which to populate the volume with data, if a non-empty volume is desired. This may be any object from a non-empty API group (non core object) or a PersistentVolumeClaim object. When this field is specified, volume binding will only succeed if the type of the specified object matches some installed volume populator or dynamic provisioner. This field will replace the functionality of the dataSource field and as such if both fields are non-empty, they must have the same value. For backwards compatibility, when namespace isn't specified in dataSourceRef, both fields (dataSource and dataSourceRef) will be set to the same value automatically if one of them is empty and the other is non-empty. When namespace is specified in dataSourceRef, dataSource isn't set to the same value and must be empty. There are three important differences between dataSource and dataSourceRef: * While dataSource only allows two specific types of objects, dataSourceRef\n allows any non-core object, as well as PersistentVolumeClaim objects.\n* While dataSource ignores disallowed values (dropping them), dataSourceRef\n preserves all values, and generates an error if a disallowed value is\n specified.\n* While dataSource only allows local objects, dataSourceRef allows objects\n in any namespaces.\n(Beta) Using this field requires the AnyVolumeDataSource feature gate to be enabled. (Alpha) Using the namespace field of dataSourceRef requires the CrossNamespaceVolumeDataSource feature gate to be enabled.", - Ref: ref("k8s.io/api/core/v1.TypedObjectReference"), - }, - }, - "volumeAttributesClassName": { - SchemaProps: spec.SchemaProps{ - Description: "volumeAttributesClassName may be used to set the VolumeAttributesClass used by this claim. If specified, the CSI driver will create or update the volume with the attributes defined in the corresponding VolumeAttributesClass. This has a different purpose than storageClassName, it can be changed after the claim is created. An empty string value means that no VolumeAttributesClass will be applied to the claim but it's not allowed to reset this field to empty string once it is set. If unspecified and the PersistentVolumeClaim is unbound, the default VolumeAttributesClass will be set by the persistentvolume controller if it exists. If the resource referred to by volumeAttributesClass does not exist, this PersistentVolumeClaim will be set to a Pending state, as reflected by the modifyVolumeStatus field, until such as a resource exists. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#volumeattributesclass (Alpha) Using this field requires the VolumeAttributesClass feature gate to be enabled.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.TypedLocalObjectReference", "k8s.io/api/core/v1.TypedObjectReference", "k8s.io/api/core/v1.VolumeResourceRequirements", "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"}, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeClaimStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeClaimStatus is the current status of a persistent volume claim.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "phase": { - SchemaProps: spec.SchemaProps{ - Description: "phase represents the current phase of PersistentVolumeClaim.\n\nPossible enum values:\n - `\"Bound\"` used for PersistentVolumeClaims that are bound\n - `\"Lost\"` used for PersistentVolumeClaims that lost their underlying PersistentVolume. The claim was bound to a PersistentVolume and this volume does not exist any longer and all data on it was lost.\n - `\"Pending\"` used for PersistentVolumeClaims that are not yet bound", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Bound", "Lost", "Pending"}, - }, - }, - "accessModes": { - SchemaProps: spec.SchemaProps{ - Description: "accessModes contains the actual access modes the volume backing the PVC has. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#access-modes-1", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "capacity": { - SchemaProps: spec.SchemaProps{ - Description: "capacity represents the actual resources of the underlying volume.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "conditions": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "conditions is the current Condition of persistent volume claim. If underlying persistent volume is being resized then the Condition will be set to 'ResizeStarted'.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PersistentVolumeClaimCondition"), - }, - }, - }, - }, - }, - "allocatedResources": { - SchemaProps: spec.SchemaProps{ - Description: "allocatedResources tracks the resources allocated to a PVC including its capacity. Key names follow standard Kubernetes label syntax. Valid values are either:\n\t* Un-prefixed keys:\n\t\t- storage - the capacity of the volume.\n\t* Custom resources must use implementation-defined prefixed names such as \"example.com/my-custom-resource\"\nApart from above values - keys that are unprefixed or have kubernetes.io prefix are considered reserved and hence may not be used.\n\nCapacity reported here may be larger than the actual capacity when a volume expansion operation is requested. For storage quota, the larger value from allocatedResources and PVC.spec.resources is used. If allocatedResources is not set, PVC.spec.resources alone is used for quota calculation. If a volume expansion capacity request is lowered, allocatedResources is only lowered if there are no expansion operations in progress and if the actual volume capacity is equal or lower than the requested capacity.\n\nA controller that receives PVC update with previously unknown resourceName should ignore the update for the purpose it was designed. For example - a controller that only is responsible for resizing capacity of the volume, should ignore PVC updates that change other valid resources associated with PVC.\n\nThis is an alpha field and requires enabling RecoverVolumeExpansionFailure feature.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "allocatedResourceStatuses": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "granular", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "allocatedResourceStatuses stores status of resource being resized for the given PVC. Key names follow standard Kubernetes label syntax. Valid values are either:\n\t* Un-prefixed keys:\n\t\t- storage - the capacity of the volume.\n\t* Custom resources must use implementation-defined prefixed names such as \"example.com/my-custom-resource\"\nApart from above values - keys that are unprefixed or have kubernetes.io prefix are considered reserved and hence may not be used.\n\nClaimResourceStatus can be in any of following states:\n\t- ControllerResizeInProgress:\n\t\tState set when resize controller starts resizing the volume in control-plane.\n\t- ControllerResizeFailed:\n\t\tState set when resize has failed in resize controller with a terminal error.\n\t- NodeResizePending:\n\t\tState set when resize controller has finished resizing the volume but further resizing of\n\t\tvolume is needed on the node.\n\t- NodeResizeInProgress:\n\t\tState set when kubelet starts resizing the volume.\n\t- NodeResizeFailed:\n\t\tState set when resizing has failed in kubelet with a terminal error. Transient errors don't set\n\t\tNodeResizeFailed.\nFor example: if expanding a PVC for more capacity - this field can be one of the following states:\n\t- pvc.status.allocatedResourceStatus['storage'] = \"ControllerResizeInProgress\"\n - pvc.status.allocatedResourceStatus['storage'] = \"ControllerResizeFailed\"\n - pvc.status.allocatedResourceStatus['storage'] = \"NodeResizePending\"\n - pvc.status.allocatedResourceStatus['storage'] = \"NodeResizeInProgress\"\n - pvc.status.allocatedResourceStatus['storage'] = \"NodeResizeFailed\"\nWhen this field is not set, it means that no resize operation is in progress for the given PVC.\n\nA controller that receives PVC update with previously unknown resourceName or ClaimResourceStatus should ignore the update for the purpose it was designed. For example - a controller that only is responsible for resizing capacity of the volume, should ignore PVC updates that change other valid resources associated with PVC.\n\nThis is an alpha field and requires enabling RecoverVolumeExpansionFailure feature.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "currentVolumeAttributesClassName": { - SchemaProps: spec.SchemaProps{ - Description: "currentVolumeAttributesClassName is the current name of the VolumeAttributesClass the PVC is using. When unset, there is no VolumeAttributeClass applied to this PersistentVolumeClaim This is an alpha field and requires enabling VolumeAttributesClass feature.", - Type: []string{"string"}, - Format: "", - }, - }, - "modifyVolumeStatus": { - SchemaProps: spec.SchemaProps{ - Description: "ModifyVolumeStatus represents the status object of ControllerModifyVolume operation. When this is unset, there is no ModifyVolume operation being attempted. This is an alpha field and requires enabling VolumeAttributesClass feature.", - Ref: ref("k8s.io/api/core/v1.ModifyVolumeStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ModifyVolumeStatus", "k8s.io/api/core/v1.PersistentVolumeClaimCondition", "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeClaimTemplate(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeClaimTemplate is used to produce PersistentVolumeClaim objects as part of an EphemeralVolumeSource.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "May contain labels and annotations that will be copied into the PVC when creating it. No other fields are allowed and will be rejected during validation.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "The specification for the PersistentVolumeClaim. The entire content is copied unchanged into the PVC that gets created from this template. The same fields as in a PersistentVolumeClaim are also valid here.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PersistentVolumeClaimSpec"), - }, - }, - }, - Required: []string{"spec"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PersistentVolumeClaimSpec", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeClaimVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeClaimVolumeSource references the user's PVC in the same namespace. This volume finds the bound PV and mounts that volume for the pod. A PersistentVolumeClaimVolumeSource is, essentially, a wrapper around another type of volume that is owned by someone else (the system).", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "claimName": { - SchemaProps: spec.SchemaProps{ - Description: "claimName is the name of a PersistentVolumeClaim in the same namespace as the pod using this volume. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly Will force the ReadOnly setting in VolumeMounts. Default false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"claimName"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeList is a list of PersistentVolume items.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "items is a list of persistent volumes. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PersistentVolume"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PersistentVolume", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeSource is similar to VolumeSource but meant for the administrator who creates PVs. Exactly one of its members must be set.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "gcePersistentDisk": { - SchemaProps: spec.SchemaProps{ - Description: "gcePersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", - Ref: ref("k8s.io/api/core/v1.GCEPersistentDiskVolumeSource"), - }, - }, - "awsElasticBlockStore": { - SchemaProps: spec.SchemaProps{ - Description: "awsElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore", - Ref: ref("k8s.io/api/core/v1.AWSElasticBlockStoreVolumeSource"), - }, - }, - "hostPath": { - SchemaProps: spec.SchemaProps{ - Description: "hostPath represents a directory on the host. Provisioned by a developer or tester. This is useful for single-node development and testing only! On-host storage is not supported in any way and WILL NOT WORK in a multi-node cluster. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath", - Ref: ref("k8s.io/api/core/v1.HostPathVolumeSource"), - }, - }, - "glusterfs": { - SchemaProps: spec.SchemaProps{ - Description: "glusterfs represents a Glusterfs volume that is attached to a host and exposed to the pod. Provisioned by an admin. More info: https://examples.k8s.io/volumes/glusterfs/README.md", - Ref: ref("k8s.io/api/core/v1.GlusterfsPersistentVolumeSource"), - }, - }, - "nfs": { - SchemaProps: spec.SchemaProps{ - Description: "nfs represents an NFS mount on the host. Provisioned by an admin. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs", - Ref: ref("k8s.io/api/core/v1.NFSVolumeSource"), - }, - }, - "rbd": { - SchemaProps: spec.SchemaProps{ - Description: "rbd represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/rbd/README.md", - Ref: ref("k8s.io/api/core/v1.RBDPersistentVolumeSource"), - }, - }, - "iscsi": { - SchemaProps: spec.SchemaProps{ - Description: "iscsi represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin.", - Ref: ref("k8s.io/api/core/v1.ISCSIPersistentVolumeSource"), - }, - }, - "cinder": { - SchemaProps: spec.SchemaProps{ - Description: "cinder represents a cinder volume attached and mounted on kubelets host machine. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - Ref: ref("k8s.io/api/core/v1.CinderPersistentVolumeSource"), - }, - }, - "cephfs": { - SchemaProps: spec.SchemaProps{ - Description: "cephFS represents a Ceph FS mount on the host that shares a pod's lifetime", - Ref: ref("k8s.io/api/core/v1.CephFSPersistentVolumeSource"), - }, - }, - "fc": { - SchemaProps: spec.SchemaProps{ - Description: "fc represents a Fibre Channel resource that is attached to a kubelet's host machine and then exposed to the pod.", - Ref: ref("k8s.io/api/core/v1.FCVolumeSource"), - }, - }, - "flocker": { - SchemaProps: spec.SchemaProps{ - Description: "flocker represents a Flocker volume attached to a kubelet's host machine and exposed to the pod for its usage. This depends on the Flocker control service being running", - Ref: ref("k8s.io/api/core/v1.FlockerVolumeSource"), - }, - }, - "flexVolume": { - SchemaProps: spec.SchemaProps{ - Description: "flexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin.", - Ref: ref("k8s.io/api/core/v1.FlexPersistentVolumeSource"), - }, - }, - "azureFile": { - SchemaProps: spec.SchemaProps{ - Description: "azureFile represents an Azure File Service mount on the host and bind mount to the pod.", - Ref: ref("k8s.io/api/core/v1.AzureFilePersistentVolumeSource"), - }, - }, - "vsphereVolume": { - SchemaProps: spec.SchemaProps{ - Description: "vsphereVolume represents a vSphere volume attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.VsphereVirtualDiskVolumeSource"), - }, - }, - "quobyte": { - SchemaProps: spec.SchemaProps{ - Description: "quobyte represents a Quobyte mount on the host that shares a pod's lifetime", - Ref: ref("k8s.io/api/core/v1.QuobyteVolumeSource"), - }, - }, - "azureDisk": { - SchemaProps: spec.SchemaProps{ - Description: "azureDisk represents an Azure Data Disk mount on the host and bind mount to the pod.", - Ref: ref("k8s.io/api/core/v1.AzureDiskVolumeSource"), - }, - }, - "photonPersistentDisk": { - SchemaProps: spec.SchemaProps{ - Description: "photonPersistentDisk represents a PhotonController persistent disk attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.PhotonPersistentDiskVolumeSource"), - }, - }, - "portworxVolume": { - SchemaProps: spec.SchemaProps{ - Description: "portworxVolume represents a portworx volume attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.PortworxVolumeSource"), - }, - }, - "scaleIO": { - SchemaProps: spec.SchemaProps{ - Description: "scaleIO represents a ScaleIO persistent volume attached and mounted on Kubernetes nodes.", - Ref: ref("k8s.io/api/core/v1.ScaleIOPersistentVolumeSource"), - }, - }, - "local": { - SchemaProps: spec.SchemaProps{ - Description: "local represents directly-attached storage with node affinity", - Ref: ref("k8s.io/api/core/v1.LocalVolumeSource"), - }, - }, - "storageos": { - SchemaProps: spec.SchemaProps{ - Description: "storageOS represents a StorageOS volume that is attached to the kubelet's host machine and mounted into the pod More info: https://examples.k8s.io/volumes/storageos/README.md", - Ref: ref("k8s.io/api/core/v1.StorageOSPersistentVolumeSource"), - }, - }, - "csi": { - SchemaProps: spec.SchemaProps{ - Description: "csi represents storage that is handled by an external CSI driver (Beta feature).", - Ref: ref("k8s.io/api/core/v1.CSIPersistentVolumeSource"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.AWSElasticBlockStoreVolumeSource", "k8s.io/api/core/v1.AzureDiskVolumeSource", "k8s.io/api/core/v1.AzureFilePersistentVolumeSource", "k8s.io/api/core/v1.CSIPersistentVolumeSource", "k8s.io/api/core/v1.CephFSPersistentVolumeSource", "k8s.io/api/core/v1.CinderPersistentVolumeSource", "k8s.io/api/core/v1.FCVolumeSource", "k8s.io/api/core/v1.FlexPersistentVolumeSource", "k8s.io/api/core/v1.FlockerVolumeSource", "k8s.io/api/core/v1.GCEPersistentDiskVolumeSource", "k8s.io/api/core/v1.GlusterfsPersistentVolumeSource", "k8s.io/api/core/v1.HostPathVolumeSource", "k8s.io/api/core/v1.ISCSIPersistentVolumeSource", "k8s.io/api/core/v1.LocalVolumeSource", "k8s.io/api/core/v1.NFSVolumeSource", "k8s.io/api/core/v1.PhotonPersistentDiskVolumeSource", "k8s.io/api/core/v1.PortworxVolumeSource", "k8s.io/api/core/v1.QuobyteVolumeSource", "k8s.io/api/core/v1.RBDPersistentVolumeSource", "k8s.io/api/core/v1.ScaleIOPersistentVolumeSource", "k8s.io/api/core/v1.StorageOSPersistentVolumeSource", "k8s.io/api/core/v1.VsphereVirtualDiskVolumeSource"}, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeSpec is the specification of a persistent volume.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "capacity": { - SchemaProps: spec.SchemaProps{ - Description: "capacity is the description of the persistent volume's resources and capacity. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#capacity", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "gcePersistentDisk": { - SchemaProps: spec.SchemaProps{ - Description: "gcePersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", - Ref: ref("k8s.io/api/core/v1.GCEPersistentDiskVolumeSource"), - }, - }, - "awsElasticBlockStore": { - SchemaProps: spec.SchemaProps{ - Description: "awsElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore", - Ref: ref("k8s.io/api/core/v1.AWSElasticBlockStoreVolumeSource"), - }, - }, - "hostPath": { - SchemaProps: spec.SchemaProps{ - Description: "hostPath represents a directory on the host. Provisioned by a developer or tester. This is useful for single-node development and testing only! On-host storage is not supported in any way and WILL NOT WORK in a multi-node cluster. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath", - Ref: ref("k8s.io/api/core/v1.HostPathVolumeSource"), - }, - }, - "glusterfs": { - SchemaProps: spec.SchemaProps{ - Description: "glusterfs represents a Glusterfs volume that is attached to a host and exposed to the pod. Provisioned by an admin. More info: https://examples.k8s.io/volumes/glusterfs/README.md", - Ref: ref("k8s.io/api/core/v1.GlusterfsPersistentVolumeSource"), - }, - }, - "nfs": { - SchemaProps: spec.SchemaProps{ - Description: "nfs represents an NFS mount on the host. Provisioned by an admin. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs", - Ref: ref("k8s.io/api/core/v1.NFSVolumeSource"), - }, - }, - "rbd": { - SchemaProps: spec.SchemaProps{ - Description: "rbd represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/rbd/README.md", - Ref: ref("k8s.io/api/core/v1.RBDPersistentVolumeSource"), - }, - }, - "iscsi": { - SchemaProps: spec.SchemaProps{ - Description: "iscsi represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin.", - Ref: ref("k8s.io/api/core/v1.ISCSIPersistentVolumeSource"), - }, - }, - "cinder": { - SchemaProps: spec.SchemaProps{ - Description: "cinder represents a cinder volume attached and mounted on kubelets host machine. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - Ref: ref("k8s.io/api/core/v1.CinderPersistentVolumeSource"), - }, - }, - "cephfs": { - SchemaProps: spec.SchemaProps{ - Description: "cephFS represents a Ceph FS mount on the host that shares a pod's lifetime", - Ref: ref("k8s.io/api/core/v1.CephFSPersistentVolumeSource"), - }, - }, - "fc": { - SchemaProps: spec.SchemaProps{ - Description: "fc represents a Fibre Channel resource that is attached to a kubelet's host machine and then exposed to the pod.", - Ref: ref("k8s.io/api/core/v1.FCVolumeSource"), - }, - }, - "flocker": { - SchemaProps: spec.SchemaProps{ - Description: "flocker represents a Flocker volume attached to a kubelet's host machine and exposed to the pod for its usage. This depends on the Flocker control service being running", - Ref: ref("k8s.io/api/core/v1.FlockerVolumeSource"), - }, - }, - "flexVolume": { - SchemaProps: spec.SchemaProps{ - Description: "flexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin.", - Ref: ref("k8s.io/api/core/v1.FlexPersistentVolumeSource"), - }, - }, - "azureFile": { - SchemaProps: spec.SchemaProps{ - Description: "azureFile represents an Azure File Service mount on the host and bind mount to the pod.", - Ref: ref("k8s.io/api/core/v1.AzureFilePersistentVolumeSource"), - }, - }, - "vsphereVolume": { - SchemaProps: spec.SchemaProps{ - Description: "vsphereVolume represents a vSphere volume attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.VsphereVirtualDiskVolumeSource"), - }, - }, - "quobyte": { - SchemaProps: spec.SchemaProps{ - Description: "quobyte represents a Quobyte mount on the host that shares a pod's lifetime", - Ref: ref("k8s.io/api/core/v1.QuobyteVolumeSource"), - }, - }, - "azureDisk": { - SchemaProps: spec.SchemaProps{ - Description: "azureDisk represents an Azure Data Disk mount on the host and bind mount to the pod.", - Ref: ref("k8s.io/api/core/v1.AzureDiskVolumeSource"), - }, - }, - "photonPersistentDisk": { - SchemaProps: spec.SchemaProps{ - Description: "photonPersistentDisk represents a PhotonController persistent disk attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.PhotonPersistentDiskVolumeSource"), - }, - }, - "portworxVolume": { - SchemaProps: spec.SchemaProps{ - Description: "portworxVolume represents a portworx volume attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.PortworxVolumeSource"), - }, - }, - "scaleIO": { - SchemaProps: spec.SchemaProps{ - Description: "scaleIO represents a ScaleIO persistent volume attached and mounted on Kubernetes nodes.", - Ref: ref("k8s.io/api/core/v1.ScaleIOPersistentVolumeSource"), - }, - }, - "local": { - SchemaProps: spec.SchemaProps{ - Description: "local represents directly-attached storage with node affinity", - Ref: ref("k8s.io/api/core/v1.LocalVolumeSource"), - }, - }, - "storageos": { - SchemaProps: spec.SchemaProps{ - Description: "storageOS represents a StorageOS volume that is attached to the kubelet's host machine and mounted into the pod More info: https://examples.k8s.io/volumes/storageos/README.md", - Ref: ref("k8s.io/api/core/v1.StorageOSPersistentVolumeSource"), - }, - }, - "csi": { - SchemaProps: spec.SchemaProps{ - Description: "csi represents storage that is handled by an external CSI driver (Beta feature).", - Ref: ref("k8s.io/api/core/v1.CSIPersistentVolumeSource"), - }, - }, - "accessModes": { - SchemaProps: spec.SchemaProps{ - Description: "accessModes contains all ways the volume can be mounted. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#access-modes", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "claimRef": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "granular", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "claimRef is part of a bi-directional binding between PersistentVolume and PersistentVolumeClaim. Expected to be non-nil when bound. claim.VolumeName is the authoritative bind between PV and PVC. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#binding", - Ref: ref("k8s.io/api/core/v1.ObjectReference"), - }, - }, - "persistentVolumeReclaimPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "persistentVolumeReclaimPolicy defines what happens to a persistent volume when released from its claim. Valid options are Retain (default for manually created PersistentVolumes), Delete (default for dynamically provisioned PersistentVolumes), and Recycle (deprecated). Recycle must be supported by the volume plugin underlying this PersistentVolume. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#reclaiming\n\nPossible enum values:\n - `\"Delete\"` means the volume will be deleted from Kubernetes on release from its claim. The volume plugin must support Deletion.\n - `\"Recycle\"` means the volume will be recycled back into the pool of unbound persistent volumes on release from its claim. The volume plugin must support Recycling.\n - `\"Retain\"` means the volume will be left in its current phase (Released) for manual reclamation by the administrator. The default policy is Retain.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Delete", "Recycle", "Retain"}, - }, - }, - "storageClassName": { - SchemaProps: spec.SchemaProps{ - Description: "storageClassName is the name of StorageClass to which this persistent volume belongs. Empty value means that this volume does not belong to any StorageClass.", - Type: []string{"string"}, - Format: "", - }, - }, - "mountOptions": { - SchemaProps: spec.SchemaProps{ - Description: "mountOptions is the list of mount options, e.g. [\"ro\", \"soft\"]. Not validated - mount will simply fail if one is invalid. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes/#mount-options", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "volumeMode": { - SchemaProps: spec.SchemaProps{ - Description: "volumeMode defines if a volume is intended to be used with a formatted filesystem or to remain in raw block state. Value of Filesystem is implied when not included in spec.\n\nPossible enum values:\n - `\"Block\"` means the volume will not be formatted with a filesystem and will remain a raw block device.\n - `\"Filesystem\"` means the volume will be or is formatted with a filesystem.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Block", "Filesystem"}, - }, - }, - "nodeAffinity": { - SchemaProps: spec.SchemaProps{ - Description: "nodeAffinity defines constraints that limit what nodes this volume can be accessed from. This field influences the scheduling of pods that use this volume.", - Ref: ref("k8s.io/api/core/v1.VolumeNodeAffinity"), - }, - }, - "volumeAttributesClassName": { - SchemaProps: spec.SchemaProps{ - Description: "Name of VolumeAttributesClass to which this persistent volume belongs. Empty value is not allowed. When this field is not set, it indicates that this volume does not belong to any VolumeAttributesClass. This field is mutable and can be changed by the CSI driver after a volume has been updated successfully to a new class. For an unbound PersistentVolume, the volumeAttributesClassName will be matched with unbound PersistentVolumeClaims during the binding process. This is an alpha field and requires enabling VolumeAttributesClass feature.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.AWSElasticBlockStoreVolumeSource", "k8s.io/api/core/v1.AzureDiskVolumeSource", "k8s.io/api/core/v1.AzureFilePersistentVolumeSource", "k8s.io/api/core/v1.CSIPersistentVolumeSource", "k8s.io/api/core/v1.CephFSPersistentVolumeSource", "k8s.io/api/core/v1.CinderPersistentVolumeSource", "k8s.io/api/core/v1.FCVolumeSource", "k8s.io/api/core/v1.FlexPersistentVolumeSource", "k8s.io/api/core/v1.FlockerVolumeSource", "k8s.io/api/core/v1.GCEPersistentDiskVolumeSource", "k8s.io/api/core/v1.GlusterfsPersistentVolumeSource", "k8s.io/api/core/v1.HostPathVolumeSource", "k8s.io/api/core/v1.ISCSIPersistentVolumeSource", "k8s.io/api/core/v1.LocalVolumeSource", "k8s.io/api/core/v1.NFSVolumeSource", "k8s.io/api/core/v1.ObjectReference", "k8s.io/api/core/v1.PhotonPersistentDiskVolumeSource", "k8s.io/api/core/v1.PortworxVolumeSource", "k8s.io/api/core/v1.QuobyteVolumeSource", "k8s.io/api/core/v1.RBDPersistentVolumeSource", "k8s.io/api/core/v1.ScaleIOPersistentVolumeSource", "k8s.io/api/core/v1.StorageOSPersistentVolumeSource", "k8s.io/api/core/v1.VolumeNodeAffinity", "k8s.io/api/core/v1.VsphereVirtualDiskVolumeSource", "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeStatus is the current status of a persistent volume.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "phase": { - SchemaProps: spec.SchemaProps{ - Description: "phase indicates if a volume is available, bound to a claim, or released by a claim. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#phase\n\nPossible enum values:\n - `\"Available\"` used for PersistentVolumes that are not yet bound Available volumes are held by the binder and matched to PersistentVolumeClaims\n - `\"Bound\"` used for PersistentVolumes that are bound\n - `\"Failed\"` used for PersistentVolumes that failed to be correctly recycled or deleted after being released from a claim\n - `\"Pending\"` used for PersistentVolumes that are not available\n - `\"Released\"` used for PersistentVolumes where the bound PersistentVolumeClaim was deleted released volumes must be recycled before becoming available again this phase is used by the persistent volume claim binder to signal to another process to reclaim the resource", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Available", "Bound", "Failed", "Pending", "Released"}, - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "message is a human-readable message indicating details about why the volume is in this state.", - Type: []string{"string"}, - Format: "", - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "reason is a brief CamelCase string that describes any failure and is meant for machine parsing and tidy display in the CLI.", - Type: []string{"string"}, - Format: "", - }, - }, - "lastPhaseTransitionTime": { - SchemaProps: spec.SchemaProps{ - Description: "lastPhaseTransitionTime is the time the phase transitioned from one to another and automatically resets to current time everytime a volume phase transitions. This is an alpha field and requires enabling PersistentVolumeLastPhaseTransitionTime feature.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_PhotonPersistentDiskVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Photon Controller persistent disk resource.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "pdID": { - SchemaProps: spec.SchemaProps{ - Description: "pdID is the ID that identifies Photon Controller persistent disk", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"pdID"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_Pod(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Pod is a collection of containers that can run on a host. This resource is created by clients and scheduled onto hosts.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Specification of the desired behavior of the pod. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Most recently observed status of the pod. This data may not be up to date. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodSpec", "k8s.io/api/core/v1.PodStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_PodAffinity(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Pod affinity is a group of inter pod affinity scheduling rules.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "requiredDuringSchedulingIgnoredDuringExecution": { - SchemaProps: spec.SchemaProps{ - Description: "If the affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to a pod label update), the system may or may not try to eventually evict the pod from its node. When there are multiple elements, the lists of nodes corresponding to each podAffinityTerm are intersected, i.e. all terms must be satisfied.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodAffinityTerm"), - }, - }, - }, - }, - }, - "preferredDuringSchedulingIgnoredDuringExecution": { - SchemaProps: spec.SchemaProps{ - Description: "The scheduler will prefer to schedule pods to nodes that satisfy the affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding \"weight\" to the sum if the node has pods which matches the corresponding podAffinityTerm; the node(s) with the highest sum are the most preferred.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.WeightedPodAffinityTerm"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodAffinityTerm", "k8s.io/api/core/v1.WeightedPodAffinityTerm"}, - } -} - -func schema_k8sio_api_core_v1_PodAffinityTerm(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Defines a set of pods (namely those matching the labelSelector relative to the given namespace(s)) that this pod should be co-located (affinity) or not co-located (anti-affinity) with, where co-located is defined as running on a node whose value of the label with key matches that of any node on which a pod of the set of pods is running", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "labelSelector": { - SchemaProps: spec.SchemaProps{ - Description: "A label query over a set of resources, in this case pods. If it's null, this PodAffinityTerm matches with no Pods.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), - }, - }, - "namespaces": { - SchemaProps: spec.SchemaProps{ - Description: "namespaces specifies a static list of namespace names that the term applies to. The term is applied to the union of the namespaces listed in this field and the ones selected by namespaceSelector. null or empty namespaces list and null namespaceSelector means \"this pod's namespace\".", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "topologyKey": { - SchemaProps: spec.SchemaProps{ - Description: "This pod should be co-located (affinity) or not co-located (anti-affinity) with the pods matching the labelSelector in the specified namespaces, where co-located is defined as running on a node whose value of the label with key topologyKey matches that of any node on which any of the selected pods is running. Empty topologyKey is not allowed.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "namespaceSelector": { - SchemaProps: spec.SchemaProps{ - Description: "A label query over the set of namespaces that the term applies to. The term is applied to the union of the namespaces selected by this field and the ones listed in the namespaces field. null selector and null or empty namespaces list means \"this pod's namespace\". An empty selector ({}) matches all namespaces.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), - }, - }, - "matchLabelKeys": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "MatchLabelKeys is a set of pod label keys to select which pods will be taken into consideration. The keys are used to lookup values from the incoming pod labels, those key-value labels are merged with `LabelSelector` as `key in (value)` to select the group of existing pods which pods will be taken into consideration for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming pod labels will be ignored. The default value is empty. The same key is forbidden to exist in both MatchLabelKeys and LabelSelector. Also, MatchLabelKeys cannot be set when LabelSelector isn't set. This is an alpha field and requires enabling MatchLabelKeysInPodAffinity feature gate.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "mismatchLabelKeys": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "MismatchLabelKeys is a set of pod label keys to select which pods will be taken into consideration. The keys are used to lookup values from the incoming pod labels, those key-value labels are merged with `LabelSelector` as `key notin (value)` to select the group of existing pods which pods will be taken into consideration for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming pod labels will be ignored. The default value is empty. The same key is forbidden to exist in both MismatchLabelKeys and LabelSelector. Also, MismatchLabelKeys cannot be set when LabelSelector isn't set. This is an alpha field and requires enabling MatchLabelKeysInPodAffinity feature gate.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"topologyKey"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"}, - } -} - -func schema_k8sio_api_core_v1_PodAntiAffinity(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Pod anti affinity is a group of inter pod anti affinity scheduling rules.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "requiredDuringSchedulingIgnoredDuringExecution": { - SchemaProps: spec.SchemaProps{ - Description: "If the anti-affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the anti-affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to a pod label update), the system may or may not try to eventually evict the pod from its node. When there are multiple elements, the lists of nodes corresponding to each podAffinityTerm are intersected, i.e. all terms must be satisfied.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodAffinityTerm"), - }, - }, - }, - }, - }, - "preferredDuringSchedulingIgnoredDuringExecution": { - SchemaProps: spec.SchemaProps{ - Description: "The scheduler will prefer to schedule pods to nodes that satisfy the anti-affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling anti-affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding \"weight\" to the sum if the node has pods which matches the corresponding podAffinityTerm; the node(s) with the highest sum are the most preferred.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.WeightedPodAffinityTerm"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodAffinityTerm", "k8s.io/api/core/v1.WeightedPodAffinityTerm"}, - } -} - -func schema_k8sio_api_core_v1_PodAttachOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodAttachOptions is the query options to a Pod's remote attach call.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "stdin": { - SchemaProps: spec.SchemaProps{ - Description: "Stdin if true, redirects the standard input stream of the pod for this call. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "stdout": { - SchemaProps: spec.SchemaProps{ - Description: "Stdout if true indicates that stdout is to be redirected for the attach call. Defaults to true.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "stderr": { - SchemaProps: spec.SchemaProps{ - Description: "Stderr if true indicates that stderr is to be redirected for the attach call. Defaults to true.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "tty": { - SchemaProps: spec.SchemaProps{ - Description: "TTY if true indicates that a tty will be allocated for the attach call. This is passed through the container runtime so the tty is allocated on the worker node by the container runtime. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "container": { - SchemaProps: spec.SchemaProps{ - Description: "The container in which to execute the command. Defaults to only container if there is only one container in the pod.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PodCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodCondition contains details for the current condition of this pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type is the type of the condition. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-conditions", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status is the status of the condition. Can be True, False, Unknown. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-conditions", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "lastProbeTime": { - SchemaProps: spec.SchemaProps{ - Description: "Last time we probed the condition.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "lastTransitionTime": { - SchemaProps: spec.SchemaProps{ - Description: "Last time the condition transitioned from one status to another.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "Unique, one-word, CamelCase reason for the condition's last transition.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "Human-readable message indicating details about last transition.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_PodDNSConfig(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodDNSConfig defines the DNS parameters of a pod in addition to those generated from DNSPolicy.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "nameservers": { - SchemaProps: spec.SchemaProps{ - Description: "A list of DNS name server IP addresses. This will be appended to the base nameservers generated from DNSPolicy. Duplicated nameservers will be removed.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "searches": { - SchemaProps: spec.SchemaProps{ - Description: "A list of DNS search domains for host-name lookup. This will be appended to the base search paths generated from DNSPolicy. Duplicated search paths will be removed.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "options": { - SchemaProps: spec.SchemaProps{ - Description: "A list of DNS resolver options. This will be merged with the base options generated from DNSPolicy. Duplicated entries will be removed. Resolution options given in Options will override those that appear in the base DNSPolicy.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodDNSConfigOption"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodDNSConfigOption"}, - } -} - -func schema_k8sio_api_core_v1_PodDNSConfigOption(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodDNSConfigOption defines DNS resolver options of a pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Required.", - Type: []string{"string"}, - Format: "", - }, - }, - "value": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PodExecOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodExecOptions is the query options to a Pod's remote exec call.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "stdin": { - SchemaProps: spec.SchemaProps{ - Description: "Redirect the standard input stream of the pod for this call. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "stdout": { - SchemaProps: spec.SchemaProps{ - Description: "Redirect the standard output stream of the pod for this call.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "stderr": { - SchemaProps: spec.SchemaProps{ - Description: "Redirect the standard error stream of the pod for this call.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "tty": { - SchemaProps: spec.SchemaProps{ - Description: "TTY if true indicates that a tty will be allocated for the exec call. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "container": { - SchemaProps: spec.SchemaProps{ - Description: "Container in which to execute the command. Defaults to only container if there is only one container in the pod.", - Type: []string{"string"}, - Format: "", - }, - }, - "command": { - SchemaProps: spec.SchemaProps{ - Description: "Command is the remote command to execute. argv array. Not executed within a shell.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"command"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PodIP(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodIP represents a single IP address allocated to the pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "ip": { - SchemaProps: spec.SchemaProps{ - Description: "IP is the IP address assigned to the pod", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PodList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodList is a list of Pods.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of pods. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Pod"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.Pod", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_PodLogOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodLogOptions is the query options for a Pod's logs REST call.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "container": { - SchemaProps: spec.SchemaProps{ - Description: "The container for which to stream logs. Defaults to only container if there is one container in the pod.", - Type: []string{"string"}, - Format: "", - }, - }, - "follow": { - SchemaProps: spec.SchemaProps{ - Description: "Follow the log stream of the pod. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "previous": { - SchemaProps: spec.SchemaProps{ - Description: "Return previous terminated container logs. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "sinceSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "A relative time in seconds before the current time from which to show logs. If this value precedes the time a pod was started, only logs since the pod start will be returned. If this value is in the future, no logs will be returned. Only one of sinceSeconds or sinceTime may be specified.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "sinceTime": { - SchemaProps: spec.SchemaProps{ - Description: "An RFC3339 timestamp from which to show logs. If this value precedes the time a pod was started, only logs since the pod start will be returned. If this value is in the future, no logs will be returned. Only one of sinceSeconds or sinceTime may be specified.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "timestamps": { - SchemaProps: spec.SchemaProps{ - Description: "If true, add an RFC3339 or RFC3339Nano timestamp at the beginning of every line of log output. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "tailLines": { - SchemaProps: spec.SchemaProps{ - Description: "If set, the number of lines from the end of the logs to show. If not specified, logs are shown from the creation of the container or sinceSeconds or sinceTime", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "limitBytes": { - SchemaProps: spec.SchemaProps{ - Description: "If set, the number of bytes to read from the server before terminating the log output. This may not display a complete final line of logging, and may return slightly more or slightly less than the specified limit.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "insecureSkipTLSVerifyBackend": { - SchemaProps: spec.SchemaProps{ - Description: "insecureSkipTLSVerifyBackend indicates that the apiserver should not confirm the validity of the serving certificate of the backend it is connecting to. This will make the HTTPS connection between the apiserver and the backend insecure. This means the apiserver cannot verify the log data it is receiving came from the real kubelet. If the kubelet is configured to verify the apiserver's TLS credentials, it does not mean the connection to the real kubelet is vulnerable to a man in the middle attack (e.g. an attacker could not intercept the actual log data coming from the real kubelet).", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_PodOS(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodOS defines the OS parameters of a pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name is the name of the operating system. The currently supported values are linux and windows. Additional value may be defined in future and can be one of: https://github.com/opencontainers/runtime-spec/blob/master/config.md#platform-specific-configuration Clients should expect to handle additional values and treat unrecognized values in this field as os: null", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PodPortForwardOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodPortForwardOptions is the query options to a Pod's port forward call when using WebSockets. The `port` query parameter must specify the port or ports (comma separated) to forward over. Port forwarding over SPDY does not use these options. It requires the port to be passed in the `port` header as part of request.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "ports": { - SchemaProps: spec.SchemaProps{ - Description: "List of ports to forward Required when using WebSockets", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PodProxyOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodProxyOptions is the query options to a Pod's proxy call.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "Path is the URL path to use for the current proxy request to pod.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PodReadinessGate(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodReadinessGate contains the reference to a pod condition", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "conditionType": { - SchemaProps: spec.SchemaProps{ - Description: "ConditionType refers to a condition in the pod's condition list with matching type.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"conditionType"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PodResourceClaim(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodResourceClaim references exactly one ResourceClaim through a ClaimSource. It adds a name to it that uniquely identifies the ResourceClaim inside the Pod. Containers that need access to the ResourceClaim reference it with this name.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name uniquely identifies this resource claim inside the pod. This must be a DNS_LABEL.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "source": { - SchemaProps: spec.SchemaProps{ - Description: "Source describes where to find the ResourceClaim.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ClaimSource"), - }, - }, - }, - Required: []string{"name"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ClaimSource"}, - } -} - -func schema_k8sio_api_core_v1_PodResourceClaimStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodResourceClaimStatus is stored in the PodStatus for each PodResourceClaim which references a ResourceClaimTemplate. It stores the generated name for the corresponding ResourceClaim.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name uniquely identifies this resource claim inside the pod. This must match the name of an entry in pod.spec.resourceClaims, which implies that the string must be a DNS_LABEL.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "resourceClaimName": { - SchemaProps: spec.SchemaProps{ - Description: "ResourceClaimName is the name of the ResourceClaim that was generated for the Pod in the namespace of the Pod. It this is unset, then generating a ResourceClaim was not necessary. The pod.spec.resourceClaims entry can be ignored in this case.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PodSchedulingGate(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodSchedulingGate is associated to a Pod to guard its scheduling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the scheduling gate. Each scheduling gate must have a unique name field.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PodSecurityContext(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodSecurityContext holds pod-level security attributes and common container settings. Some fields are also present in container.securityContext. Field values of container.securityContext take precedence over field values of PodSecurityContext.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "seLinuxOptions": { - SchemaProps: spec.SchemaProps{ - Description: "The SELinux context to be applied to all containers. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container. Note that this field cannot be set when spec.os.name is windows.", - Ref: ref("k8s.io/api/core/v1.SELinuxOptions"), - }, - }, - "windowsOptions": { - SchemaProps: spec.SchemaProps{ - Description: "The Windows specific settings applied to all containers. If unspecified, the options within a container's SecurityContext will be used. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. Note that this field cannot be set when spec.os.name is linux.", - Ref: ref("k8s.io/api/core/v1.WindowsSecurityContextOptions"), - }, - }, - "runAsUser": { - SchemaProps: spec.SchemaProps{ - Description: "The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container. Note that this field cannot be set when spec.os.name is windows.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "runAsGroup": { - SchemaProps: spec.SchemaProps{ - Description: "The GID to run the entrypoint of the container process. Uses runtime default if unset. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container. Note that this field cannot be set when spec.os.name is windows.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "runAsNonRoot": { - SchemaProps: spec.SchemaProps{ - Description: "Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. If unset or false, no such validation will be performed. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "supplementalGroups": { - SchemaProps: spec.SchemaProps{ - Description: "A list of groups applied to the first process run in each container, in addition to the container's primary GID, the fsGroup (if specified), and group memberships defined in the container image for the uid of the container process. If unspecified, no additional groups are added to any container. Note that group memberships defined in the container image for the uid of the container process are still effective, even if they are not included in this list. Note that this field cannot be set when spec.os.name is windows.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: 0, - Type: []string{"integer"}, - Format: "int64", - }, - }, - }, - }, - }, - "fsGroup": { - SchemaProps: spec.SchemaProps{ - Description: "A special supplemental group that applies to all containers in a pod. Some volume types allow the Kubelet to change the ownership of that volume to be owned by the pod:\n\n1. The owning GID will be the FSGroup 2. The setgid bit is set (new files created in the volume will be owned by FSGroup) 3. The permission bits are OR'd with rw-rw----\n\nIf unset, the Kubelet will not modify the ownership and permissions of any volume. Note that this field cannot be set when spec.os.name is windows.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "sysctls": { - SchemaProps: spec.SchemaProps{ - Description: "Sysctls hold a list of namespaced sysctls used for the pod. Pods with unsupported sysctls (by the container runtime) might fail to launch. Note that this field cannot be set when spec.os.name is windows.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Sysctl"), - }, - }, - }, - }, - }, - "fsGroupChangePolicy": { - SchemaProps: spec.SchemaProps{ - Description: "fsGroupChangePolicy defines behavior of changing ownership and permission of the volume before being exposed inside Pod. This field will only apply to volume types which support fsGroup based ownership(and permissions). It will have no effect on ephemeral volume types such as: secret, configmaps and emptydir. Valid values are \"OnRootMismatch\" and \"Always\". If not specified, \"Always\" is used. Note that this field cannot be set when spec.os.name is windows.\n\nPossible enum values:\n - `\"Always\"` indicates that volume's ownership and permissions should always be changed whenever volume is mounted inside a Pod. This the default behavior.\n - `\"OnRootMismatch\"` indicates that volume's ownership and permissions will be changed only when permission and ownership of root directory does not match with expected permissions on the volume. This can help shorten the time it takes to change ownership and permissions of a volume.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Always", "OnRootMismatch"}, - }, - }, - "seccompProfile": { - SchemaProps: spec.SchemaProps{ - Description: "The seccomp options to use by the containers in this pod. Note that this field cannot be set when spec.os.name is windows.", - Ref: ref("k8s.io/api/core/v1.SeccompProfile"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.SELinuxOptions", "k8s.io/api/core/v1.SeccompProfile", "k8s.io/api/core/v1.Sysctl", "k8s.io/api/core/v1.WindowsSecurityContextOptions"}, - } -} - -func schema_k8sio_api_core_v1_PodSignature(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Describes the class of pods that should avoid this node. Exactly one field should be set.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "podController": { - SchemaProps: spec.SchemaProps{ - Description: "Reference to controller whose pods should avoid this node.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.OwnerReference"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.OwnerReference"}, - } -} - -func schema_k8sio_api_core_v1_PodSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodSpec is a description of a pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "volumes": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge,retainKeys", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Volume"), - }, - }, - }, - }, - }, - "initContainers": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of initialization containers belonging to the pod. Init containers are executed in order prior to containers being started. If any init container fails, the pod is considered to have failed and is handled according to its restartPolicy. The name for an init container or normal container must be unique among all containers. Init containers may not have Lifecycle actions, Readiness probes, Liveness probes, or Startup probes. The resourceRequirements of an init container are taken into account during scheduling by finding the highest request/limit for each resource type, and then using the max of of that value or the sum of the normal containers. Limits are applied to init containers in a similar fashion. Init containers cannot currently be added or removed. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Container"), - }, - }, - }, - }, - }, - "containers": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of containers belonging to the pod. Containers cannot currently be added or removed. There must be at least one container in a Pod. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Container"), - }, - }, - }, - }, - }, - "ephemeralContainers": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of ephemeral containers run in this pod. Ephemeral containers may be run in an existing pod to perform user-initiated actions such as debugging. This list cannot be specified when creating a pod, and it cannot be modified by updating the pod spec. In order to add an ephemeral container to an existing pod, use the pod's ephemeralcontainers subresource.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EphemeralContainer"), - }, - }, - }, - }, - }, - "restartPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Restart policy for all containers within the pod. One of Always, OnFailure, Never. In some contexts, only a subset of those values may be permitted. Default to Always. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy\n\nPossible enum values:\n - `\"Always\"`\n - `\"Never\"`\n - `\"OnFailure\"`", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Always", "Never", "OnFailure"}, - }, - }, - "terminationGracePeriodSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Optional duration in seconds the pod needs to terminate gracefully. May be decreased in delete request. Value must be non-negative integer. The value zero indicates stop immediately via the kill signal (no opportunity to shut down). If this value is nil, the default grace period will be used instead. The grace period is the duration in seconds after the processes running in the pod are sent a termination signal and the time when the processes are forcibly halted with a kill signal. Set this value longer than the expected cleanup time for your process. Defaults to 30 seconds.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "activeDeadlineSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Optional duration in seconds the pod may be active on the node relative to StartTime before the system will actively try to mark it failed and kill associated containers. Value must be a positive integer.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "dnsPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Set DNS policy for the pod. Defaults to \"ClusterFirst\". Valid values are 'ClusterFirstWithHostNet', 'ClusterFirst', 'Default' or 'None'. DNS parameters given in DNSConfig will be merged with the policy selected with DNSPolicy. To have DNS options set along with hostNetwork, you have to specify DNS policy explicitly to 'ClusterFirstWithHostNet'.\n\nPossible enum values:\n - `\"ClusterFirst\"` indicates that the pod should use cluster DNS first unless hostNetwork is true, if it is available, then fall back on the default (as determined by kubelet) DNS settings.\n - `\"ClusterFirstWithHostNet\"` indicates that the pod should use cluster DNS first, if it is available, then fall back on the default (as determined by kubelet) DNS settings.\n - `\"Default\"` indicates that the pod should use the default (as determined by kubelet) DNS settings.\n - `\"None\"` indicates that the pod should use empty DNS settings. DNS parameters such as nameservers and search paths should be defined via DNSConfig.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"ClusterFirst", "ClusterFirstWithHostNet", "Default", "None"}, - }, - }, - "nodeSelector": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "NodeSelector is a selector which must be true for the pod to fit on a node. Selector which must match a node's labels for the pod to be scheduled on that node. More info: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "serviceAccountName": { - SchemaProps: spec.SchemaProps{ - Description: "ServiceAccountName is the name of the ServiceAccount to use to run this pod. More info: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/", - Type: []string{"string"}, - Format: "", - }, - }, - "serviceAccount": { - SchemaProps: spec.SchemaProps{ - Description: "DeprecatedServiceAccount is a depreciated alias for ServiceAccountName. Deprecated: Use serviceAccountName instead.", - Type: []string{"string"}, - Format: "", - }, - }, - "automountServiceAccountToken": { - SchemaProps: spec.SchemaProps{ - Description: "AutomountServiceAccountToken indicates whether a service account token should be automatically mounted.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "nodeName": { - SchemaProps: spec.SchemaProps{ - Description: "NodeName is a request to schedule this pod onto a specific node. If it is non-empty, the scheduler simply schedules this pod onto that node, assuming that it fits resource requirements.", - Type: []string{"string"}, - Format: "", - }, - }, - "hostNetwork": { - SchemaProps: spec.SchemaProps{ - Description: "Host networking requested for this pod. Use the host's network namespace. If this option is set, the ports that will be used must be specified. Default to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "hostPID": { - SchemaProps: spec.SchemaProps{ - Description: "Use the host's pid namespace. Optional: Default to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "hostIPC": { - SchemaProps: spec.SchemaProps{ - Description: "Use the host's ipc namespace. Optional: Default to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "shareProcessNamespace": { - SchemaProps: spec.SchemaProps{ - Description: "Share a single process namespace between all of the containers in a pod. When this is set containers will be able to view and signal processes from other containers in the same pod, and the first process in each container will not be assigned PID 1. HostPID and ShareProcessNamespace cannot both be set. Optional: Default to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "securityContext": { - SchemaProps: spec.SchemaProps{ - Description: "SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field.", - Ref: ref("k8s.io/api/core/v1.PodSecurityContext"), - }, - }, - "imagePullSecrets": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. If specified, these secrets will be passed to individual puller implementations for them to use. More info: https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - }, - }, - }, - "hostname": { - SchemaProps: spec.SchemaProps{ - Description: "Specifies the hostname of the Pod If not specified, the pod's hostname will be set to a system-defined value.", - Type: []string{"string"}, - Format: "", - }, - }, - "subdomain": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, the fully qualified Pod hostname will be \"...svc.\". If not specified, the pod will not have a domainname at all.", - Type: []string{"string"}, - Format: "", - }, - }, - "affinity": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, the pod's scheduling constraints", - Ref: ref("k8s.io/api/core/v1.Affinity"), - }, - }, - "schedulerName": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, the pod will be dispatched by specified scheduler. If not specified, the pod will be dispatched by default scheduler.", - Type: []string{"string"}, - Format: "", - }, - }, - "tolerations": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, the pod's tolerations.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Toleration"), - }, - }, - }, - }, - }, - "hostAliases": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "ip", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "HostAliases is an optional list of hosts and IPs that will be injected into the pod's hosts file if specified. This is only valid for non-hostNetwork pods.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.HostAlias"), - }, - }, - }, - }, - }, - "priorityClassName": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, indicates the pod's priority. \"system-node-critical\" and \"system-cluster-critical\" are two special keywords which indicate the highest priorities with the former being the highest priority. Any other name must be defined by creating a PriorityClass object with that name. If not specified, the pod priority will be default or zero if there is no default.", - Type: []string{"string"}, - Format: "", - }, - }, - "priority": { - SchemaProps: spec.SchemaProps{ - Description: "The priority value. Various system components use this field to find the priority of the pod. When Priority Admission Controller is enabled, it prevents users from setting this field. The admission controller populates this field from PriorityClassName. The higher the value, the higher the priority.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "dnsConfig": { - SchemaProps: spec.SchemaProps{ - Description: "Specifies the DNS parameters of a pod. Parameters specified here will be merged to the generated DNS configuration based on DNSPolicy.", - Ref: ref("k8s.io/api/core/v1.PodDNSConfig"), - }, - }, - "readinessGates": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, all readiness gates will be evaluated for pod readiness. A pod is ready when all its containers are ready AND all conditions specified in the readiness gates have status equal to \"True\" More info: https://git.k8s.io/enhancements/keps/sig-network/580-pod-readiness-gates", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodReadinessGate"), - }, - }, - }, - }, - }, - "runtimeClassName": { - SchemaProps: spec.SchemaProps{ - Description: "RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group, which should be used to run this pod. If no RuntimeClass resource matches the named class, the pod will not be run. If unset or empty, the \"legacy\" RuntimeClass will be used, which is an implicit class with an empty definition that uses the default runtime handler. More info: https://git.k8s.io/enhancements/keps/sig-node/585-runtime-class", - Type: []string{"string"}, - Format: "", - }, - }, - "enableServiceLinks": { - SchemaProps: spec.SchemaProps{ - Description: "EnableServiceLinks indicates whether information about services should be injected into pod's environment variables, matching the syntax of Docker links. Optional: Defaults to true.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "preemptionPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "PreemptionPolicy is the Policy for preempting pods with lower priority. One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset.\n\nPossible enum values:\n - `\"Never\"` means that pod never preempts other pods with lower priority.\n - `\"PreemptLowerPriority\"` means that pod can preempt other pods with lower priority.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Never", "PreemptLowerPriority"}, - }, - }, - "overhead": { - SchemaProps: spec.SchemaProps{ - Description: "Overhead represents the resource overhead associated with running a pod for a given RuntimeClass. This field will be autopopulated at admission time by the RuntimeClass admission controller. If the RuntimeClass admission controller is enabled, overhead must not be set in Pod create requests. The RuntimeClass admission controller will reject Pod create requests which have the overhead already set. If RuntimeClass is configured and selected in the PodSpec, Overhead will be set to the value defined in the corresponding RuntimeClass, otherwise it will remain unset and treated as zero. More info: https://git.k8s.io/enhancements/keps/sig-node/688-pod-overhead/README.md", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "topologySpreadConstraints": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "topologyKey", - "whenUnsatisfiable", - }, - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "topologyKey", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "TopologySpreadConstraints describes how a group of pods ought to spread across topology domains. Scheduler will schedule pods in a way which abides by the constraints. All topologySpreadConstraints are ANDed.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.TopologySpreadConstraint"), - }, - }, - }, - }, - }, - "setHostnameAsFQDN": { - SchemaProps: spec.SchemaProps{ - Description: "If true the pod's hostname will be configured as the pod's FQDN, rather than the leaf name (the default). In Linux containers, this means setting the FQDN in the hostname field of the kernel (the nodename field of struct utsname). In Windows containers, this means setting the registry value of hostname for the registry key HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters to FQDN. If a pod does not have FQDN, this has no effect. Default to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "os": { - SchemaProps: spec.SchemaProps{ - Description: "Specifies the OS of the containers in the pod. Some pod and container fields are restricted if this is set.\n\nIf the OS field is set to linux, the following fields must be unset: -securityContext.windowsOptions\n\nIf the OS field is set to windows, following fields must be unset: - spec.hostPID - spec.hostIPC - spec.hostUsers - spec.securityContext.seLinuxOptions - spec.securityContext.seccompProfile - spec.securityContext.fsGroup - spec.securityContext.fsGroupChangePolicy - spec.securityContext.sysctls - spec.shareProcessNamespace - spec.securityContext.runAsUser - spec.securityContext.runAsGroup - spec.securityContext.supplementalGroups - spec.containers[*].securityContext.seLinuxOptions - spec.containers[*].securityContext.seccompProfile - spec.containers[*].securityContext.capabilities - spec.containers[*].securityContext.readOnlyRootFilesystem - spec.containers[*].securityContext.privileged - spec.containers[*].securityContext.allowPrivilegeEscalation - spec.containers[*].securityContext.procMount - spec.containers[*].securityContext.runAsUser - spec.containers[*].securityContext.runAsGroup", - Ref: ref("k8s.io/api/core/v1.PodOS"), - }, - }, - "hostUsers": { - SchemaProps: spec.SchemaProps{ - Description: "Use the host's user namespace. Optional: Default to true. If set to true or not present, the pod will be run in the host user namespace, useful for when the pod needs a feature only available to the host user namespace, such as loading a kernel module with CAP_SYS_MODULE. When set to false, a new userns is created for the pod. Setting false is useful for mitigating container breakout vulnerabilities even allowing users to run their containers as root without actually having root privileges on the host. This field is alpha-level and is only honored by servers that enable the UserNamespacesSupport feature.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "schedulingGates": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "name", - }, - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "SchedulingGates is an opaque list of values that if specified will block scheduling the pod. If schedulingGates is not empty, the pod will stay in the SchedulingGated state and the scheduler will not attempt to schedule the pod.\n\nSchedulingGates can only be set at pod creation time, and be removed only afterwards.\n\nThis is a beta feature enabled by the PodSchedulingReadiness feature gate.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodSchedulingGate"), - }, - }, - }, - }, - }, - "resourceClaims": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "name", - }, - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge,retainKeys", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "ResourceClaims defines which ResourceClaims must be allocated and reserved before the Pod is allowed to start. The resources will be made available to those containers which consume them by name.\n\nThis is an alpha field and requires enabling the DynamicResourceAllocation feature gate.\n\nThis field is immutable.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodResourceClaim"), - }, - }, - }, - }, - }, - }, - Required: []string{"containers"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.Affinity", "k8s.io/api/core/v1.Container", "k8s.io/api/core/v1.EphemeralContainer", "k8s.io/api/core/v1.HostAlias", "k8s.io/api/core/v1.LocalObjectReference", "k8s.io/api/core/v1.PodDNSConfig", "k8s.io/api/core/v1.PodOS", "k8s.io/api/core/v1.PodReadinessGate", "k8s.io/api/core/v1.PodResourceClaim", "k8s.io/api/core/v1.PodSchedulingGate", "k8s.io/api/core/v1.PodSecurityContext", "k8s.io/api/core/v1.Toleration", "k8s.io/api/core/v1.TopologySpreadConstraint", "k8s.io/api/core/v1.Volume", "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_PodStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodStatus represents information about the status of a pod. Status may trail the actual state of a system, especially if the node that hosts the pod cannot contact the control plane.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "phase": { - SchemaProps: spec.SchemaProps{ - Description: "The phase of a Pod is a simple, high-level summary of where the Pod is in its lifecycle. The conditions array, the reason and message fields, and the individual container status arrays contain more detail about the pod's status. There are five possible phase values:\n\nPending: The pod has been accepted by the Kubernetes system, but one or more of the container images has not been created. This includes time before being scheduled as well as time spent downloading images over the network, which could take a while. Running: The pod has been bound to a node, and all of the containers have been created. At least one container is still running, or is in the process of starting or restarting. Succeeded: All containers in the pod have terminated in success, and will not be restarted. Failed: All containers in the pod have terminated, and at least one container has terminated in failure. The container either exited with non-zero status or was terminated by the system. Unknown: For some reason the state of the pod could not be obtained, typically due to an error in communicating with the host of the pod.\n\nMore info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-phase\n\nPossible enum values:\n - `\"Failed\"` means that all containers in the pod have terminated, and at least one container has terminated in a failure (exited with a non-zero exit code or was stopped by the system).\n - `\"Pending\"` means the pod has been accepted by the system, but one or more of the containers has not been started. This includes time before being bound to a node, as well as time spent pulling images onto the host.\n - `\"Running\"` means the pod has been bound to a node and all of the containers have been started. At least one container is still running or is in the process of being restarted.\n - `\"Succeeded\"` means that all containers in the pod have voluntarily terminated with a container exit code of 0, and the system is not going to restart any of these containers.\n - `\"Unknown\"` means that for some reason the state of the pod could not be obtained, typically due to an error in communicating with the host of the pod. Deprecated: It isn't being set since 2015 (74da3b14b0c0f658b3bb8d2def5094686d0e9095)", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Failed", "Pending", "Running", "Succeeded", "Unknown"}, - }, - }, - "conditions": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Current service state of pod. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-conditions", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodCondition"), - }, - }, - }, - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "A human readable message indicating details about why the pod is in this condition.", - Type: []string{"string"}, - Format: "", - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "A brief CamelCase message indicating details about why the pod is in this state. e.g. 'Evicted'", - Type: []string{"string"}, - Format: "", - }, - }, - "nominatedNodeName": { - SchemaProps: spec.SchemaProps{ - Description: "nominatedNodeName is set only when this pod preempts other pods on the node, but it cannot be scheduled right away as preemption victims receive their graceful termination periods. This field does not guarantee that the pod will be scheduled on this node. Scheduler may decide to place the pod elsewhere if other nodes become available sooner. Scheduler may also decide to give the resources on this node to a higher priority pod that is created after preemption. As a result, this field may be different than PodSpec.nodeName when the pod is scheduled.", - Type: []string{"string"}, - Format: "", - }, - }, - "hostIP": { - SchemaProps: spec.SchemaProps{ - Description: "hostIP holds the IP address of the host to which the pod is assigned. Empty if the pod has not started yet. A pod can be assigned to a node that has a problem in kubelet which in turns mean that HostIP will not be updated even if there is a node is assigned to pod", - Type: []string{"string"}, - Format: "", - }, - }, - "hostIPs": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - "x-kubernetes-patch-merge-key": "ip", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "hostIPs holds the IP addresses allocated to the host. If this field is specified, the first entry must match the hostIP field. This list is empty if the pod has not started yet. A pod can be assigned to a node that has a problem in kubelet which in turns means that HostIPs will not be updated even if there is a node is assigned to this pod.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.HostIP"), - }, - }, - }, - }, - }, - "podIP": { - SchemaProps: spec.SchemaProps{ - Description: "podIP address allocated to the pod. Routable at least within the cluster. Empty if not yet allocated.", - Type: []string{"string"}, - Format: "", - }, - }, - "podIPs": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "ip", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "podIPs holds the IP addresses allocated to the pod. If this field is specified, the 0th entry must match the podIP field. Pods may be allocated at most 1 value for each of IPv4 and IPv6. This list is empty if no IPs have been allocated yet.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodIP"), - }, - }, - }, - }, - }, - "startTime": { - SchemaProps: spec.SchemaProps{ - Description: "RFC 3339 date and time at which the object was acknowledged by the Kubelet. This is before the Kubelet pulled the container image(s) for the pod.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "initContainerStatuses": { - SchemaProps: spec.SchemaProps{ - Description: "The list has one entry per init container in the manifest. The most recent successful init container will have ready = true, the most recently started container will have startTime set. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-and-container-status", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerStatus"), - }, - }, - }, - }, - }, - "containerStatuses": { - SchemaProps: spec.SchemaProps{ - Description: "The list has one entry per container in the manifest. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-and-container-status", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerStatus"), - }, - }, - }, - }, - }, - "qosClass": { - SchemaProps: spec.SchemaProps{ - Description: "The Quality of Service (QOS) classification assigned to the pod based on resource requirements See PodQOSClass type for available QOS classes More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-qos/#quality-of-service-classes\n\nPossible enum values:\n - `\"BestEffort\"` is the BestEffort qos class.\n - `\"Burstable\"` is the Burstable qos class.\n - `\"Guaranteed\"` is the Guaranteed qos class.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"BestEffort", "Burstable", "Guaranteed"}, - }, - }, - "ephemeralContainerStatuses": { - SchemaProps: spec.SchemaProps{ - Description: "Status for any ephemeral containers that have run in this pod.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerStatus"), - }, - }, - }, - }, - }, - "resize": { - SchemaProps: spec.SchemaProps{ - Description: "Status of resources resize desired for pod's containers. It is empty if no resources resize is pending. Any changes to container resources will automatically set this to \"Proposed\"", - Type: []string{"string"}, - Format: "", - }, - }, - "resourceClaimStatuses": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "name", - }, - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge,retainKeys", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Status of resource claims.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodResourceClaimStatus"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ContainerStatus", "k8s.io/api/core/v1.HostIP", "k8s.io/api/core/v1.PodCondition", "k8s.io/api/core/v1.PodIP", "k8s.io/api/core/v1.PodResourceClaimStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_PodStatusResult(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodStatusResult is a wrapper for PodStatus returned by kubelet that can be encode/decoded", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Most recently observed status of the pod. This data may not be up to date. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_PodTemplate(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodTemplate describes a template for creating copies of a predefined pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "template": { - SchemaProps: spec.SchemaProps{ - Description: "Template defines the pods that will be created from this pod template. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodTemplateSpec"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodTemplateSpec", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_PodTemplateList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodTemplateList is a list of PodTemplates.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of pod templates", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodTemplate"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodTemplate", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_PodTemplateSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodTemplateSpec describes the data a pod should have when created from a template", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Specification of the desired behavior of the pod. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodSpec"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodSpec", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_PortStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "port": { - SchemaProps: spec.SchemaProps{ - Description: "Port is the port number of the service port of which status is recorded here", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "protocol": { - SchemaProps: spec.SchemaProps{ - Description: "Protocol is the protocol of the service port of which status is recorded here The supported values are: \"TCP\", \"UDP\", \"SCTP\"\n\nPossible enum values:\n - `\"SCTP\"` is the SCTP protocol.\n - `\"TCP\"` is the TCP protocol.\n - `\"UDP\"` is the UDP protocol.", - Default: "", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"SCTP", "TCP", "UDP"}, - }, - }, - "error": { - SchemaProps: spec.SchemaProps{ - Description: "Error is to record the problem with the service port The format of the error shall comply with the following rules: - built-in error values shall be specified in this file and those shall use\n CamelCase names\n- cloud provider specific error values must have names that comply with the\n format foo.example.com/CamelCase.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"port", "protocol"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PortworxVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PortworxVolumeSource represents a Portworx volume resource.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "volumeID": { - SchemaProps: spec.SchemaProps{ - Description: "volumeID uniquely identifies a Portworx volume", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fSType represents the filesystem type to mount Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\". Implicitly inferred to be \"ext4\" if unspecified.", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"volumeID"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PreferAvoidPodsEntry(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Describes a class of pods that should avoid this node.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "podSignature": { - SchemaProps: spec.SchemaProps{ - Description: "The class of pods.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodSignature"), - }, - }, - "evictionTime": { - SchemaProps: spec.SchemaProps{ - Description: "Time at which this entry was added to the list.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "(brief) reason why this entry was added to the list.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "Human readable message indicating why this entry was added to the list.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"podSignature"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodSignature", "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_PreferredSchedulingTerm(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "An empty preferred scheduling term matches all objects with implicit weight 0 (i.e. it's a no-op). A null preferred scheduling term matches no objects (i.e. is also a no-op).", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "weight": { - SchemaProps: spec.SchemaProps{ - Description: "Weight associated with matching the corresponding nodeSelectorTerm, in the range 1-100.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "preference": { - SchemaProps: spec.SchemaProps{ - Description: "A node selector term, associated with the corresponding weight.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NodeSelectorTerm"), - }, - }, - }, - Required: []string{"weight", "preference"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NodeSelectorTerm"}, - } -} - -func schema_k8sio_api_core_v1_Probe(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Probe describes a health check to be performed against a container to determine whether it is alive or ready to receive traffic.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "exec": { - SchemaProps: spec.SchemaProps{ - Description: "Exec specifies the action to take.", - Ref: ref("k8s.io/api/core/v1.ExecAction"), - }, - }, - "httpGet": { - SchemaProps: spec.SchemaProps{ - Description: "HTTPGet specifies the http request to perform.", - Ref: ref("k8s.io/api/core/v1.HTTPGetAction"), - }, - }, - "tcpSocket": { - SchemaProps: spec.SchemaProps{ - Description: "TCPSocket specifies an action involving a TCP port.", - Ref: ref("k8s.io/api/core/v1.TCPSocketAction"), - }, - }, - "grpc": { - SchemaProps: spec.SchemaProps{ - Description: "GRPC specifies an action involving a GRPC port.", - Ref: ref("k8s.io/api/core/v1.GRPCAction"), - }, - }, - "initialDelaySeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Number of seconds after the container has started before liveness probes are initiated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "timeoutSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Number of seconds after which the probe times out. Defaults to 1 second. Minimum value is 1. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "periodSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "How often (in seconds) to perform the probe. Default to 10 seconds. Minimum value is 1.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "successThreshold": { - SchemaProps: spec.SchemaProps{ - Description: "Minimum consecutive successes for the probe to be considered successful after having failed. Defaults to 1. Must be 1 for liveness and startup. Minimum value is 1.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "failureThreshold": { - SchemaProps: spec.SchemaProps{ - Description: "Minimum consecutive failures for the probe to be considered failed after having succeeded. Defaults to 3. Minimum value is 1.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "terminationGracePeriodSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Optional duration in seconds the pod needs to terminate gracefully upon probe failure. The grace period is the duration in seconds after the processes running in the pod are sent a termination signal and the time when the processes are forcibly halted with a kill signal. Set this value longer than the expected cleanup time for your process. If this value is nil, the pod's terminationGracePeriodSeconds will be used. Otherwise, this value overrides the value provided by the pod spec. Value must be non-negative integer. The value zero indicates stop immediately via the kill signal (no opportunity to shut down). This is a beta field and requires enabling ProbeTerminationGracePeriod feature gate. Minimum value is 1. spec.terminationGracePeriodSeconds is used if unset.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ExecAction", "k8s.io/api/core/v1.GRPCAction", "k8s.io/api/core/v1.HTTPGetAction", "k8s.io/api/core/v1.TCPSocketAction"}, - } -} - -func schema_k8sio_api_core_v1_ProbeHandler(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ProbeHandler defines a specific action that should be taken in a probe. One and only one of the fields must be specified.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "exec": { - SchemaProps: spec.SchemaProps{ - Description: "Exec specifies the action to take.", - Ref: ref("k8s.io/api/core/v1.ExecAction"), - }, - }, - "httpGet": { - SchemaProps: spec.SchemaProps{ - Description: "HTTPGet specifies the http request to perform.", - Ref: ref("k8s.io/api/core/v1.HTTPGetAction"), - }, - }, - "tcpSocket": { - SchemaProps: spec.SchemaProps{ - Description: "TCPSocket specifies an action involving a TCP port.", - Ref: ref("k8s.io/api/core/v1.TCPSocketAction"), - }, - }, - "grpc": { - SchemaProps: spec.SchemaProps{ - Description: "GRPC specifies an action involving a GRPC port.", - Ref: ref("k8s.io/api/core/v1.GRPCAction"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ExecAction", "k8s.io/api/core/v1.GRPCAction", "k8s.io/api/core/v1.HTTPGetAction", "k8s.io/api/core/v1.TCPSocketAction"}, - } -} - -func schema_k8sio_api_core_v1_ProjectedVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a projected volume source", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "sources": { - SchemaProps: spec.SchemaProps{ - Description: "sources is the list of volume projections", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.VolumeProjection"), - }, - }, - }, - }, - }, - "defaultMode": { - SchemaProps: spec.SchemaProps{ - Description: "defaultMode are the mode bits used to set permissions on created files by default. Must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.VolumeProjection"}, - } -} - -func schema_k8sio_api_core_v1_QuobyteVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Quobyte mount that lasts the lifetime of a pod. Quobyte volumes do not support ownership management or SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "registry": { - SchemaProps: spec.SchemaProps{ - Description: "registry represents a single or multiple Quobyte Registry services specified as a string as host:port pair (multiple entries are separated with commas) which acts as the central registry for volumes", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "volume": { - SchemaProps: spec.SchemaProps{ - Description: "volume is a string that references an already created Quobyte volume by name.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly here will force the Quobyte volume to be mounted with read-only permissions. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "user": { - SchemaProps: spec.SchemaProps{ - Description: "user to map volume access to Defaults to serivceaccount user", - Type: []string{"string"}, - Format: "", - }, - }, - "group": { - SchemaProps: spec.SchemaProps{ - Description: "group to map volume access to Default is no group", - Type: []string{"string"}, - Format: "", - }, - }, - "tenant": { - SchemaProps: spec.SchemaProps{ - Description: "tenant owning the given Quobyte volume in the Backend Used with dynamically provisioned Quobyte volumes, value is set by the plugin", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"registry", "volume"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_RBDPersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Rados Block Device mount that lasts the lifetime of a pod. RBD volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "monitors": { - SchemaProps: spec.SchemaProps{ - Description: "monitors is a collection of Ceph monitors. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "image": { - SchemaProps: spec.SchemaProps{ - Description: "image is the rados image name. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#rbd", - Type: []string{"string"}, - Format: "", - }, - }, - "pool": { - SchemaProps: spec.SchemaProps{ - Description: "pool is the rados pool name. Default is rbd. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Type: []string{"string"}, - Format: "", - }, - }, - "user": { - SchemaProps: spec.SchemaProps{ - Description: "user is the rados user name. Default is admin. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Type: []string{"string"}, - Format: "", - }, - }, - "keyring": { - SchemaProps: spec.SchemaProps{ - Description: "keyring is the path to key ring for RBDUser. Default is /etc/ceph/keyring. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Type: []string{"string"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef is name of the authentication secret for RBDUser. If provided overrides keyring. Default is nil. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"monitors", "image"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.SecretReference"}, - } -} - -func schema_k8sio_api_core_v1_RBDVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Rados Block Device mount that lasts the lifetime of a pod. RBD volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "monitors": { - SchemaProps: spec.SchemaProps{ - Description: "monitors is a collection of Ceph monitors. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "image": { - SchemaProps: spec.SchemaProps{ - Description: "image is the rados image name. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#rbd", - Type: []string{"string"}, - Format: "", - }, - }, - "pool": { - SchemaProps: spec.SchemaProps{ - Description: "pool is the rados pool name. Default is rbd. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Type: []string{"string"}, - Format: "", - }, - }, - "user": { - SchemaProps: spec.SchemaProps{ - Description: "user is the rados user name. Default is admin. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Type: []string{"string"}, - Format: "", - }, - }, - "keyring": { - SchemaProps: spec.SchemaProps{ - Description: "keyring is the path to key ring for RBDUser. Default is /etc/ceph/keyring. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Type: []string{"string"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef is name of the authentication secret for RBDUser. If provided overrides keyring. Default is nil. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"monitors", "image"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LocalObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_RangeAllocation(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "RangeAllocation is not a public type.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "range": { - SchemaProps: spec.SchemaProps{ - Description: "Range is string that identifies the range represented by 'data'.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "data": { - SchemaProps: spec.SchemaProps{ - Description: "Data is a bit array containing all allocated addresses in the previous segment.", - Type: []string{"string"}, - Format: "byte", - }, - }, - }, - Required: []string{"range", "data"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_ReplicationController(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ReplicationController represents the configuration of a replication controller.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "If the Labels of a ReplicationController are empty, they are defaulted to be the same as the Pod(s) that the replication controller manages. Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Spec defines the specification of the desired behavior of the replication controller. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ReplicationControllerSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status is the most recently observed status of the replication controller. This data may be out of date by some window of time. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ReplicationControllerStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ReplicationControllerSpec", "k8s.io/api/core/v1.ReplicationControllerStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_ReplicationControllerCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ReplicationControllerCondition describes the state of a replication controller at a certain point.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of replication controller condition.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status of the condition, one of True, False, Unknown.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "lastTransitionTime": { - SchemaProps: spec.SchemaProps{ - Description: "The last time the condition transitioned from one status to another.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "The reason for the condition's last transition.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "A human readable message indicating details about the transition.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_ReplicationControllerList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ReplicationControllerList is a collection of replication controllers.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of replication controllers. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ReplicationController"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ReplicationController", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_ReplicationControllerSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ReplicationControllerSpec is the specification of a replication controller.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "replicas": { - SchemaProps: spec.SchemaProps{ - Description: "Replicas is the number of desired replicas. This is a pointer to distinguish between explicit zero and unspecified. Defaults to 1. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#what-is-a-replicationcontroller", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "minReadySeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready)", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "selector": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Selector is a label query over pods that should match the Replicas count. If Selector is empty, it is defaulted to the labels present on the Pod template. Label keys and values that must match in order to be controlled by this replication controller, if empty defaulted to labels on Pod template. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "template": { - SchemaProps: spec.SchemaProps{ - Description: "Template is the object that describes the pod that will be created if insufficient replicas are detected. This takes precedence over a TemplateRef. The only allowed template.spec.restartPolicy value is \"Always\". More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#pod-template", - Ref: ref("k8s.io/api/core/v1.PodTemplateSpec"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodTemplateSpec"}, - } -} - -func schema_k8sio_api_core_v1_ReplicationControllerStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ReplicationControllerStatus represents the current status of a replication controller.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "replicas": { - SchemaProps: spec.SchemaProps{ - Description: "Replicas is the most recently observed number of replicas. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#what-is-a-replicationcontroller", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "fullyLabeledReplicas": { - SchemaProps: spec.SchemaProps{ - Description: "The number of pods that have labels matching the labels of the pod template of the replication controller.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "readyReplicas": { - SchemaProps: spec.SchemaProps{ - Description: "The number of ready replicas for this replication controller.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "availableReplicas": { - SchemaProps: spec.SchemaProps{ - Description: "The number of available replicas (ready for at least minReadySeconds) for this replication controller.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "observedGeneration": { - SchemaProps: spec.SchemaProps{ - Description: "ObservedGeneration reflects the generation of the most recently observed replication controller.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "conditions": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Represents the latest available observations of a replication controller's current state.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ReplicationControllerCondition"), - }, - }, - }, - }, - }, - }, - Required: []string{"replicas"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ReplicationControllerCondition"}, - } -} - -func schema_k8sio_api_core_v1_ResourceClaim(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ResourceClaim references one entry in PodSpec.ResourceClaims.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name must match the name of one entry in pod.spec.resourceClaims of the Pod where this field is used. It makes that resource available inside a container.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ResourceFieldSelector(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ResourceFieldSelector represents container resources (cpu, memory) and their output format", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "containerName": { - SchemaProps: spec.SchemaProps{ - Description: "Container name: required for volumes, optional for env vars", - Type: []string{"string"}, - Format: "", - }, - }, - "resource": { - SchemaProps: spec.SchemaProps{ - Description: "Required: resource to select", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "divisor": { - SchemaProps: spec.SchemaProps{ - Description: "Specifies the output format of the exposed resources, defaults to \"1\"", - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - Required: []string{"resource"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_ResourceQuota(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ResourceQuota sets aggregate quota restrictions enforced per namespace", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Spec defines the desired quota. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ResourceQuotaSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status defines the actual enforced quota and its current usage. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ResourceQuotaStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ResourceQuotaSpec", "k8s.io/api/core/v1.ResourceQuotaStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_ResourceQuotaList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ResourceQuotaList is a list of ResourceQuota items.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is a list of ResourceQuota objects. More info: https://kubernetes.io/docs/concepts/policy/resource-quotas/", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ResourceQuota"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ResourceQuota", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_ResourceQuotaSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ResourceQuotaSpec defines the desired hard limits to enforce for Quota.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "hard": { - SchemaProps: spec.SchemaProps{ - Description: "hard is the set of desired hard limits for each named resource. More info: https://kubernetes.io/docs/concepts/policy/resource-quotas/", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "scopes": { - SchemaProps: spec.SchemaProps{ - Description: "A collection of filters that must match each object tracked by a quota. If not specified, the quota matches all objects.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "scopeSelector": { - SchemaProps: spec.SchemaProps{ - Description: "scopeSelector is also a collection of filters like scopes that must match each object tracked by a quota but expressed using ScopeSelectorOperator in combination with possible values. For a resource to match, both scopes AND scopeSelector (if specified in spec), must be matched.", - Ref: ref("k8s.io/api/core/v1.ScopeSelector"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ScopeSelector", "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_ResourceQuotaStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ResourceQuotaStatus defines the enforced hard limits and observed use.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "hard": { - SchemaProps: spec.SchemaProps{ - Description: "Hard is the set of enforced hard limits for each named resource. More info: https://kubernetes.io/docs/concepts/policy/resource-quotas/", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "used": { - SchemaProps: spec.SchemaProps{ - Description: "Used is the current observed total usage of the resource in the namespace.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_ResourceRequirements(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ResourceRequirements describes the compute resource requirements.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "limits": { - SchemaProps: spec.SchemaProps{ - Description: "Limits describes the maximum amount of compute resources allowed. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "requests": { - SchemaProps: spec.SchemaProps{ - Description: "Requests describes the minimum amount of compute resources required. If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value. Requests cannot exceed Limits. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "claims": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "name", - }, - "x-kubernetes-list-type": "map", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Claims lists the names of resources, defined in spec.resourceClaims, that are used by this container.\n\nThis is an alpha field and requires enabling the DynamicResourceAllocation feature gate.\n\nThis field is immutable. It can only be set for containers.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ResourceClaim"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ResourceClaim", "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_SELinuxOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "SELinuxOptions are the labels to be applied to the container", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "user": { - SchemaProps: spec.SchemaProps{ - Description: "User is a SELinux user label that applies to the container.", - Type: []string{"string"}, - Format: "", - }, - }, - "role": { - SchemaProps: spec.SchemaProps{ - Description: "Role is a SELinux role label that applies to the container.", - Type: []string{"string"}, - Format: "", - }, - }, - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type is a SELinux type label that applies to the container.", - Type: []string{"string"}, - Format: "", - }, - }, - "level": { - SchemaProps: spec.SchemaProps{ - Description: "Level is SELinux level label that applies to the container.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ScaleIOPersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ScaleIOPersistentVolumeSource represents a persistent ScaleIO volume", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "gateway": { - SchemaProps: spec.SchemaProps{ - Description: "gateway is the host address of the ScaleIO API Gateway.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "system": { - SchemaProps: spec.SchemaProps{ - Description: "system is the name of the storage system as configured in ScaleIO.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef references to the secret for ScaleIO user and other sensitive information. If this is not provided, Login operation will fail.", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - "sslEnabled": { - SchemaProps: spec.SchemaProps{ - Description: "sslEnabled is the flag to enable/disable SSL communication with Gateway, default false", - Type: []string{"boolean"}, - Format: "", - }, - }, - "protectionDomain": { - SchemaProps: spec.SchemaProps{ - Description: "protectionDomain is the name of the ScaleIO Protection Domain for the configured storage.", - Type: []string{"string"}, - Format: "", - }, - }, - "storagePool": { - SchemaProps: spec.SchemaProps{ - Description: "storagePool is the ScaleIO Storage Pool associated with the protection domain.", - Type: []string{"string"}, - Format: "", - }, - }, - "storageMode": { - SchemaProps: spec.SchemaProps{ - Description: "storageMode indicates whether the storage for a volume should be ThickProvisioned or ThinProvisioned. Default is ThinProvisioned.", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeName": { - SchemaProps: spec.SchemaProps{ - Description: "volumeName is the name of a volume already created in the ScaleIO system that is associated with this volume source.", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Default is \"xfs\"", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"gateway", "system", "secretRef"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.SecretReference"}, - } -} - -func schema_k8sio_api_core_v1_ScaleIOVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ScaleIOVolumeSource represents a persistent ScaleIO volume", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "gateway": { - SchemaProps: spec.SchemaProps{ - Description: "gateway is the host address of the ScaleIO API Gateway.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "system": { - SchemaProps: spec.SchemaProps{ - Description: "system is the name of the storage system as configured in ScaleIO.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef references to the secret for ScaleIO user and other sensitive information. If this is not provided, Login operation will fail.", - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - "sslEnabled": { - SchemaProps: spec.SchemaProps{ - Description: "sslEnabled Flag enable/disable SSL communication with Gateway, default false", - Type: []string{"boolean"}, - Format: "", - }, - }, - "protectionDomain": { - SchemaProps: spec.SchemaProps{ - Description: "protectionDomain is the name of the ScaleIO Protection Domain for the configured storage.", - Type: []string{"string"}, - Format: "", - }, - }, - "storagePool": { - SchemaProps: spec.SchemaProps{ - Description: "storagePool is the ScaleIO Storage Pool associated with the protection domain.", - Type: []string{"string"}, - Format: "", - }, - }, - "storageMode": { - SchemaProps: spec.SchemaProps{ - Description: "storageMode indicates whether the storage for a volume should be ThickProvisioned or ThinProvisioned. Default is ThinProvisioned.", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeName": { - SchemaProps: spec.SchemaProps{ - Description: "volumeName is the name of a volume already created in the ScaleIO system that is associated with this volume source.", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Default is \"xfs\".", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"gateway", "system", "secretRef"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LocalObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_ScopeSelector(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A scope selector represents the AND of the selectors represented by the scoped-resource selector requirements.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "matchExpressions": { - SchemaProps: spec.SchemaProps{ - Description: "A list of scope selector requirements by scope of the resources.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ScopedResourceSelectorRequirement"), - }, - }, - }, - }, - }, - }, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ScopedResourceSelectorRequirement"}, - } -} - -func schema_k8sio_api_core_v1_ScopedResourceSelectorRequirement(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A scoped-resource selector requirement is a selector that contains values, a scope name, and an operator that relates the scope name and values.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "scopeName": { - SchemaProps: spec.SchemaProps{ - Description: "The name of the scope that the selector applies to.\n\nPossible enum values:\n - `\"BestEffort\"` Match all pod objects that have best effort quality of service\n - `\"CrossNamespacePodAffinity\"` Match all pod objects that have cross-namespace pod (anti)affinity mentioned.\n - `\"NotBestEffort\"` Match all pod objects that do not have best effort quality of service\n - `\"NotTerminating\"` Match all pod objects where spec.activeDeadlineSeconds is nil\n - `\"PriorityClass\"` Match all pod objects that have priority class mentioned\n - `\"Terminating\"` Match all pod objects where spec.activeDeadlineSeconds >=0", - Default: "", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"BestEffort", "CrossNamespacePodAffinity", "NotBestEffort", "NotTerminating", "PriorityClass", "Terminating"}, - }, - }, - "operator": { - SchemaProps: spec.SchemaProps{ - Description: "Represents a scope's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist.\n\nPossible enum values:\n - `\"DoesNotExist\"`\n - `\"Exists\"`\n - `\"In\"`\n - `\"NotIn\"`", - Default: "", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"DoesNotExist", "Exists", "In", "NotIn"}, - }, - }, - "values": { - SchemaProps: spec.SchemaProps{ - Description: "An array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"scopeName", "operator"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_SeccompProfile(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "SeccompProfile defines a pod/container's seccomp profile settings. Only one profile source may be set.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "type indicates which kind of seccomp profile will be applied. Valid options are:\n\nLocalhost - a profile defined in a file on the node should be used. RuntimeDefault - the container runtime default profile should be used. Unconfined - no profile should be applied.\n\nPossible enum values:\n - `\"Localhost\"` indicates a profile defined in a file on the node should be used. The file's location relative to /seccomp.\n - `\"RuntimeDefault\"` represents the default container runtime seccomp profile.\n - `\"Unconfined\"` indicates no seccomp profile is applied (A.K.A. unconfined).", - Default: "", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Localhost", "RuntimeDefault", "Unconfined"}, - }, - }, - "localhostProfile": { - SchemaProps: spec.SchemaProps{ - Description: "localhostProfile indicates a profile defined in a file on the node should be used. The profile must be preconfigured on the node to work. Must be a descending path, relative to the kubelet's configured seccomp profile location. Must be set if type is \"Localhost\". Must NOT be set for any other type.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-unions": []interface{}{ - map[string]interface{}{ - "discriminator": "type", - "fields-to-discriminateBy": map[string]interface{}{ - "localhostProfile": "LocalhostProfile", - }, - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_Secret(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Secret holds secret data of a certain type. The total bytes of the values in the Data field must be less than MaxSecretSize bytes.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "immutable": { - SchemaProps: spec.SchemaProps{ - Description: "Immutable, if set to true, ensures that data stored in the Secret cannot be updated (only object metadata can be modified). If not set to true, the field can be modified at any time. Defaulted to nil.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "data": { - SchemaProps: spec.SchemaProps{ - Description: "Data contains the secret data. Each key must consist of alphanumeric characters, '-', '_' or '.'. The serialized form of the secret data is a base64 encoded string, representing the arbitrary (possibly non-string) data value here. Described in https://tools.ietf.org/html/rfc4648#section-4", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "byte", - }, - }, - }, - }, - }, - "stringData": { - SchemaProps: spec.SchemaProps{ - Description: "stringData allows specifying non-binary secret data in string form. It is provided as a write-only input field for convenience. All keys and values are merged into the data field on write, overwriting any existing values. The stringData field is never output when reading from the API.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Used to facilitate programmatic handling of secret data. More info: https://kubernetes.io/docs/concepts/configuration/secret/#secret-types", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_SecretEnvSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "SecretEnvSource selects a Secret to populate the environment variables with.\n\nThe contents of the target Secret's Data field will represent the key-value pairs as environment variables.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Type: []string{"string"}, - Format: "", - }, - }, - "optional": { - SchemaProps: spec.SchemaProps{ - Description: "Specify whether the Secret must be defined", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_SecretKeySelector(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "SecretKeySelector selects a key of a Secret.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Type: []string{"string"}, - Format: "", - }, - }, - "key": { - SchemaProps: spec.SchemaProps{ - Description: "The key of the secret to select from. Must be a valid secret key.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "optional": { - SchemaProps: spec.SchemaProps{ - Description: "Specify whether the Secret or its key must be defined", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"key"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_SecretList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "SecretList is a list of Secret.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is a list of secret objects. More info: https://kubernetes.io/docs/concepts/configuration/secret", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Secret"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.Secret", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_SecretProjection(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Adapts a secret into a projected volume.\n\nThe contents of the target Secret's Data field will be presented in a projected volume as files using the keys in the Data field as the file names. Note that this is identical to a secret volume source without the default mode.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Type: []string{"string"}, - Format: "", - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "items if unspecified, each key-value pair in the Data field of the referenced Secret will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the Secret, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.KeyToPath"), - }, - }, - }, - }, - }, - "optional": { - SchemaProps: spec.SchemaProps{ - Description: "optional field specify whether the Secret or its key must be defined", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.KeyToPath"}, - } -} - -func schema_k8sio_api_core_v1_SecretReference(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "SecretReference represents a Secret Reference. It has enough information to retrieve secret in any namespace", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "name is unique within a namespace to reference a secret resource.", - Type: []string{"string"}, - Format: "", - }, - }, - "namespace": { - SchemaProps: spec.SchemaProps{ - Description: "namespace defines the space within which the secret name must be unique.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_SecretVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Adapts a Secret into a volume.\n\nThe contents of the target Secret's Data field will be presented in a volume as files using the keys in the Data field as the file names. Secret volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "secretName": { - SchemaProps: spec.SchemaProps{ - Description: "secretName is the name of the secret in the pod's namespace to use. More info: https://kubernetes.io/docs/concepts/storage/volumes#secret", - Type: []string{"string"}, - Format: "", - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "items If unspecified, each key-value pair in the Data field of the referenced Secret will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the Secret, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.KeyToPath"), - }, - }, - }, - }, - }, - "defaultMode": { - SchemaProps: spec.SchemaProps{ - Description: "defaultMode is Optional: mode bits used to set permissions on created files by default. Must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "optional": { - SchemaProps: spec.SchemaProps{ - Description: "optional field specify whether the Secret or its keys must be defined", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.KeyToPath"}, - } -} - -func schema_k8sio_api_core_v1_SecurityContext(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "SecurityContext holds security configuration that will be applied to a container. Some fields are present in both SecurityContext and PodSecurityContext. When both are set, the values in SecurityContext take precedence.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "capabilities": { - SchemaProps: spec.SchemaProps{ - Description: "The capabilities to add/drop when running containers. Defaults to the default set of capabilities granted by the container runtime. Note that this field cannot be set when spec.os.name is windows.", - Ref: ref("k8s.io/api/core/v1.Capabilities"), - }, - }, - "privileged": { - SchemaProps: spec.SchemaProps{ - Description: "Run container in privileged mode. Processes in privileged containers are essentially equivalent to root on the host. Defaults to false. Note that this field cannot be set when spec.os.name is windows.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "seLinuxOptions": { - SchemaProps: spec.SchemaProps{ - Description: "The SELinux context to be applied to the container. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. Note that this field cannot be set when spec.os.name is windows.", - Ref: ref("k8s.io/api/core/v1.SELinuxOptions"), - }, - }, - "windowsOptions": { - SchemaProps: spec.SchemaProps{ - Description: "The Windows specific settings applied to all containers. If unspecified, the options from the PodSecurityContext will be used. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. Note that this field cannot be set when spec.os.name is linux.", - Ref: ref("k8s.io/api/core/v1.WindowsSecurityContextOptions"), - }, - }, - "runAsUser": { - SchemaProps: spec.SchemaProps{ - Description: "The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. Note that this field cannot be set when spec.os.name is windows.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "runAsGroup": { - SchemaProps: spec.SchemaProps{ - Description: "The GID to run the entrypoint of the container process. Uses runtime default if unset. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. Note that this field cannot be set when spec.os.name is windows.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "runAsNonRoot": { - SchemaProps: spec.SchemaProps{ - Description: "Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. If unset or false, no such validation will be performed. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "readOnlyRootFilesystem": { - SchemaProps: spec.SchemaProps{ - Description: "Whether this container has a read-only root filesystem. Default is false. Note that this field cannot be set when spec.os.name is windows.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "allowPrivilegeEscalation": { - SchemaProps: spec.SchemaProps{ - Description: "AllowPrivilegeEscalation controls whether a process can gain more privileges than its parent process. This bool directly controls if the no_new_privs flag will be set on the container process. AllowPrivilegeEscalation is true always when the container is: 1) run as Privileged 2) has CAP_SYS_ADMIN Note that this field cannot be set when spec.os.name is windows.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "procMount": { - SchemaProps: spec.SchemaProps{ - Description: "procMount denotes the type of proc mount to use for the containers. The default is DefaultProcMount which uses the container runtime defaults for readonly paths and masked paths. This requires the ProcMountType feature flag to be enabled. Note that this field cannot be set when spec.os.name is windows.\n\nPossible enum values:\n - `\"Default\"` uses the container runtime defaults for readonly and masked paths for /proc. Most container runtimes mask certain paths in /proc to avoid accidental security exposure of special devices or information.\n - `\"Unmasked\"` bypasses the default masking behavior of the container runtime and ensures the newly created /proc the container stays in tact with no modifications.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Default", "Unmasked"}, - }, - }, - "seccompProfile": { - SchemaProps: spec.SchemaProps{ - Description: "The seccomp options to use by this container. If seccomp options are provided at both the pod & container level, the container options override the pod options. Note that this field cannot be set when spec.os.name is windows.", - Ref: ref("k8s.io/api/core/v1.SeccompProfile"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.Capabilities", "k8s.io/api/core/v1.SELinuxOptions", "k8s.io/api/core/v1.SeccompProfile", "k8s.io/api/core/v1.WindowsSecurityContextOptions"}, - } -} - -func schema_k8sio_api_core_v1_SerializedReference(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "SerializedReference is a reference to serialized object.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "reference": { - SchemaProps: spec.SchemaProps{ - Description: "The reference to an object in the system.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ObjectReference"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_Service(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Service is a named abstraction of software service (for example, mysql) consisting of local port (for example 3306) that the proxy listens on, and the selector that determines which pods will answer requests sent through the proxy.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Spec defines the behavior of a service. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ServiceSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Most recently observed status of the service. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ServiceStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ServiceSpec", "k8s.io/api/core/v1.ServiceStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_ServiceAccount(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ServiceAccount binds together: * a name, understood by users, and perhaps by peripheral systems, for an identity * a principal that can be authenticated and authorized * a set of secrets", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "secrets": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Secrets is a list of the secrets in the same namespace that pods running using this ServiceAccount are allowed to use. Pods are only limited to this list if this service account has a \"kubernetes.io/enforce-mountable-secrets\" annotation set to \"true\". This field should not be used to find auto-generated service account token secrets for use outside of pods. Instead, tokens can be requested directly using the TokenRequest API, or service account token secrets can be manually created. More info: https://kubernetes.io/docs/concepts/configuration/secret", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ObjectReference"), - }, - }, - }, - }, - }, - "imagePullSecrets": { - SchemaProps: spec.SchemaProps{ - Description: "ImagePullSecrets is a list of references to secrets in the same namespace to use for pulling any images in pods that reference this ServiceAccount. ImagePullSecrets are distinct from Secrets because Secrets can be mounted in the pod, but ImagePullSecrets are only accessed by the kubelet. More info: https://kubernetes.io/docs/concepts/containers/images/#specifying-imagepullsecrets-on-a-pod", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - }, - }, - }, - "automountServiceAccountToken": { - SchemaProps: spec.SchemaProps{ - Description: "AutomountServiceAccountToken indicates whether pods running as this service account should have an API token automatically mounted. Can be overridden at the pod level.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LocalObjectReference", "k8s.io/api/core/v1.ObjectReference", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_ServiceAccountList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ServiceAccountList is a list of ServiceAccount objects", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of ServiceAccounts. More info: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ServiceAccount"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ServiceAccount", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_ServiceAccountTokenProjection(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ServiceAccountTokenProjection represents a projected service account token volume. This projection can be used to insert a service account token into the pods runtime filesystem for use against APIs (Kubernetes API Server or otherwise).", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "audience": { - SchemaProps: spec.SchemaProps{ - Description: "audience is the intended audience of the token. A recipient of a token must identify itself with an identifier specified in the audience of the token, and otherwise should reject the token. The audience defaults to the identifier of the apiserver.", - Type: []string{"string"}, - Format: "", - }, - }, - "expirationSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "expirationSeconds is the requested duration of validity of the service account token. As the token approaches expiration, the kubelet volume plugin will proactively rotate the service account token. The kubelet will start trying to rotate the token if the token is older than 80 percent of its time to live or if the token is older than 24 hours.Defaults to 1 hour and must be at least 10 minutes.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "path is the path relative to the mount point of the file to project the token into.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"path"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ServiceList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ServiceList holds a list of services.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of services", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Service"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.Service", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_ServicePort(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ServicePort contains information on service's port.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "The name of this port within the service. This must be a DNS_LABEL. All ports within a ServiceSpec must have unique names. When considering the endpoints for a Service, this must match the 'name' field in the EndpointPort. Optional if only one ServicePort is defined on this service.", - Type: []string{"string"}, - Format: "", - }, - }, - "protocol": { - SchemaProps: spec.SchemaProps{ - Description: "The IP protocol for this port. Supports \"TCP\", \"UDP\", and \"SCTP\". Default is TCP.\n\nPossible enum values:\n - `\"SCTP\"` is the SCTP protocol.\n - `\"TCP\"` is the TCP protocol.\n - `\"UDP\"` is the UDP protocol.", - Default: "TCP", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"SCTP", "TCP", "UDP"}, - }, - }, - "appProtocol": { - SchemaProps: spec.SchemaProps{ - Description: "The application protocol for this port. This is used as a hint for implementations to offer richer behavior for protocols that they understand. This field follows standard Kubernetes label syntax. Valid values are either:\n\n* Un-prefixed protocol names - reserved for IANA standard service names (as per RFC-6335 and https://www.iana.org/assignments/service-names).\n\n* Kubernetes-defined prefixed names:\n * 'kubernetes.io/h2c' - HTTP/2 prior knowledge over cleartext as described in https://www.rfc-editor.org/rfc/rfc9113.html#name-starting-http-2-with-prior-\n * 'kubernetes.io/ws' - WebSocket over cleartext as described in https://www.rfc-editor.org/rfc/rfc6455\n * 'kubernetes.io/wss' - WebSocket over TLS as described in https://www.rfc-editor.org/rfc/rfc6455\n\n* Other protocols should use implementation-defined prefixed names such as mycompany.com/my-custom-protocol.", - Type: []string{"string"}, - Format: "", - }, - }, - "port": { - SchemaProps: spec.SchemaProps{ - Description: "The port that will be exposed by this service.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "targetPort": { - SchemaProps: spec.SchemaProps{ - Description: "Number or name of the port to access on the pods targeted by the service. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME. If this is a string, it will be looked up as a named port in the target Pod's container ports. If this is not specified, the value of the 'port' field is used (an identity map). This field is ignored for services with clusterIP=None, and should be omitted or set equal to the 'port' field. More info: https://kubernetes.io/docs/concepts/services-networking/service/#defining-a-service", - Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), - }, - }, - "nodePort": { - SchemaProps: spec.SchemaProps{ - Description: "The port on each node on which this service is exposed when type is NodePort or LoadBalancer. Usually assigned by the system. If a value is specified, in-range, and not in use it will be used, otherwise the operation will fail. If not specified, a port will be allocated if this Service requires one. If this field is specified when creating a Service which does not need it, creation will fail. This field will be wiped when updating a Service to no longer need it (e.g. changing type from NodePort to ClusterIP). More info: https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport", - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - Required: []string{"port"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/util/intstr.IntOrString"}, - } -} - -func schema_k8sio_api_core_v1_ServiceProxyOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ServiceProxyOptions is the query options to a Service's proxy call.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ServiceSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ServiceSpec describes the attributes that a user creates on a service.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "ports": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "port", - "protocol", - }, - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "port", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "The list of ports that are exposed by this service. More info: https://kubernetes.io/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ServicePort"), - }, - }, - }, - }, - }, - "selector": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Route service traffic to pods with label keys and values matching this selector. If empty or not present, the service is assumed to have an external process managing its endpoints, which Kubernetes will not modify. Only applies to types ClusterIP, NodePort, and LoadBalancer. Ignored if type is ExternalName. More info: https://kubernetes.io/docs/concepts/services-networking/service/", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "clusterIP": { - SchemaProps: spec.SchemaProps{ - Description: "clusterIP is the IP address of the service and is usually assigned randomly. If an address is specified manually, is in-range (as per system configuration), and is not in use, it will be allocated to the service; otherwise creation of the service will fail. This field may not be changed through updates unless the type field is also being changed to ExternalName (which requires this field to be blank) or the type field is being changed from ExternalName (in which case this field may optionally be specified, as describe above). Valid values are \"None\", empty string (\"\"), or a valid IP address. Setting this to \"None\" makes a \"headless service\" (no virtual IP), which is useful when direct endpoint connections are preferred and proxying is not required. Only applies to types ClusterIP, NodePort, and LoadBalancer. If this field is specified when creating a Service of type ExternalName, creation will fail. This field will be wiped when updating a Service to type ExternalName. More info: https://kubernetes.io/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies", - Type: []string{"string"}, - Format: "", - }, - }, - "clusterIPs": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "ClusterIPs is a list of IP addresses assigned to this service, and are usually assigned randomly. If an address is specified manually, is in-range (as per system configuration), and is not in use, it will be allocated to the service; otherwise creation of the service will fail. This field may not be changed through updates unless the type field is also being changed to ExternalName (which requires this field to be empty) or the type field is being changed from ExternalName (in which case this field may optionally be specified, as describe above). Valid values are \"None\", empty string (\"\"), or a valid IP address. Setting this to \"None\" makes a \"headless service\" (no virtual IP), which is useful when direct endpoint connections are preferred and proxying is not required. Only applies to types ClusterIP, NodePort, and LoadBalancer. If this field is specified when creating a Service of type ExternalName, creation will fail. This field will be wiped when updating a Service to type ExternalName. If this field is not specified, it will be initialized from the clusterIP field. If this field is specified, clients must ensure that clusterIPs[0] and clusterIP have the same value.\n\nThis field may hold a maximum of two entries (dual-stack IPs, in either order). These IPs must correspond to the values of the ipFamilies field. Both clusterIPs and ipFamilies are governed by the ipFamilyPolicy field. More info: https://kubernetes.io/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "type": { - SchemaProps: spec.SchemaProps{ - Description: "type determines how the Service is exposed. Defaults to ClusterIP. Valid options are ExternalName, ClusterIP, NodePort, and LoadBalancer. \"ClusterIP\" allocates a cluster-internal IP address for load-balancing to endpoints. Endpoints are determined by the selector or if that is not specified, by manual construction of an Endpoints object or EndpointSlice objects. If clusterIP is \"None\", no virtual IP is allocated and the endpoints are published as a set of endpoints rather than a virtual IP. \"NodePort\" builds on ClusterIP and allocates a port on every node which routes to the same endpoints as the clusterIP. \"LoadBalancer\" builds on NodePort and creates an external load-balancer (if supported in the current cloud) which routes to the same endpoints as the clusterIP. \"ExternalName\" aliases this service to the specified externalName. Several other fields do not apply to ExternalName services. More info: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types\n\nPossible enum values:\n - `\"ClusterIP\"` means a service will only be accessible inside the cluster, via the cluster IP.\n - `\"ExternalName\"` means a service consists of only a reference to an external name that kubedns or equivalent will return as a CNAME record, with no exposing or proxying of any pods involved.\n - `\"LoadBalancer\"` means a service will be exposed via an external load balancer (if the cloud provider supports it), in addition to 'NodePort' type.\n - `\"NodePort\"` means a service will be exposed on one port of every node, in addition to 'ClusterIP' type.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"ClusterIP", "ExternalName", "LoadBalancer", "NodePort"}, - }, - }, - "externalIPs": { - SchemaProps: spec.SchemaProps{ - Description: "externalIPs is a list of IP addresses for which nodes in the cluster will also accept traffic for this service. These IPs are not managed by Kubernetes. The user is responsible for ensuring that traffic arrives at a node with this IP. A common example is external load-balancers that are not part of the Kubernetes system.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "sessionAffinity": { - SchemaProps: spec.SchemaProps{ - Description: "Supports \"ClientIP\" and \"None\". Used to maintain session affinity. Enable client IP based session affinity. Must be ClientIP or None. Defaults to None. More info: https://kubernetes.io/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies\n\nPossible enum values:\n - `\"ClientIP\"` is the Client IP based.\n - `\"None\"` - no session affinity.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"ClientIP", "None"}, - }, - }, - "loadBalancerIP": { - SchemaProps: spec.SchemaProps{ - Description: "Only applies to Service Type: LoadBalancer. This feature depends on whether the underlying cloud-provider supports specifying the loadBalancerIP when a load balancer is created. This field will be ignored if the cloud-provider does not support the feature. Deprecated: This field was under-specified and its meaning varies across implementations. Using it is non-portable and it may not support dual-stack. Users are encouraged to use implementation-specific annotations when available.", - Type: []string{"string"}, - Format: "", - }, - }, - "loadBalancerSourceRanges": { - SchemaProps: spec.SchemaProps{ - Description: "If specified and supported by the platform, this will restrict traffic through the cloud-provider load-balancer will be restricted to the specified client IPs. This field will be ignored if the cloud-provider does not support the feature.\" More info: https://kubernetes.io/docs/tasks/access-application-cluster/create-external-load-balancer/", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "externalName": { - SchemaProps: spec.SchemaProps{ - Description: "externalName is the external reference that discovery mechanisms will return as an alias for this service (e.g. a DNS CNAME record). No proxying will be involved. Must be a lowercase RFC-1123 hostname (https://tools.ietf.org/html/rfc1123) and requires `type` to be \"ExternalName\".", - Type: []string{"string"}, - Format: "", - }, - }, - "externalTrafficPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "externalTrafficPolicy describes how nodes distribute service traffic they receive on one of the Service's \"externally-facing\" addresses (NodePorts, ExternalIPs, and LoadBalancer IPs). If set to \"Local\", the proxy will configure the service in a way that assumes that external load balancers will take care of balancing the service traffic between nodes, and so each node will deliver traffic only to the node-local endpoints of the service, without masquerading the client source IP. (Traffic mistakenly sent to a node with no endpoints will be dropped.) The default value, \"Cluster\", uses the standard behavior of routing to all endpoints evenly (possibly modified by topology and other features). Note that traffic sent to an External IP or LoadBalancer IP from within the cluster will always get \"Cluster\" semantics, but clients sending to a NodePort from within the cluster may need to take traffic policy into account when picking a node.\n\nPossible enum values:\n - `\"Cluster\"`\n - `\"Cluster\"` routes traffic to all endpoints.\n - `\"Local\"`\n - `\"Local\"` preserves the source IP of the traffic by routing only to endpoints on the same node as the traffic was received on (dropping the traffic if there are no local endpoints).", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Cluster", "Cluster", "Local", "Local"}, - }, - }, - "healthCheckNodePort": { - SchemaProps: spec.SchemaProps{ - Description: "healthCheckNodePort specifies the healthcheck nodePort for the service. This only applies when type is set to LoadBalancer and externalTrafficPolicy is set to Local. If a value is specified, is in-range, and is not in use, it will be used. If not specified, a value will be automatically allocated. External systems (e.g. load-balancers) can use this port to determine if a given node holds endpoints for this service or not. If this field is specified when creating a Service which does not need it, creation will fail. This field will be wiped when updating a Service to no longer need it (e.g. changing type). This field cannot be updated once set.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "publishNotReadyAddresses": { - SchemaProps: spec.SchemaProps{ - Description: "publishNotReadyAddresses indicates that any agent which deals with endpoints for this Service should disregard any indications of ready/not-ready. The primary use case for setting this field is for a StatefulSet's Headless Service to propagate SRV DNS records for its Pods for the purpose of peer discovery. The Kubernetes controllers that generate Endpoints and EndpointSlice resources for Services interpret this to mean that all endpoints are considered \"ready\" even if the Pods themselves are not. Agents which consume only Kubernetes generated endpoints through the Endpoints or EndpointSlice resources can safely assume this behavior.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "sessionAffinityConfig": { - SchemaProps: spec.SchemaProps{ - Description: "sessionAffinityConfig contains the configurations of session affinity.", - Ref: ref("k8s.io/api/core/v1.SessionAffinityConfig"), - }, - }, - "ipFamilies": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "IPFamilies is a list of IP families (e.g. IPv4, IPv6) assigned to this service. This field is usually assigned automatically based on cluster configuration and the ipFamilyPolicy field. If this field is specified manually, the requested family is available in the cluster, and ipFamilyPolicy allows it, it will be used; otherwise creation of the service will fail. This field is conditionally mutable: it allows for adding or removing a secondary IP family, but it does not allow changing the primary IP family of the Service. Valid values are \"IPv4\" and \"IPv6\". This field only applies to Services of types ClusterIP, NodePort, and LoadBalancer, and does apply to \"headless\" services. This field will be wiped when updating a Service to type ExternalName.\n\nThis field may hold a maximum of two entries (dual-stack families, in either order). These families must correspond to the values of the clusterIPs field, if specified. Both clusterIPs and ipFamilies are governed by the ipFamilyPolicy field.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "ipFamilyPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "IPFamilyPolicy represents the dual-stack-ness requested or required by this Service. If there is no value provided, then this field will be set to SingleStack. Services can be \"SingleStack\" (a single IP family), \"PreferDualStack\" (two IP families on dual-stack configured clusters or a single IP family on single-stack clusters), or \"RequireDualStack\" (two IP families on dual-stack configured clusters, otherwise fail). The ipFamilies and clusterIPs fields depend on the value of this field. This field will be wiped when updating a service to type ExternalName.\n\nPossible enum values:\n - `\"PreferDualStack\"` indicates that this service prefers dual-stack when the cluster is configured for dual-stack. If the cluster is not configured for dual-stack the service will be assigned a single IPFamily. If the IPFamily is not set in service.spec.ipFamilies then the service will be assigned the default IPFamily configured on the cluster\n - `\"RequireDualStack\"` indicates that this service requires dual-stack. Using IPFamilyPolicyRequireDualStack on a single stack cluster will result in validation errors. The IPFamilies (and their order) assigned to this service is based on service.spec.ipFamilies. If service.spec.ipFamilies was not provided then it will be assigned according to how they are configured on the cluster. If service.spec.ipFamilies has only one entry then the alternative IPFamily will be added by apiserver\n - `\"SingleStack\"` indicates that this service is required to have a single IPFamily. The IPFamily assigned is based on the default IPFamily used by the cluster or as identified by service.spec.ipFamilies field", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"PreferDualStack", "RequireDualStack", "SingleStack"}, - }, - }, - "allocateLoadBalancerNodePorts": { - SchemaProps: spec.SchemaProps{ - Description: "allocateLoadBalancerNodePorts defines if NodePorts will be automatically allocated for services with type LoadBalancer. Default is \"true\". It may be set to \"false\" if the cluster load-balancer does not rely on NodePorts. If the caller requests specific NodePorts (by specifying a value), those requests will be respected, regardless of this field. This field may only be set for services with type LoadBalancer and will be cleared if the type is changed to any other type.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "loadBalancerClass": { - SchemaProps: spec.SchemaProps{ - Description: "loadBalancerClass is the class of the load balancer implementation this Service belongs to. If specified, the value of this field must be a label-style identifier, with an optional prefix, e.g. \"internal-vip\" or \"example.com/internal-vip\". Unprefixed names are reserved for end-users. This field can only be set when the Service type is 'LoadBalancer'. If not set, the default load balancer implementation is used, today this is typically done through the cloud provider integration, but should apply for any default implementation. If set, it is assumed that a load balancer implementation is watching for Services with a matching class. Any default load balancer implementation (e.g. cloud providers) should ignore Services that set this field. This field can only be set when creating or updating a Service to type 'LoadBalancer'. Once set, it can not be changed. This field will be wiped when a service is updated to a non 'LoadBalancer' type.", - Type: []string{"string"}, - Format: "", - }, - }, - "internalTrafficPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "InternalTrafficPolicy describes how nodes distribute service traffic they receive on the ClusterIP. If set to \"Local\", the proxy will assume that pods only want to talk to endpoints of the service on the same node as the pod, dropping the traffic if there are no local endpoints. The default value, \"Cluster\", uses the standard behavior of routing to all endpoints evenly (possibly modified by topology and other features).\n\nPossible enum values:\n - `\"Cluster\"` routes traffic to all endpoints.\n - `\"Local\"` routes traffic only to endpoints on the same node as the client pod (dropping the traffic if there are no local endpoints).", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Cluster", "Local"}, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ServicePort", "k8s.io/api/core/v1.SessionAffinityConfig"}, - } -} - -func schema_k8sio_api_core_v1_ServiceStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ServiceStatus represents the current status of a service.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "loadBalancer": { - SchemaProps: spec.SchemaProps{ - Description: "LoadBalancer contains the current status of the load-balancer, if one is present.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.LoadBalancerStatus"), - }, - }, - "conditions": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "type", - }, - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Current service state", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Condition"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LoadBalancerStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.Condition"}, - } -} - -func schema_k8sio_api_core_v1_SessionAffinityConfig(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "SessionAffinityConfig represents the configurations of session affinity.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "clientIP": { - SchemaProps: spec.SchemaProps{ - Description: "clientIP contains the configurations of Client IP based session affinity.", - Ref: ref("k8s.io/api/core/v1.ClientIPConfig"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ClientIPConfig"}, - } -} - -func schema_k8sio_api_core_v1_SleepAction(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "SleepAction describes a \"sleep\" action.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "seconds": { - SchemaProps: spec.SchemaProps{ - Description: "Seconds is the number of seconds to sleep.", - Default: 0, - Type: []string{"integer"}, - Format: "int64", - }, - }, - }, - Required: []string{"seconds"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_StorageOSPersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a StorageOS persistent volume resource.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "volumeName": { - SchemaProps: spec.SchemaProps{ - Description: "volumeName is the human-readable name of the StorageOS volume. Volume names are only unique within a namespace.", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeNamespace": { - SchemaProps: spec.SchemaProps{ - Description: "volumeNamespace specifies the scope of the volume within StorageOS. If no namespace is specified then the Pod's namespace will be used. This allows the Kubernetes name scoping to be mirrored within StorageOS for tighter integration. Set VolumeName to any name to override the default behaviour. Set to \"default\" if you are not using namespaces within StorageOS. Namespaces that do not pre-exist within StorageOS will be created.", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef specifies the secret to use for obtaining the StorageOS API credentials. If not specified, default values will be attempted.", - Ref: ref("k8s.io/api/core/v1.ObjectReference"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_StorageOSVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a StorageOS persistent volume resource.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "volumeName": { - SchemaProps: spec.SchemaProps{ - Description: "volumeName is the human-readable name of the StorageOS volume. Volume names are only unique within a namespace.", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeNamespace": { - SchemaProps: spec.SchemaProps{ - Description: "volumeNamespace specifies the scope of the volume within StorageOS. If no namespace is specified then the Pod's namespace will be used. This allows the Kubernetes name scoping to be mirrored within StorageOS for tighter integration. Set VolumeName to any name to override the default behaviour. Set to \"default\" if you are not using namespaces within StorageOS. Namespaces that do not pre-exist within StorageOS will be created.", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef specifies the secret to use for obtaining the StorageOS API credentials. If not specified, default values will be attempted.", - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LocalObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_Sysctl(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Sysctl defines a kernel parameter to be set", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of a property to set", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "value": { - SchemaProps: spec.SchemaProps{ - Description: "Value of a property to set", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name", "value"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_TCPSocketAction(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "TCPSocketAction describes an action based on opening a socket", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "port": { - SchemaProps: spec.SchemaProps{ - Description: "Number or name of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.", - Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), - }, - }, - "host": { - SchemaProps: spec.SchemaProps{ - Description: "Optional: Host name to connect to, defaults to the pod IP.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"port"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/util/intstr.IntOrString"}, - } -} - -func schema_k8sio_api_core_v1_Taint(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "The node this Taint is attached to has the \"effect\" on any pod that does not tolerate the Taint.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "key": { - SchemaProps: spec.SchemaProps{ - Description: "Required. The taint key to be applied to a node.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "value": { - SchemaProps: spec.SchemaProps{ - Description: "The taint value corresponding to the taint key.", - Type: []string{"string"}, - Format: "", - }, - }, - "effect": { - SchemaProps: spec.SchemaProps{ - Description: "Required. The effect of the taint on pods that do not tolerate the taint. Valid effects are NoSchedule, PreferNoSchedule and NoExecute.\n\nPossible enum values:\n - `\"NoExecute\"` Evict any already-running pods that do not tolerate the taint. Currently enforced by NodeController.\n - `\"NoSchedule\"` Do not allow new pods to schedule onto the node unless they tolerate the taint, but allow all pods submitted to Kubelet without going through the scheduler to start, and allow all already-running pods to continue running. Enforced by the scheduler.\n - `\"PreferNoSchedule\"` Like TaintEffectNoSchedule, but the scheduler tries not to schedule new pods onto the node, rather than prohibiting new pods from scheduling onto the node entirely. Enforced by the scheduler.", - Default: "", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"NoExecute", "NoSchedule", "PreferNoSchedule"}, - }, - }, - "timeAdded": { - SchemaProps: spec.SchemaProps{ - Description: "TimeAdded represents the time at which the taint was added. It is only written for NoExecute taints.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - }, - Required: []string{"key", "effect"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_Toleration(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "The pod this Toleration is attached to tolerates any taint that matches the triple using the matching operator .", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "key": { - SchemaProps: spec.SchemaProps{ - Description: "Key is the taint key that the toleration applies to. Empty means match all taint keys. If the key is empty, operator must be Exists; this combination means to match all values and all keys.", - Type: []string{"string"}, - Format: "", - }, - }, - "operator": { - SchemaProps: spec.SchemaProps{ - Description: "Operator represents a key's relationship to the value. Valid operators are Exists and Equal. Defaults to Equal. Exists is equivalent to wildcard for value, so that a pod can tolerate all taints of a particular category.\n\nPossible enum values:\n - `\"Equal\"`\n - `\"Exists\"`", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Equal", "Exists"}, - }, - }, - "value": { - SchemaProps: spec.SchemaProps{ - Description: "Value is the taint value the toleration matches to. If the operator is Exists, the value should be empty, otherwise just a regular string.", - Type: []string{"string"}, - Format: "", - }, - }, - "effect": { - SchemaProps: spec.SchemaProps{ - Description: "Effect indicates the taint effect to match. Empty means match all taint effects. When specified, allowed values are NoSchedule, PreferNoSchedule and NoExecute.\n\nPossible enum values:\n - `\"NoExecute\"` Evict any already-running pods that do not tolerate the taint. Currently enforced by NodeController.\n - `\"NoSchedule\"` Do not allow new pods to schedule onto the node unless they tolerate the taint, but allow all pods submitted to Kubelet without going through the scheduler to start, and allow all already-running pods to continue running. Enforced by the scheduler.\n - `\"PreferNoSchedule\"` Like TaintEffectNoSchedule, but the scheduler tries not to schedule new pods onto the node, rather than prohibiting new pods from scheduling onto the node entirely. Enforced by the scheduler.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"NoExecute", "NoSchedule", "PreferNoSchedule"}, - }, - }, - "tolerationSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "TolerationSeconds represents the period of time the toleration (which must be of effect NoExecute, otherwise this field is ignored) tolerates the taint. By default, it is not set, which means tolerate the taint forever (do not evict). Zero and negative values will be treated as 0 (evict immediately) by the system.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_TopologySelectorLabelRequirement(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A topology selector requirement is a selector that matches given label. This is an alpha feature and may change in the future.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "key": { - SchemaProps: spec.SchemaProps{ - Description: "The label key that the selector applies to.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "values": { - SchemaProps: spec.SchemaProps{ - Description: "An array of string values. One value must match the label to be selected. Each entry in Values is ORed.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"key", "values"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_TopologySelectorTerm(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A topology selector term represents the result of label queries. A null or empty topology selector term matches no objects. The requirements of them are ANDed. It provides a subset of functionality as NodeSelectorTerm. This is an alpha feature and may change in the future.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "matchLabelExpressions": { - SchemaProps: spec.SchemaProps{ - Description: "A list of topology selector requirements by labels.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.TopologySelectorLabelRequirement"), - }, - }, - }, - }, - }, - }, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.TopologySelectorLabelRequirement"}, - } -} - -func schema_k8sio_api_core_v1_TopologySpreadConstraint(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "TopologySpreadConstraint specifies how to spread matching pods among the given topology.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "maxSkew": { - SchemaProps: spec.SchemaProps{ - Description: "MaxSkew describes the degree to which pods may be unevenly distributed. When `whenUnsatisfiable=DoNotSchedule`, it is the maximum permitted difference between the number of matching pods in the target topology and the global minimum. The global minimum is the minimum number of matching pods in an eligible domain or zero if the number of eligible domains is less than MinDomains. For example, in a 3-zone cluster, MaxSkew is set to 1, and pods with the same labelSelector spread as 2/2/1: In this case, the global minimum is 1. | zone1 | zone2 | zone3 | | P P | P P | P | - if MaxSkew is 1, incoming pod can only be scheduled to zone3 to become 2/2/2; scheduling it onto zone1(zone2) would make the ActualSkew(3-1) on zone1(zone2) violate MaxSkew(1). - if MaxSkew is 2, incoming pod can be scheduled onto any zone. When `whenUnsatisfiable=ScheduleAnyway`, it is used to give higher precedence to topologies that satisfy it. It's a required field. Default value is 1 and 0 is not allowed.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "topologyKey": { - SchemaProps: spec.SchemaProps{ - Description: "TopologyKey is the key of node labels. Nodes that have a label with this key and identical values are considered to be in the same topology. We consider each as a \"bucket\", and try to put balanced number of pods into each bucket. We define a domain as a particular instance of a topology. Also, we define an eligible domain as a domain whose nodes meet the requirements of nodeAffinityPolicy and nodeTaintsPolicy. e.g. If TopologyKey is \"kubernetes.io/hostname\", each Node is a domain of that topology. And, if TopologyKey is \"topology.kubernetes.io/zone\", each zone is a domain of that topology. It's a required field.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "whenUnsatisfiable": { - SchemaProps: spec.SchemaProps{ - Description: "WhenUnsatisfiable indicates how to deal with a pod if it doesn't satisfy the spread constraint. - DoNotSchedule (default) tells the scheduler not to schedule it. - ScheduleAnyway tells the scheduler to schedule the pod in any location,\n but giving higher precedence to topologies that would help reduce the\n skew.\nA constraint is considered \"Unsatisfiable\" for an incoming pod if and only if every possible node assignment for that pod would violate \"MaxSkew\" on some topology. For example, in a 3-zone cluster, MaxSkew is set to 1, and pods with the same labelSelector spread as 3/1/1: | zone1 | zone2 | zone3 | | P P P | P | P | If WhenUnsatisfiable is set to DoNotSchedule, incoming pod can only be scheduled to zone2(zone3) to become 3/2/1(3/1/2) as ActualSkew(2-1) on zone2(zone3) satisfies MaxSkew(1). In other words, the cluster can still be imbalanced, but scheduler won't make it *more* imbalanced. It's a required field.\n\nPossible enum values:\n - `\"DoNotSchedule\"` instructs the scheduler not to schedule the pod when constraints are not satisfied.\n - `\"ScheduleAnyway\"` instructs the scheduler to schedule the pod even if constraints are not satisfied.", - Default: "", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"DoNotSchedule", "ScheduleAnyway"}, - }, - }, - "labelSelector": { - SchemaProps: spec.SchemaProps{ - Description: "LabelSelector is used to find matching pods. Pods that match this label selector are counted to determine the number of pods in their corresponding topology domain.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), - }, - }, - "minDomains": { - SchemaProps: spec.SchemaProps{ - Description: "MinDomains indicates a minimum number of eligible domains. When the number of eligible domains with matching topology keys is less than minDomains, Pod Topology Spread treats \"global minimum\" as 0, and then the calculation of Skew is performed. And when the number of eligible domains with matching topology keys equals or greater than minDomains, this value has no effect on scheduling. As a result, when the number of eligible domains is less than minDomains, scheduler won't schedule more than maxSkew Pods to those domains. If value is nil, the constraint behaves as if MinDomains is equal to 1. Valid values are integers greater than 0. When value is not nil, WhenUnsatisfiable must be DoNotSchedule.\n\nFor example, in a 3-zone cluster, MaxSkew is set to 2, MinDomains is set to 5 and pods with the same labelSelector spread as 2/2/2: | zone1 | zone2 | zone3 | | P P | P P | P P | The number of domains is less than 5(MinDomains), so \"global minimum\" is treated as 0. In this situation, new pod with the same labelSelector cannot be scheduled, because computed skew will be 3(3 - 0) if new Pod is scheduled to any of the three zones, it will violate MaxSkew.\n\nThis is a beta field and requires the MinDomainsInPodTopologySpread feature gate to be enabled (enabled by default).", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "nodeAffinityPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "NodeAffinityPolicy indicates how we will treat Pod's nodeAffinity/nodeSelector when calculating pod topology spread skew. Options are: - Honor: only nodes matching nodeAffinity/nodeSelector are included in the calculations. - Ignore: nodeAffinity/nodeSelector are ignored. All nodes are included in the calculations.\n\nIf this value is nil, the behavior is equivalent to the Honor policy. This is a beta-level feature default enabled by the NodeInclusionPolicyInPodTopologySpread feature flag.\n\nPossible enum values:\n - `\"Honor\"` means use this scheduling directive when calculating pod topology spread skew.\n - `\"Ignore\"` means ignore this scheduling directive when calculating pod topology spread skew.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Honor", "Ignore"}, - }, - }, - "nodeTaintsPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "NodeTaintsPolicy indicates how we will treat node taints when calculating pod topology spread skew. Options are: - Honor: nodes without taints, along with tainted nodes for which the incoming pod has a toleration, are included. - Ignore: node taints are ignored. All nodes are included.\n\nIf this value is nil, the behavior is equivalent to the Ignore policy. This is a beta-level feature default enabled by the NodeInclusionPolicyInPodTopologySpread feature flag.\n\nPossible enum values:\n - `\"Honor\"` means use this scheduling directive when calculating pod topology spread skew.\n - `\"Ignore\"` means ignore this scheduling directive when calculating pod topology spread skew.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Honor", "Ignore"}, - }, - }, - "matchLabelKeys": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "MatchLabelKeys is a set of pod label keys to select the pods over which spreading will be calculated. The keys are used to lookup values from the incoming pod labels, those key-value labels are ANDed with labelSelector to select the group of existing pods over which spreading will be calculated for the incoming pod. The same key is forbidden to exist in both MatchLabelKeys and LabelSelector. MatchLabelKeys cannot be set when LabelSelector isn't set. Keys that don't exist in the incoming pod labels will be ignored. A null or empty list means only match against labelSelector.\n\nThis is a beta field and requires the MatchLabelKeysInPodTopologySpread feature gate to be enabled (enabled by default).", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"maxSkew", "topologyKey", "whenUnsatisfiable"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"}, - } -} - -func schema_k8sio_api_core_v1_TypedLocalObjectReference(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "TypedLocalObjectReference contains enough information to let you locate the typed referenced object inside the same namespace.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "apiGroup": { - SchemaProps: spec.SchemaProps{ - Description: "APIGroup is the group for the resource being referenced. If APIGroup is not specified, the specified Kind must be in the core API group. For any other third-party types, APIGroup is required.", - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is the type of resource being referenced", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name is the name of resource being referenced", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"kind", "name"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_TypedObjectReference(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "apiGroup": { - SchemaProps: spec.SchemaProps{ - Description: "APIGroup is the group for the resource being referenced. If APIGroup is not specified, the specified Kind must be in the core API group. For any other third-party types, APIGroup is required.", - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is the type of resource being referenced", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name is the name of resource being referenced", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "namespace": { - SchemaProps: spec.SchemaProps{ - Description: "Namespace is the namespace of resource being referenced Note that when a namespace is specified, a gateway.networking.k8s.io/ReferenceGrant object is required in the referent namespace to allow that namespace's owner to accept the reference. See the ReferenceGrant documentation for details. (Alpha) This field requires the CrossNamespaceVolumeDataSource feature gate to be enabled.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"kind", "name"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_Volume(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Volume represents a named volume in a pod that may be accessed by any container in the pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "name of the volume. Must be a DNS_LABEL and unique within the pod. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "hostPath": { - SchemaProps: spec.SchemaProps{ - Description: "hostPath represents a pre-existing file or directory on the host machine that is directly exposed to the container. This is generally used for system agents or other privileged things that are allowed to see the host machine. Most containers will NOT need this. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath", - Ref: ref("k8s.io/api/core/v1.HostPathVolumeSource"), - }, - }, - "emptyDir": { - SchemaProps: spec.SchemaProps{ - Description: "emptyDir represents a temporary directory that shares a pod's lifetime. More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir", - Ref: ref("k8s.io/api/core/v1.EmptyDirVolumeSource"), - }, - }, - "gcePersistentDisk": { - SchemaProps: spec.SchemaProps{ - Description: "gcePersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", - Ref: ref("k8s.io/api/core/v1.GCEPersistentDiskVolumeSource"), - }, - }, - "awsElasticBlockStore": { - SchemaProps: spec.SchemaProps{ - Description: "awsElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore", - Ref: ref("k8s.io/api/core/v1.AWSElasticBlockStoreVolumeSource"), - }, - }, - "gitRepo": { - SchemaProps: spec.SchemaProps{ - Description: "gitRepo represents a git repository at a particular revision. DEPRECATED: GitRepo is deprecated. To provision a container with a git repo, mount an EmptyDir into an InitContainer that clones the repo using git, then mount the EmptyDir into the Pod's container.", - Ref: ref("k8s.io/api/core/v1.GitRepoVolumeSource"), - }, - }, - "secret": { - SchemaProps: spec.SchemaProps{ - Description: "secret represents a secret that should populate this volume. More info: https://kubernetes.io/docs/concepts/storage/volumes#secret", - Ref: ref("k8s.io/api/core/v1.SecretVolumeSource"), - }, - }, - "nfs": { - SchemaProps: spec.SchemaProps{ - Description: "nfs represents an NFS mount on the host that shares a pod's lifetime More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs", - Ref: ref("k8s.io/api/core/v1.NFSVolumeSource"), - }, - }, - "iscsi": { - SchemaProps: spec.SchemaProps{ - Description: "iscsi represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://examples.k8s.io/volumes/iscsi/README.md", - Ref: ref("k8s.io/api/core/v1.ISCSIVolumeSource"), - }, - }, - "glusterfs": { - SchemaProps: spec.SchemaProps{ - Description: "glusterfs represents a Glusterfs mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/glusterfs/README.md", - Ref: ref("k8s.io/api/core/v1.GlusterfsVolumeSource"), - }, - }, - "persistentVolumeClaim": { - SchemaProps: spec.SchemaProps{ - Description: "persistentVolumeClaimVolumeSource represents a reference to a PersistentVolumeClaim in the same namespace. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims", - Ref: ref("k8s.io/api/core/v1.PersistentVolumeClaimVolumeSource"), - }, - }, - "rbd": { - SchemaProps: spec.SchemaProps{ - Description: "rbd represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/rbd/README.md", - Ref: ref("k8s.io/api/core/v1.RBDVolumeSource"), - }, - }, - "flexVolume": { - SchemaProps: spec.SchemaProps{ - Description: "flexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin.", - Ref: ref("k8s.io/api/core/v1.FlexVolumeSource"), - }, - }, - "cinder": { - SchemaProps: spec.SchemaProps{ - Description: "cinder represents a cinder volume attached and mounted on kubelets host machine. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - Ref: ref("k8s.io/api/core/v1.CinderVolumeSource"), - }, - }, - "cephfs": { - SchemaProps: spec.SchemaProps{ - Description: "cephFS represents a Ceph FS mount on the host that shares a pod's lifetime", - Ref: ref("k8s.io/api/core/v1.CephFSVolumeSource"), - }, - }, - "flocker": { - SchemaProps: spec.SchemaProps{ - Description: "flocker represents a Flocker volume attached to a kubelet's host machine. This depends on the Flocker control service being running", - Ref: ref("k8s.io/api/core/v1.FlockerVolumeSource"), - }, - }, - "downwardAPI": { - SchemaProps: spec.SchemaProps{ - Description: "downwardAPI represents downward API about the pod that should populate this volume", - Ref: ref("k8s.io/api/core/v1.DownwardAPIVolumeSource"), - }, - }, - "fc": { - SchemaProps: spec.SchemaProps{ - Description: "fc represents a Fibre Channel resource that is attached to a kubelet's host machine and then exposed to the pod.", - Ref: ref("k8s.io/api/core/v1.FCVolumeSource"), - }, - }, - "azureFile": { - SchemaProps: spec.SchemaProps{ - Description: "azureFile represents an Azure File Service mount on the host and bind mount to the pod.", - Ref: ref("k8s.io/api/core/v1.AzureFileVolumeSource"), - }, - }, - "configMap": { - SchemaProps: spec.SchemaProps{ - Description: "configMap represents a configMap that should populate this volume", - Ref: ref("k8s.io/api/core/v1.ConfigMapVolumeSource"), - }, - }, - "vsphereVolume": { - SchemaProps: spec.SchemaProps{ - Description: "vsphereVolume represents a vSphere volume attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.VsphereVirtualDiskVolumeSource"), - }, - }, - "quobyte": { - SchemaProps: spec.SchemaProps{ - Description: "quobyte represents a Quobyte mount on the host that shares a pod's lifetime", - Ref: ref("k8s.io/api/core/v1.QuobyteVolumeSource"), - }, - }, - "azureDisk": { - SchemaProps: spec.SchemaProps{ - Description: "azureDisk represents an Azure Data Disk mount on the host and bind mount to the pod.", - Ref: ref("k8s.io/api/core/v1.AzureDiskVolumeSource"), - }, - }, - "photonPersistentDisk": { - SchemaProps: spec.SchemaProps{ - Description: "photonPersistentDisk represents a PhotonController persistent disk attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.PhotonPersistentDiskVolumeSource"), - }, - }, - "projected": { - SchemaProps: spec.SchemaProps{ - Description: "projected items for all in one resources secrets, configmaps, and downward API", - Ref: ref("k8s.io/api/core/v1.ProjectedVolumeSource"), - }, - }, - "portworxVolume": { - SchemaProps: spec.SchemaProps{ - Description: "portworxVolume represents a portworx volume attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.PortworxVolumeSource"), - }, - }, - "scaleIO": { - SchemaProps: spec.SchemaProps{ - Description: "scaleIO represents a ScaleIO persistent volume attached and mounted on Kubernetes nodes.", - Ref: ref("k8s.io/api/core/v1.ScaleIOVolumeSource"), - }, - }, - "storageos": { - SchemaProps: spec.SchemaProps{ - Description: "storageOS represents a StorageOS volume attached and mounted on Kubernetes nodes.", - Ref: ref("k8s.io/api/core/v1.StorageOSVolumeSource"), - }, - }, - "csi": { - SchemaProps: spec.SchemaProps{ - Description: "csi (Container Storage Interface) represents ephemeral storage that is handled by certain external CSI drivers (Beta feature).", - Ref: ref("k8s.io/api/core/v1.CSIVolumeSource"), - }, - }, - "ephemeral": { - SchemaProps: spec.SchemaProps{ - Description: "ephemeral represents a volume that is handled by a cluster storage driver. The volume's lifecycle is tied to the pod that defines it - it will be created before the pod starts, and deleted when the pod is removed.\n\nUse this if: a) the volume is only needed while the pod runs, b) features of normal volumes like restoring from snapshot or capacity\n tracking are needed,\nc) the storage driver is specified through a storage class, and d) the storage driver supports dynamic volume provisioning through\n a PersistentVolumeClaim (see EphemeralVolumeSource for more\n information on the connection between this volume type\n and PersistentVolumeClaim).\n\nUse PersistentVolumeClaim or one of the vendor-specific APIs for volumes that persist for longer than the lifecycle of an individual pod.\n\nUse CSI for light-weight local ephemeral volumes if the CSI driver is meant to be used that way - see the documentation of the driver for more information.\n\nA pod can use both types of ephemeral volumes and persistent volumes at the same time.", - Ref: ref("k8s.io/api/core/v1.EphemeralVolumeSource"), - }, - }, - }, - Required: []string{"name"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.AWSElasticBlockStoreVolumeSource", "k8s.io/api/core/v1.AzureDiskVolumeSource", "k8s.io/api/core/v1.AzureFileVolumeSource", "k8s.io/api/core/v1.CSIVolumeSource", "k8s.io/api/core/v1.CephFSVolumeSource", "k8s.io/api/core/v1.CinderVolumeSource", "k8s.io/api/core/v1.ConfigMapVolumeSource", "k8s.io/api/core/v1.DownwardAPIVolumeSource", "k8s.io/api/core/v1.EmptyDirVolumeSource", "k8s.io/api/core/v1.EphemeralVolumeSource", "k8s.io/api/core/v1.FCVolumeSource", "k8s.io/api/core/v1.FlexVolumeSource", "k8s.io/api/core/v1.FlockerVolumeSource", "k8s.io/api/core/v1.GCEPersistentDiskVolumeSource", "k8s.io/api/core/v1.GitRepoVolumeSource", "k8s.io/api/core/v1.GlusterfsVolumeSource", "k8s.io/api/core/v1.HostPathVolumeSource", "k8s.io/api/core/v1.ISCSIVolumeSource", "k8s.io/api/core/v1.NFSVolumeSource", "k8s.io/api/core/v1.PersistentVolumeClaimVolumeSource", "k8s.io/api/core/v1.PhotonPersistentDiskVolumeSource", "k8s.io/api/core/v1.PortworxVolumeSource", "k8s.io/api/core/v1.ProjectedVolumeSource", "k8s.io/api/core/v1.QuobyteVolumeSource", "k8s.io/api/core/v1.RBDVolumeSource", "k8s.io/api/core/v1.ScaleIOVolumeSource", "k8s.io/api/core/v1.SecretVolumeSource", "k8s.io/api/core/v1.StorageOSVolumeSource", "k8s.io/api/core/v1.VsphereVirtualDiskVolumeSource"}, - } -} - -func schema_k8sio_api_core_v1_VolumeDevice(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "volumeDevice describes a mapping of a raw block device within a container.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "name must match the name of a persistentVolumeClaim in the pod", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "devicePath": { - SchemaProps: spec.SchemaProps{ - Description: "devicePath is the path inside of the container that the device will be mapped to.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name", "devicePath"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_VolumeMount(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "VolumeMount describes a mounting of a Volume within a container.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "This must match the Name of a Volume.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "Mounted read-only if true, read-write otherwise (false or unspecified). Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "mountPath": { - SchemaProps: spec.SchemaProps{ - Description: "Path within the container at which the volume should be mounted. Must not contain ':'.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "subPath": { - SchemaProps: spec.SchemaProps{ - Description: "Path within the volume from which the container's volume should be mounted. Defaults to \"\" (volume's root).", - Type: []string{"string"}, - Format: "", - }, - }, - "mountPropagation": { - SchemaProps: spec.SchemaProps{ - Description: "mountPropagation determines how mounts are propagated from the host to container and the other way around. When not set, MountPropagationNone is used. This field is beta in 1.10.\n\nPossible enum values:\n - `\"Bidirectional\"` means that the volume in a container will receive new mounts from the host or other containers, and its own mounts will be propagated from the container to the host or other containers. Note that this mode is recursively applied to all mounts in the volume (\"rshared\" in Linux terminology).\n - `\"HostToContainer\"` means that the volume in a container will receive new mounts from the host or other containers, but filesystems mounted inside the container won't be propagated to the host or other containers. Note that this mode is recursively applied to all mounts in the volume (\"rslave\" in Linux terminology).\n - `\"None\"` means that the volume in a container will not receive new mounts from the host or other containers, and filesystems mounted inside the container won't be propagated to the host or other containers. Note that this mode corresponds to \"private\" in Linux terminology.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Bidirectional", "HostToContainer", "None"}, - }, - }, - "subPathExpr": { - SchemaProps: spec.SchemaProps{ - Description: "Expanded path within the volume from which the container's volume should be mounted. Behaves similarly to SubPath but environment variable references $(VAR_NAME) are expanded using the container's environment. Defaults to \"\" (volume's root). SubPathExpr and SubPath are mutually exclusive.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name", "mountPath"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_VolumeNodeAffinity(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "VolumeNodeAffinity defines constraints that limit what nodes this volume can be accessed from.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "required": { - SchemaProps: spec.SchemaProps{ - Description: "required specifies hard node constraints that must be met.", - Ref: ref("k8s.io/api/core/v1.NodeSelector"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NodeSelector"}, - } -} - -func schema_k8sio_api_core_v1_VolumeProjection(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Projection that may be projected along with other supported volume types", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "secret": { - SchemaProps: spec.SchemaProps{ - Description: "secret information about the secret data to project", - Ref: ref("k8s.io/api/core/v1.SecretProjection"), - }, - }, - "downwardAPI": { - SchemaProps: spec.SchemaProps{ - Description: "downwardAPI information about the downwardAPI data to project", - Ref: ref("k8s.io/api/core/v1.DownwardAPIProjection"), - }, - }, - "configMap": { - SchemaProps: spec.SchemaProps{ - Description: "configMap information about the configMap data to project", - Ref: ref("k8s.io/api/core/v1.ConfigMapProjection"), - }, - }, - "serviceAccountToken": { - SchemaProps: spec.SchemaProps{ - Description: "serviceAccountToken is information about the serviceAccountToken data to project", - Ref: ref("k8s.io/api/core/v1.ServiceAccountTokenProjection"), - }, - }, - "clusterTrustBundle": { - SchemaProps: spec.SchemaProps{ - Description: "ClusterTrustBundle allows a pod to access the `.spec.trustBundle` field of ClusterTrustBundle objects in an auto-updating file.\n\nAlpha, gated by the ClusterTrustBundleProjection feature gate.\n\nClusterTrustBundle objects can either be selected by name, or by the combination of signer name and a label selector.\n\nKubelet performs aggressive normalization of the PEM contents written into the pod filesystem. Esoteric PEM features such as inter-block comments and block headers are stripped. Certificates are deduplicated. The ordering of certificates within the file is arbitrary, and Kubelet may change the order over time.", - Ref: ref("k8s.io/api/core/v1.ClusterTrustBundleProjection"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ClusterTrustBundleProjection", "k8s.io/api/core/v1.ConfigMapProjection", "k8s.io/api/core/v1.DownwardAPIProjection", "k8s.io/api/core/v1.SecretProjection", "k8s.io/api/core/v1.ServiceAccountTokenProjection"}, - } -} - -func schema_k8sio_api_core_v1_VolumeResourceRequirements(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "VolumeResourceRequirements describes the storage resource requirements for a volume.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "limits": { - SchemaProps: spec.SchemaProps{ - Description: "Limits describes the maximum amount of compute resources allowed. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "requests": { - SchemaProps: spec.SchemaProps{ - Description: "Requests describes the minimum amount of compute resources required. If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value. Requests cannot exceed Limits. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_VolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents the source of a volume to mount. Only one of its members may be specified.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "hostPath": { - SchemaProps: spec.SchemaProps{ - Description: "hostPath represents a pre-existing file or directory on the host machine that is directly exposed to the container. This is generally used for system agents or other privileged things that are allowed to see the host machine. Most containers will NOT need this. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath", - Ref: ref("k8s.io/api/core/v1.HostPathVolumeSource"), - }, - }, - "emptyDir": { - SchemaProps: spec.SchemaProps{ - Description: "emptyDir represents a temporary directory that shares a pod's lifetime. More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir", - Ref: ref("k8s.io/api/core/v1.EmptyDirVolumeSource"), - }, - }, - "gcePersistentDisk": { - SchemaProps: spec.SchemaProps{ - Description: "gcePersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", - Ref: ref("k8s.io/api/core/v1.GCEPersistentDiskVolumeSource"), - }, - }, - "awsElasticBlockStore": { - SchemaProps: spec.SchemaProps{ - Description: "awsElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore", - Ref: ref("k8s.io/api/core/v1.AWSElasticBlockStoreVolumeSource"), - }, - }, - "gitRepo": { - SchemaProps: spec.SchemaProps{ - Description: "gitRepo represents a git repository at a particular revision. DEPRECATED: GitRepo is deprecated. To provision a container with a git repo, mount an EmptyDir into an InitContainer that clones the repo using git, then mount the EmptyDir into the Pod's container.", - Ref: ref("k8s.io/api/core/v1.GitRepoVolumeSource"), - }, - }, - "secret": { - SchemaProps: spec.SchemaProps{ - Description: "secret represents a secret that should populate this volume. More info: https://kubernetes.io/docs/concepts/storage/volumes#secret", - Ref: ref("k8s.io/api/core/v1.SecretVolumeSource"), - }, - }, - "nfs": { - SchemaProps: spec.SchemaProps{ - Description: "nfs represents an NFS mount on the host that shares a pod's lifetime More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs", - Ref: ref("k8s.io/api/core/v1.NFSVolumeSource"), - }, - }, - "iscsi": { - SchemaProps: spec.SchemaProps{ - Description: "iscsi represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://examples.k8s.io/volumes/iscsi/README.md", - Ref: ref("k8s.io/api/core/v1.ISCSIVolumeSource"), - }, - }, - "glusterfs": { - SchemaProps: spec.SchemaProps{ - Description: "glusterfs represents a Glusterfs mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/glusterfs/README.md", - Ref: ref("k8s.io/api/core/v1.GlusterfsVolumeSource"), - }, - }, - "persistentVolumeClaim": { - SchemaProps: spec.SchemaProps{ - Description: "persistentVolumeClaimVolumeSource represents a reference to a PersistentVolumeClaim in the same namespace. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims", - Ref: ref("k8s.io/api/core/v1.PersistentVolumeClaimVolumeSource"), - }, - }, - "rbd": { - SchemaProps: spec.SchemaProps{ - Description: "rbd represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/rbd/README.md", - Ref: ref("k8s.io/api/core/v1.RBDVolumeSource"), - }, - }, - "flexVolume": { - SchemaProps: spec.SchemaProps{ - Description: "flexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin.", - Ref: ref("k8s.io/api/core/v1.FlexVolumeSource"), - }, - }, - "cinder": { - SchemaProps: spec.SchemaProps{ - Description: "cinder represents a cinder volume attached and mounted on kubelets host machine. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - Ref: ref("k8s.io/api/core/v1.CinderVolumeSource"), - }, - }, - "cephfs": { - SchemaProps: spec.SchemaProps{ - Description: "cephFS represents a Ceph FS mount on the host that shares a pod's lifetime", - Ref: ref("k8s.io/api/core/v1.CephFSVolumeSource"), - }, - }, - "flocker": { - SchemaProps: spec.SchemaProps{ - Description: "flocker represents a Flocker volume attached to a kubelet's host machine. This depends on the Flocker control service being running", - Ref: ref("k8s.io/api/core/v1.FlockerVolumeSource"), - }, - }, - "downwardAPI": { - SchemaProps: spec.SchemaProps{ - Description: "downwardAPI represents downward API about the pod that should populate this volume", - Ref: ref("k8s.io/api/core/v1.DownwardAPIVolumeSource"), - }, - }, - "fc": { - SchemaProps: spec.SchemaProps{ - Description: "fc represents a Fibre Channel resource that is attached to a kubelet's host machine and then exposed to the pod.", - Ref: ref("k8s.io/api/core/v1.FCVolumeSource"), - }, - }, - "azureFile": { - SchemaProps: spec.SchemaProps{ - Description: "azureFile represents an Azure File Service mount on the host and bind mount to the pod.", - Ref: ref("k8s.io/api/core/v1.AzureFileVolumeSource"), - }, - }, - "configMap": { - SchemaProps: spec.SchemaProps{ - Description: "configMap represents a configMap that should populate this volume", - Ref: ref("k8s.io/api/core/v1.ConfigMapVolumeSource"), - }, - }, - "vsphereVolume": { - SchemaProps: spec.SchemaProps{ - Description: "vsphereVolume represents a vSphere volume attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.VsphereVirtualDiskVolumeSource"), - }, - }, - "quobyte": { - SchemaProps: spec.SchemaProps{ - Description: "quobyte represents a Quobyte mount on the host that shares a pod's lifetime", - Ref: ref("k8s.io/api/core/v1.QuobyteVolumeSource"), - }, - }, - "azureDisk": { - SchemaProps: spec.SchemaProps{ - Description: "azureDisk represents an Azure Data Disk mount on the host and bind mount to the pod.", - Ref: ref("k8s.io/api/core/v1.AzureDiskVolumeSource"), - }, - }, - "photonPersistentDisk": { - SchemaProps: spec.SchemaProps{ - Description: "photonPersistentDisk represents a PhotonController persistent disk attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.PhotonPersistentDiskVolumeSource"), - }, - }, - "projected": { - SchemaProps: spec.SchemaProps{ - Description: "projected items for all in one resources secrets, configmaps, and downward API", - Ref: ref("k8s.io/api/core/v1.ProjectedVolumeSource"), - }, - }, - "portworxVolume": { - SchemaProps: spec.SchemaProps{ - Description: "portworxVolume represents a portworx volume attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.PortworxVolumeSource"), - }, - }, - "scaleIO": { - SchemaProps: spec.SchemaProps{ - Description: "scaleIO represents a ScaleIO persistent volume attached and mounted on Kubernetes nodes.", - Ref: ref("k8s.io/api/core/v1.ScaleIOVolumeSource"), - }, - }, - "storageos": { - SchemaProps: spec.SchemaProps{ - Description: "storageOS represents a StorageOS volume attached and mounted on Kubernetes nodes.", - Ref: ref("k8s.io/api/core/v1.StorageOSVolumeSource"), - }, - }, - "csi": { - SchemaProps: spec.SchemaProps{ - Description: "csi (Container Storage Interface) represents ephemeral storage that is handled by certain external CSI drivers (Beta feature).", - Ref: ref("k8s.io/api/core/v1.CSIVolumeSource"), - }, - }, - "ephemeral": { - SchemaProps: spec.SchemaProps{ - Description: "ephemeral represents a volume that is handled by a cluster storage driver. The volume's lifecycle is tied to the pod that defines it - it will be created before the pod starts, and deleted when the pod is removed.\n\nUse this if: a) the volume is only needed while the pod runs, b) features of normal volumes like restoring from snapshot or capacity\n tracking are needed,\nc) the storage driver is specified through a storage class, and d) the storage driver supports dynamic volume provisioning through\n a PersistentVolumeClaim (see EphemeralVolumeSource for more\n information on the connection between this volume type\n and PersistentVolumeClaim).\n\nUse PersistentVolumeClaim or one of the vendor-specific APIs for volumes that persist for longer than the lifecycle of an individual pod.\n\nUse CSI for light-weight local ephemeral volumes if the CSI driver is meant to be used that way - see the documentation of the driver for more information.\n\nA pod can use both types of ephemeral volumes and persistent volumes at the same time.", - Ref: ref("k8s.io/api/core/v1.EphemeralVolumeSource"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.AWSElasticBlockStoreVolumeSource", "k8s.io/api/core/v1.AzureDiskVolumeSource", "k8s.io/api/core/v1.AzureFileVolumeSource", "k8s.io/api/core/v1.CSIVolumeSource", "k8s.io/api/core/v1.CephFSVolumeSource", "k8s.io/api/core/v1.CinderVolumeSource", "k8s.io/api/core/v1.ConfigMapVolumeSource", "k8s.io/api/core/v1.DownwardAPIVolumeSource", "k8s.io/api/core/v1.EmptyDirVolumeSource", "k8s.io/api/core/v1.EphemeralVolumeSource", "k8s.io/api/core/v1.FCVolumeSource", "k8s.io/api/core/v1.FlexVolumeSource", "k8s.io/api/core/v1.FlockerVolumeSource", "k8s.io/api/core/v1.GCEPersistentDiskVolumeSource", "k8s.io/api/core/v1.GitRepoVolumeSource", "k8s.io/api/core/v1.GlusterfsVolumeSource", "k8s.io/api/core/v1.HostPathVolumeSource", "k8s.io/api/core/v1.ISCSIVolumeSource", "k8s.io/api/core/v1.NFSVolumeSource", "k8s.io/api/core/v1.PersistentVolumeClaimVolumeSource", "k8s.io/api/core/v1.PhotonPersistentDiskVolumeSource", "k8s.io/api/core/v1.PortworxVolumeSource", "k8s.io/api/core/v1.ProjectedVolumeSource", "k8s.io/api/core/v1.QuobyteVolumeSource", "k8s.io/api/core/v1.RBDVolumeSource", "k8s.io/api/core/v1.ScaleIOVolumeSource", "k8s.io/api/core/v1.SecretVolumeSource", "k8s.io/api/core/v1.StorageOSVolumeSource", "k8s.io/api/core/v1.VsphereVirtualDiskVolumeSource"}, - } -} - -func schema_k8sio_api_core_v1_VsphereVirtualDiskVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a vSphere volume resource.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "volumePath": { - SchemaProps: spec.SchemaProps{ - Description: "volumePath is the path that identifies vSphere volume vmdk", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - Type: []string{"string"}, - Format: "", - }, - }, - "storagePolicyName": { - SchemaProps: spec.SchemaProps{ - Description: "storagePolicyName is the storage Policy Based Management (SPBM) profile name.", - Type: []string{"string"}, - Format: "", - }, - }, - "storagePolicyID": { - SchemaProps: spec.SchemaProps{ - Description: "storagePolicyID is the storage Policy Based Management (SPBM) profile ID associated with the StoragePolicyName.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"volumePath"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_WeightedPodAffinityTerm(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "The weights of all of the matched WeightedPodAffinityTerm fields are added per-node to find the most preferred node(s)", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "weight": { - SchemaProps: spec.SchemaProps{ - Description: "weight associated with matching the corresponding podAffinityTerm, in the range 1-100.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "podAffinityTerm": { - SchemaProps: spec.SchemaProps{ - Description: "Required. A pod affinity term, associated with the corresponding weight.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodAffinityTerm"), - }, - }, - }, - Required: []string{"weight", "podAffinityTerm"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodAffinityTerm"}, - } -} - -func schema_k8sio_api_core_v1_WindowsSecurityContextOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "WindowsSecurityContextOptions contain Windows-specific options and credentials.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "gmsaCredentialSpecName": { - SchemaProps: spec.SchemaProps{ - Description: "GMSACredentialSpecName is the name of the GMSA credential spec to use.", - Type: []string{"string"}, - Format: "", - }, - }, - "gmsaCredentialSpec": { - SchemaProps: spec.SchemaProps{ - Description: "GMSACredentialSpec is where the GMSA admission webhook (https://github.com/kubernetes-sigs/windows-gmsa) inlines the contents of the GMSA credential spec named by the GMSACredentialSpecName field.", - Type: []string{"string"}, - Format: "", - }, - }, - "runAsUserName": { - SchemaProps: spec.SchemaProps{ - Description: "The UserName in Windows to run the entrypoint of the container process. Defaults to the user specified in image metadata if unspecified. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.", - Type: []string{"string"}, - Format: "", - }, - }, - "hostProcess": { - SchemaProps: spec.SchemaProps{ - Description: "HostProcess determines if a container should be run as a 'Host Process' container. All of a Pod's containers must have the same effective HostProcess value (it is not allowed to have a mix of HostProcess containers and non-HostProcess containers). In addition, if HostProcess is true then HostNetwork must also be set to true.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_rbac_v1_AggregationRule(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "AggregationRule describes how to locate ClusterRoles to aggregate into the ClusterRole", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "clusterRoleSelectors": { - SchemaProps: spec.SchemaProps{ - Description: "ClusterRoleSelectors holds a list of selectors which will be used to find ClusterRoles and create the rules. If any of the selectors match, then the ClusterRole's permissions will be added", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"}, - } -} - -func schema_k8sio_api_rbac_v1_ClusterRole(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ClusterRole is a cluster level, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding or ClusterRoleBinding.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "rules": { - SchemaProps: spec.SchemaProps{ - Description: "Rules holds all the PolicyRules for this ClusterRole", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/rbac/v1.PolicyRule"), - }, - }, - }, - }, - }, - "aggregationRule": { - SchemaProps: spec.SchemaProps{ - Description: "AggregationRule is an optional field that describes how to build the Rules for this ClusterRole. If AggregationRule is set, then the Rules are controller managed and direct changes to Rules will be stomped by the controller.", - Ref: ref("k8s.io/api/rbac/v1.AggregationRule"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/rbac/v1.AggregationRule", "k8s.io/api/rbac/v1.PolicyRule", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_rbac_v1_ClusterRoleBinding(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ClusterRoleBinding references a ClusterRole, but not contain it. It can reference a ClusterRole in the global namespace, and adds who information via Subject.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "subjects": { - SchemaProps: spec.SchemaProps{ - Description: "Subjects holds references to the objects the role applies to.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/rbac/v1.Subject"), - }, - }, - }, - }, - }, - "roleRef": { - SchemaProps: spec.SchemaProps{ - Description: "RoleRef can only reference a ClusterRole in the global namespace. If the RoleRef cannot be resolved, the Authorizer must return an error. This field is immutable.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/rbac/v1.RoleRef"), - }, - }, - }, - Required: []string{"roleRef"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/rbac/v1.RoleRef", "k8s.io/api/rbac/v1.Subject", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_rbac_v1_ClusterRoleBindingList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ClusterRoleBindingList is a collection of ClusterRoleBindings", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is a list of ClusterRoleBindings", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/rbac/v1.ClusterRoleBinding"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/rbac/v1.ClusterRoleBinding", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_rbac_v1_ClusterRoleList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ClusterRoleList is a collection of ClusterRoles", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is a list of ClusterRoles", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/rbac/v1.ClusterRole"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/rbac/v1.ClusterRole", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_rbac_v1_PolicyRule(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PolicyRule holds information that describes a policy rule, but does not contain information about who the rule applies to or which namespace the rule applies to.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "verbs": { - SchemaProps: spec.SchemaProps{ - Description: "Verbs is a list of Verbs that apply to ALL the ResourceKinds contained in this rule. '*' represents all verbs.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "apiGroups": { - SchemaProps: spec.SchemaProps{ - Description: "APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed. \"\" represents the core API group and \"*\" represents all API groups.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "resources": { - SchemaProps: spec.SchemaProps{ - Description: "Resources is a list of resources this rule applies to. '*' represents all resources.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "resourceNames": { - SchemaProps: spec.SchemaProps{ - Description: "ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "nonResourceURLs": { - SchemaProps: spec.SchemaProps{ - Description: "NonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path Since non-resource URLs are not namespaced, this field is only applicable for ClusterRoles referenced from a ClusterRoleBinding. Rules can either apply to API resources (such as \"pods\" or \"secrets\") or non-resource URL paths (such as \"/api\"), but not both.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"verbs"}, - }, - }, - } -} - -func schema_k8sio_api_rbac_v1_Role(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Role is a namespaced, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "rules": { - SchemaProps: spec.SchemaProps{ - Description: "Rules holds all the PolicyRules for this Role", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/rbac/v1.PolicyRule"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/rbac/v1.PolicyRule", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_rbac_v1_RoleBinding(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "RoleBinding references a role, but does not contain it. It can reference a Role in the same namespace or a ClusterRole in the global namespace. It adds who information via Subjects and namespace information by which namespace it exists in. RoleBindings in a given namespace only have effect in that namespace.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "subjects": { - SchemaProps: spec.SchemaProps{ - Description: "Subjects holds references to the objects the role applies to.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/rbac/v1.Subject"), - }, - }, - }, - }, - }, - "roleRef": { - SchemaProps: spec.SchemaProps{ - Description: "RoleRef can reference a Role in the current namespace or a ClusterRole in the global namespace. If the RoleRef cannot be resolved, the Authorizer must return an error. This field is immutable.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/rbac/v1.RoleRef"), - }, - }, - }, - Required: []string{"roleRef"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/rbac/v1.RoleRef", "k8s.io/api/rbac/v1.Subject", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_rbac_v1_RoleBindingList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "RoleBindingList is a collection of RoleBindings", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is a list of RoleBindings", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/rbac/v1.RoleBinding"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/rbac/v1.RoleBinding", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_rbac_v1_RoleList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "RoleList is a collection of Roles", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is a list of Roles", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/rbac/v1.Role"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/rbac/v1.Role", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_rbac_v1_RoleRef(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "RoleRef contains information that points to the role being used", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "apiGroup": { - SchemaProps: spec.SchemaProps{ - Description: "APIGroup is the group for the resource being referenced", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is the type of resource being referenced", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name is the name of resource being referenced", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"apiGroup", "kind", "name"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - } -} - -func schema_k8sio_api_rbac_v1_Subject(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Subject contains a reference to the object or user identities a role binding applies to. This can either hold a direct API object reference, or a value for non-objects such as user and group names.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind of object being referenced. Values defined by this API group are \"User\", \"Group\", and \"ServiceAccount\". If the Authorizer does not recognized the kind value, the Authorizer should report an error.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "apiGroup": { - SchemaProps: spec.SchemaProps{ - Description: "APIGroup holds the API group of the referenced subject. Defaults to \"\" for ServiceAccount subjects. Defaults to \"rbac.authorization.k8s.io\" for User and Group subjects.", - Type: []string{"string"}, - Format: "", - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the object being referenced.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "namespace": { - SchemaProps: spec.SchemaProps{ - Description: "Namespace of the referenced object. If the object kind is non-namespace, such as \"User\" or \"Group\", and this value is not empty the Authorizer should report an error.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"kind", "name"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - } -} - -func schema_apimachinery_pkg_api_resource_Quantity(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.EmbedOpenAPIDefinitionIntoV2Extension(common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Quantity is a fixed-point representation of a number. It provides convenient marshaling/unmarshaling in JSON and YAML, in addition to String() and AsInt64() accessors.\n\nThe serialization format is:\n\n``` ::= \n\n\t(Note that may be empty, from the \"\" case in .)\n\n ::= 0 | 1 | ... | 9 ::= | ::= | . | . | . ::= \"+\" | \"-\" ::= | ::= | | ::= Ki | Mi | Gi | Ti | Pi | Ei\n\n\t(International System of units; See: http://physics.nist.gov/cuu/Units/binary.html)\n\n ::= m | \"\" | k | M | G | T | P | E\n\n\t(Note that 1024 = 1Ki but 1000 = 1k; I didn't choose the capitalization.)\n\n ::= \"e\" | \"E\" ```\n\nNo matter which of the three exponent forms is used, no quantity may represent a number greater than 2^63-1 in magnitude, nor may it have more than 3 decimal places. Numbers larger or more precise will be capped or rounded up. (E.g.: 0.1m will rounded up to 1m.) This may be extended in the future if we require larger or smaller quantities.\n\nWhen a Quantity is parsed from a string, it will remember the type of suffix it had, and will use the same type again when it is serialized.\n\nBefore serializing, Quantity will be put in \"canonical form\". This means that Exponent/suffix will be adjusted up or down (with a corresponding increase or decrease in Mantissa) such that:\n\n- No precision is lost - No fractional digits will be emitted - The exponent (or suffix) is as large as possible.\n\nThe sign will be omitted unless the number is negative.\n\nExamples:\n\n- 1.5 will be serialized as \"1500m\" - 1.5Gi will be serialized as \"1536Mi\"\n\nNote that the quantity will NEVER be internally represented by a floating point number. That is the whole point of this exercise.\n\nNon-canonical values will still parse as long as they are well formed, but will be re-emitted in their canonical form. (So always use canonical form, or don't diff.)\n\nThis format is intended to make it difficult to use these numbers without writing some sort of special handling code in the hopes that that will cause implementors to also use a fixed point implementation.", - OneOf: common.GenerateOpenAPIV3OneOfSchema(resource.Quantity{}.OpenAPIV3OneOfTypes()), - Format: resource.Quantity{}.OpenAPISchemaFormat(), - }, - }, - }, common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Quantity is a fixed-point representation of a number. It provides convenient marshaling/unmarshaling in JSON and YAML, in addition to String() and AsInt64() accessors.\n\nThe serialization format is:\n\n``` ::= \n\n\t(Note that may be empty, from the \"\" case in .)\n\n ::= 0 | 1 | ... | 9 ::= | ::= | . | . | . ::= \"+\" | \"-\" ::= | ::= | | ::= Ki | Mi | Gi | Ti | Pi | Ei\n\n\t(International System of units; See: http://physics.nist.gov/cuu/Units/binary.html)\n\n ::= m | \"\" | k | M | G | T | P | E\n\n\t(Note that 1024 = 1Ki but 1000 = 1k; I didn't choose the capitalization.)\n\n ::= \"e\" | \"E\" ```\n\nNo matter which of the three exponent forms is used, no quantity may represent a number greater than 2^63-1 in magnitude, nor may it have more than 3 decimal places. Numbers larger or more precise will be capped or rounded up. (E.g.: 0.1m will rounded up to 1m.) This may be extended in the future if we require larger or smaller quantities.\n\nWhen a Quantity is parsed from a string, it will remember the type of suffix it had, and will use the same type again when it is serialized.\n\nBefore serializing, Quantity will be put in \"canonical form\". This means that Exponent/suffix will be adjusted up or down (with a corresponding increase or decrease in Mantissa) such that:\n\n- No precision is lost - No fractional digits will be emitted - The exponent (or suffix) is as large as possible.\n\nThe sign will be omitted unless the number is negative.\n\nExamples:\n\n- 1.5 will be serialized as \"1500m\" - 1.5Gi will be serialized as \"1536Mi\"\n\nNote that the quantity will NEVER be internally represented by a floating point number. That is the whole point of this exercise.\n\nNon-canonical values will still parse as long as they are well formed, but will be re-emitted in their canonical form. (So always use canonical form, or don't diff.)\n\nThis format is intended to make it difficult to use these numbers without writing some sort of special handling code in the hopes that that will cause implementors to also use a fixed point implementation.", - Type: resource.Quantity{}.OpenAPISchemaType(), - Format: resource.Quantity{}.OpenAPISchemaFormat(), - }, - }, - }) -} - -func schema_apimachinery_pkg_api_resource_int64Amount(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "int64Amount represents a fixed precision numerator and arbitrary scale exponent. It is faster than operations on inf.Dec for values that can be represented as int64.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "value": { - SchemaProps: spec.SchemaProps{ - Default: 0, - Type: []string{"integer"}, - Format: "int64", - }, - }, - "scale": { - SchemaProps: spec.SchemaProps{ - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - Required: []string{"value", "scale"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_APIGroup(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "APIGroup contains the name, the supported versions, and the preferred version of a group.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Description: "name is the name of the group.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "versions": { - SchemaProps: spec.SchemaProps{ - Description: "versions are the versions supported in this group.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.GroupVersionForDiscovery"), - }, - }, - }, - }, - }, - "preferredVersion": { - SchemaProps: spec.SchemaProps{ - Description: "preferredVersion is the version preferred by the API server, which probably is the storage version.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.GroupVersionForDiscovery"), - }, - }, - "serverAddressByClientCIDRs": { - SchemaProps: spec.SchemaProps{ - Description: "a map of client CIDR to server address that is serving this group. This is to help clients reach servers in the most network-efficient way possible. Clients can use the appropriate server address as per the CIDR that they match. In case of multiple matches, clients should use the longest matching CIDR. The server returns only those CIDRs that it thinks that the client can match. For example: the master will return an internal IP CIDR only, if the client reaches the server using an internal IP. Server looks at X-Forwarded-For header or X-Real-Ip header or request.RemoteAddr (in that order) to get the client IP.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ServerAddressByClientCIDR"), - }, - }, - }, - }, - }, - }, - Required: []string{"name", "versions"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.GroupVersionForDiscovery", "k8s.io/apimachinery/pkg/apis/meta/v1.ServerAddressByClientCIDR"}, - } -} - -func schema_pkg_apis_meta_v1_APIGroupList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "APIGroupList is a list of APIGroup, to allow clients to discover the API at /apis.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "groups": { - SchemaProps: spec.SchemaProps{ - Description: "groups is a list of APIGroup.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.APIGroup"), - }, - }, - }, - }, - }, - }, - Required: []string{"groups"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.APIGroup"}, - } -} - -func schema_pkg_apis_meta_v1_APIResource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "APIResource specifies the name of a resource and whether it is namespaced.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "name is the plural name of the resource.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "singularName": { - SchemaProps: spec.SchemaProps{ - Description: "singularName is the singular name of the resource. This allows clients to handle plural and singular opaquely. The singularName is more correct for reporting status on a single item and both singular and plural are allowed from the kubectl CLI interface.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "namespaced": { - SchemaProps: spec.SchemaProps{ - Description: "namespaced indicates if a resource is namespaced or not.", - Default: false, - Type: []string{"boolean"}, - Format: "", - }, - }, - "group": { - SchemaProps: spec.SchemaProps{ - Description: "group is the preferred group of the resource. Empty implies the group of the containing resource list. For subresources, this may have a different value, for example: Scale\".", - Type: []string{"string"}, - Format: "", - }, - }, - "version": { - SchemaProps: spec.SchemaProps{ - Description: "version is the preferred version of the resource. Empty implies the version of the containing resource list For subresources, this may have a different value, for example: v1 (while inside a v1beta1 version of the core resource's group)\".", - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "kind is the kind for the resource (e.g. 'Foo' is the kind for a resource 'foo')", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "verbs": { - SchemaProps: spec.SchemaProps{ - Description: "verbs is a list of supported kube verbs (this includes get, list, watch, create, update, patch, delete, deletecollection, and proxy)", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "shortNames": { - SchemaProps: spec.SchemaProps{ - Description: "shortNames is a list of suggested short names of the resource.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "categories": { - SchemaProps: spec.SchemaProps{ - Description: "categories is a list of the grouped resources this resource belongs to (e.g. 'all')", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "storageVersionHash": { - SchemaProps: spec.SchemaProps{ - Description: "The hash value of the storage version, the version this resource is converted to when written to the data store. Value must be treated as opaque by clients. Only equality comparison on the value is valid. This is an alpha feature and may change or be removed in the future. The field is populated by the apiserver only if the StorageVersionHash feature gate is enabled. This field will remain optional even if it graduates.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name", "singularName", "namespaced", "kind", "verbs"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_APIResourceList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "APIResourceList is a list of APIResource, it is used to expose the name of the resources supported in a specific group and version, and if the resource is namespaced.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "groupVersion": { - SchemaProps: spec.SchemaProps{ - Description: "groupVersion is the group and version this APIResourceList is for.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "resources": { - SchemaProps: spec.SchemaProps{ - Description: "resources contains the name of the resources and if they are namespaced.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.APIResource"), - }, - }, - }, - }, - }, - }, - Required: []string{"groupVersion", "resources"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.APIResource"}, - } -} - -func schema_pkg_apis_meta_v1_APIVersions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "APIVersions lists the versions that are available, to allow clients to discover the API at /api, which is the root path of the legacy v1 API.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "versions": { - SchemaProps: spec.SchemaProps{ - Description: "versions are the api versions that are available.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "serverAddressByClientCIDRs": { - SchemaProps: spec.SchemaProps{ - Description: "a map of client CIDR to server address that is serving this group. This is to help clients reach servers in the most network-efficient way possible. Clients can use the appropriate server address as per the CIDR that they match. In case of multiple matches, clients should use the longest matching CIDR. The server returns only those CIDRs that it thinks that the client can match. For example: the master will return an internal IP CIDR only, if the client reaches the server using an internal IP. Server looks at X-Forwarded-For header or X-Real-Ip header or request.RemoteAddr (in that order) to get the client IP.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ServerAddressByClientCIDR"), - }, - }, - }, - }, - }, - }, - Required: []string{"versions", "serverAddressByClientCIDRs"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ServerAddressByClientCIDR"}, - } -} - -func schema_pkg_apis_meta_v1_ApplyOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ApplyOptions may be provided when applying an API object. FieldManager is required for apply requests. ApplyOptions is equivalent to PatchOptions. It is provided as a convenience with documentation that speaks specifically to how the options fields relate to apply.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "dryRun": { - SchemaProps: spec.SchemaProps{ - Description: "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "force": { - SchemaProps: spec.SchemaProps{ - Description: "Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people.", - Default: false, - Type: []string{"boolean"}, - Format: "", - }, - }, - "fieldManager": { - SchemaProps: spec.SchemaProps{ - Description: "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"force", "fieldManager"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_Condition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Condition contains details for one aspect of the current state of this API Resource.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "type of condition in CamelCase or in foo.example.com/CamelCase.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "status of the condition, one of True, False, Unknown.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "observedGeneration": { - SchemaProps: spec.SchemaProps{ - Description: "observedGeneration represents the .metadata.generation that the condition was set based upon. For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date with respect to the current state of the instance.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "lastTransitionTime": { - SchemaProps: spec.SchemaProps{ - Description: "lastTransitionTime is the last time the condition transitioned from one status to another. This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "reason contains a programmatic identifier indicating the reason for the condition's last transition. Producers of specific condition types may define expected values and meanings for this field, and whether the values are considered a guaranteed API. The value should be a CamelCase string. This field may not be empty.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "message is a human readable message indicating details about the transition. This may be an empty string.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status", "lastTransitionTime", "reason", "message"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_pkg_apis_meta_v1_CreateOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "CreateOptions may be provided when creating an API object.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "dryRun": { - SchemaProps: spec.SchemaProps{ - Description: "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "fieldManager": { - SchemaProps: spec.SchemaProps{ - Description: "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.", - Type: []string{"string"}, - Format: "", - }, - }, - "fieldValidation": { - SchemaProps: spec.SchemaProps{ - Description: "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_DeleteOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "DeleteOptions may be provided when deleting an API object.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "gracePeriodSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "preconditions": { - SchemaProps: spec.SchemaProps{ - Description: "Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Preconditions"), - }, - }, - "orphanDependents": { - SchemaProps: spec.SchemaProps{ - Description: "Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "propagationPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.", - Type: []string{"string"}, - Format: "", - }, - }, - "dryRun": { - SchemaProps: spec.SchemaProps{ - Description: "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Preconditions"}, - } -} - -func schema_pkg_apis_meta_v1_Duration(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Duration is a wrapper around time.Duration which supports correct marshaling to YAML and JSON. In particular, it marshals into strings, which can be used as map keys in json.", - Type: v1.Duration{}.OpenAPISchemaType(), - Format: v1.Duration{}.OpenAPISchemaFormat(), - }, - }, - } -} - -func schema_pkg_apis_meta_v1_FieldsV1(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "FieldsV1 stores a set of fields in a data structure like a Trie, in JSON format.\n\nEach key is either a '.' representing the field itself, and will always map to an empty set, or a string representing a sub-field or item. The string will follow one of these four formats: 'f:', where is the name of a field in a struct, or key in a map 'v:', where is the exact json formatted value of a list item 'i:', where is position of a item in a list 'k:', where is a map of a list item's key fields to their unique values If a key maps to an empty Fields value, the field that key represents is part of the set.\n\nThe exact format is defined in sigs.k8s.io/structured-merge-diff", - Type: []string{"object"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_GetOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "GetOptions is the standard query options to the standard REST get call.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "resourceVersion": { - SchemaProps: spec.SchemaProps{ - Description: "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 details.\n\nDefaults to unset", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_GroupKind(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "GroupKind specifies a Group and a Kind, but does not force a version. This is useful for identifying concepts during lookup stages without having partially valid types", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "group": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"group", "kind"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_GroupResource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "GroupResource specifies a Group and a Resource, but does not force a version. This is useful for identifying concepts during lookup stages without having partially valid types", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "group": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "resource": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"group", "resource"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_GroupVersion(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "GroupVersion contains the \"group\" and the \"version\", which uniquely identifies the API.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "group": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "version": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"group", "version"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_GroupVersionForDiscovery(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "GroupVersion contains the \"group/version\" and \"version\" string of a version. It is made a struct to keep extensibility.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "groupVersion": { - SchemaProps: spec.SchemaProps{ - Description: "groupVersion specifies the API group and version in the form \"group/version\"", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "version": { - SchemaProps: spec.SchemaProps{ - Description: "version specifies the version in the form of \"version\". This is to save the clients the trouble of splitting the GroupVersion.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"groupVersion", "version"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_GroupVersionKind(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "GroupVersionKind unambiguously identifies a kind. It doesn't anonymously include GroupVersion to avoid automatic coercion. It doesn't use a GroupVersion to avoid custom marshalling", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "group": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "version": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"group", "version", "kind"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_GroupVersionResource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "GroupVersionResource unambiguously identifies a resource. It doesn't anonymously include GroupVersion to avoid automatic coercion. It doesn't use a GroupVersion to avoid custom marshalling", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "group": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "version": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "resource": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"group", "version", "resource"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_InternalEvent(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "InternalEvent makes watch.Event versioned", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "Type": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "Object": { - SchemaProps: spec.SchemaProps{ - Description: "Object is:\n * If Type is Added or Modified: the new state of the object.\n * If Type is Deleted: the state of the object immediately before deletion.\n * If Type is Bookmark: the object (instance of a type being watched) where\n only ResourceVersion field is set. On successful restart of watch from a\n bookmark resourceVersion, client is guaranteed to not get repeat event\n nor miss any events.\n * If Type is Error: *api.Status is recommended; other types may make sense\n depending on context.", - Ref: ref("k8s.io/apimachinery/pkg/runtime.Object"), - }, - }, - }, - Required: []string{"Type", "Object"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/runtime.Object"}, - } -} - -func schema_pkg_apis_meta_v1_LabelSelector(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A label selector is a label query over a set of resources. The result of matchLabels and matchExpressions are ANDed. An empty label selector matches all objects. A null label selector matches no objects.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "matchLabels": { - SchemaProps: spec.SchemaProps{ - Description: "matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "matchExpressions": { - SchemaProps: spec.SchemaProps{ - Description: "matchExpressions is a list of label selector requirements. The requirements are ANDed.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelectorRequirement"), - }, - }, - }, - }, - }, - }, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelectorRequirement"}, - } -} - -func schema_pkg_apis_meta_v1_LabelSelectorRequirement(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "key": { - SchemaProps: spec.SchemaProps{ - Description: "key is the label key that the selector applies to.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "operator": { - SchemaProps: spec.SchemaProps{ - Description: "operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "values": { - SchemaProps: spec.SchemaProps{ - Description: "values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"key", "operator"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_List(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "List holds a list of objects, which may not be known by the server.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of objects", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/runtime.RawExtension"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "k8s.io/apimachinery/pkg/runtime.RawExtension"}, - } -} - -func schema_pkg_apis_meta_v1_ListMeta(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "selfLink": { - SchemaProps: spec.SchemaProps{ - Description: "Deprecated: selfLink is a legacy read-only field that is no longer populated by the system.", - Type: []string{"string"}, - Format: "", - }, - }, - "resourceVersion": { - SchemaProps: spec.SchemaProps{ - Description: "String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency", - Type: []string{"string"}, - Format: "", - }, - }, - "continue": { - SchemaProps: spec.SchemaProps{ - Description: "continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.", - Type: []string{"string"}, - Format: "", - }, - }, - "remainingItemCount": { - SchemaProps: spec.SchemaProps{ - Description: "remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_ListOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ListOptions is the query options to a standard REST list call.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "labelSelector": { - SchemaProps: spec.SchemaProps{ - Description: "A selector to restrict the list of returned objects by their labels. Defaults to everything.", - Type: []string{"string"}, - Format: "", - }, - }, - "fieldSelector": { - SchemaProps: spec.SchemaProps{ - Description: "A selector to restrict the list of returned objects by their fields. Defaults to everything.", - Type: []string{"string"}, - Format: "", - }, - }, - "watch": { - SchemaProps: spec.SchemaProps{ - Description: "Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "allowWatchBookmarks": { - SchemaProps: spec.SchemaProps{ - Description: "allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not 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.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "resourceVersion": { - SchemaProps: spec.SchemaProps{ - Description: "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 details.\n\nDefaults to unset", - Type: []string{"string"}, - Format: "", - }, - }, - "resourceVersionMatch": { - SchemaProps: spec.SchemaProps{ - Description: "resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset", - Type: []string{"string"}, - Format: "", - }, - }, - "timeoutSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "limit": { - SchemaProps: spec.SchemaProps{ - Description: "limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.\n\nThe server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "continue": { - SchemaProps: spec.SchemaProps{ - Description: "The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\".\n\nThis field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.", - Type: []string{"string"}, - Format: "", - }, - }, - "sendInitialEvents": { - SchemaProps: spec.SchemaProps{ - Description: "`sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched.\n\nWhen `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan\n is interpreted as \"data at least as new as the provided `resourceVersion`\"\n and the bookmark event is send when the state is synced\n to a `resourceVersion` at least as fresh as the one provided by the ListOptions.\n If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the\n bookmark event is send when the state is synced at least to the moment\n when request started being processed.\n- `resourceVersionMatch` set to any other value or unset\n Invalid error is returned.\n\nDefaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_ManagedFieldsEntry(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ManagedFieldsEntry is a workflow-id, a FieldSet and the group version of the resource that the fieldset applies to.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "manager": { - SchemaProps: spec.SchemaProps{ - Description: "Manager is an identifier of the workflow managing these fields.", - Type: []string{"string"}, - Format: "", - }, - }, - "operation": { - SchemaProps: spec.SchemaProps{ - Description: "Operation is the type of operation which lead to this ManagedFieldsEntry being created. The only valid values for this field are 'Apply' and 'Update'.", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the version of this resource that this field set applies to. The format is \"group/version\" just like the top-level APIVersion field. It is necessary to track the version of a field set because it cannot be automatically converted.", - Type: []string{"string"}, - Format: "", - }, - }, - "time": { - SchemaProps: spec.SchemaProps{ - Description: "Time is the timestamp of when the ManagedFields entry was added. The timestamp will also be updated if a field is added, the manager changes any of the owned fields value or removes a field. The timestamp does not update when a field is removed from the entry because another manager took it over.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "fieldsType": { - SchemaProps: spec.SchemaProps{ - Description: "FieldsType is the discriminator for the different fields format and version. There is currently only one possible value: \"FieldsV1\"", - Type: []string{"string"}, - Format: "", - }, - }, - "fieldsV1": { - SchemaProps: spec.SchemaProps{ - Description: "FieldsV1 holds the first JSON version format as described in the \"FieldsV1\" type.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.FieldsV1"), - }, - }, - "subresource": { - SchemaProps: spec.SchemaProps{ - Description: "Subresource is the name of the subresource used to update that object, or empty string if the object was updated through the main resource. The value of this field is used to distinguish between managers, even if they share the same name. For example, a status update will be distinct from a regular update using the same manager name. Note that the APIVersion field is not related to the Subresource field and it always corresponds to the version of the main resource.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.FieldsV1", "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_pkg_apis_meta_v1_MicroTime(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "MicroTime is version of Time with microsecond level precision.", - Type: v1.MicroTime{}.OpenAPISchemaType(), - Format: v1.MicroTime{}.OpenAPISchemaFormat(), - }, - }, - } -} - -func schema_pkg_apis_meta_v1_ObjectMeta(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ObjectMeta is metadata that all persisted resources must have, which includes all objects users must create.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names", - Type: []string{"string"}, - Format: "", - }, - }, - "generateName": { - SchemaProps: spec.SchemaProps{ - Description: "GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server.\n\nIf this field is specified and the generated name exists, the server will return a 409.\n\nApplied only if Name is not specified. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency", - Type: []string{"string"}, - Format: "", - }, - }, - "namespace": { - SchemaProps: spec.SchemaProps{ - Description: "Namespace defines the space within which each name must be unique. An empty namespace is equivalent to the \"default\" namespace, but \"default\" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty.\n\nMust be a DNS_LABEL. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces", - Type: []string{"string"}, - Format: "", - }, - }, - "selfLink": { - SchemaProps: spec.SchemaProps{ - Description: "Deprecated: selfLink is a legacy read-only field that is no longer populated by the system.", - Type: []string{"string"}, - Format: "", - }, - }, - "uid": { - SchemaProps: spec.SchemaProps{ - Description: "UID is the unique in time and space value for this object. It is typically generated by the server on successful creation of a resource and is not allowed to change on PUT operations.\n\nPopulated by the system. Read-only. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids", - Type: []string{"string"}, - Format: "", - }, - }, - "resourceVersion": { - SchemaProps: spec.SchemaProps{ - Description: "An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. Clients must treat these values as opaque and passed unmodified back to the server. They may only be valid for a particular resource or set of resources.\n\nPopulated by the system. Read-only. Value must be treated as opaque by clients and . More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency", - Type: []string{"string"}, - Format: "", - }, - }, - "generation": { - SchemaProps: spec.SchemaProps{ - Description: "A sequence number representing a specific generation of the desired state. Populated by the system. Read-only.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "creationTimestamp": { - SchemaProps: spec.SchemaProps{ - Description: "CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC.\n\nPopulated by the system. Read-only. Null for lists. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "deletionTimestamp": { - SchemaProps: spec.SchemaProps{ - Description: "DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This field is set by the server when a graceful deletion is requested by the user, and is not directly settable by a client. The resource is expected to be deleted (no longer visible from resource lists, and not reachable by name) after the time in this field, once the finalizers list is empty. As long as the finalizers list contains items, deletion is blocked. Once the deletionTimestamp is set, this value may not be unset or be set further into the future, although it may be shortened or the resource may be deleted prior to this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react by sending a graceful termination signal to the containers in the pod. After that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup, remove the pod from the API. In the presence of network partitions, this object may still exist after this timestamp, until an administrator or automated process can determine the resource is fully terminated. If not set, graceful deletion of the object has not been requested.\n\nPopulated by the system when a graceful deletion is requested. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "deletionGracePeriodSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Number of seconds allowed for this object to gracefully terminate before it will be removed from the system. Only set when deletionTimestamp is also set. May only be shortened. Read-only.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "labels": { - SchemaProps: spec.SchemaProps{ - Description: "Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "annotations": { - SchemaProps: spec.SchemaProps{ - Description: "Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "ownerReferences": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "uid", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.OwnerReference"), - }, - }, - }, - }, - }, - "finalizers": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Must be empty before the object is deleted from the registry. Each entry is an identifier for the responsible component that will remove the entry from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only be removed. Finalizers may be processed and removed in any order. Order is NOT enforced because it introduces significant risk of stuck finalizers. finalizers is a shared field, any actor with permission can reorder it. If the finalizer list is processed in order, then this can lead to a situation in which the component responsible for the first finalizer in the list is waiting for a signal (field value, external system, or other) produced by a component responsible for a finalizer later in the list, resulting in a deadlock. Without enforced ordering finalizers are free to order amongst themselves and are not vulnerable to ordering changes in the list.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "managedFields": { - SchemaProps: spec.SchemaProps{ - Description: "ManagedFields maps workflow-id and version to the set of fields that are managed by that workflow. This is mostly for internal housekeeping, and users typically shouldn't need to set or understand this field. A workflow can be the user's name, a controller's name, or the name of a specific apply path like \"ci-cd\". The set of fields is always in the version that the workflow used when modifying the object.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ManagedFieldsEntry"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ManagedFieldsEntry", "k8s.io/apimachinery/pkg/apis/meta/v1.OwnerReference", "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_pkg_apis_meta_v1_OwnerReference(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "OwnerReference contains enough information to let you identify an owning object. An owning object must be in the same namespace as the dependent, or be cluster-scoped, so there is no namespace field.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "API version of the referent.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "uid": { - SchemaProps: spec.SchemaProps{ - Description: "UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "controller": { - SchemaProps: spec.SchemaProps{ - Description: "If true, this reference points to the managing controller.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "blockOwnerDeletion": { - SchemaProps: spec.SchemaProps{ - Description: "If true, AND if the owner has the \"foregroundDeletion\" finalizer, then the owner cannot be deleted from the key-value store until this reference is removed. See https://kubernetes.io/docs/concepts/architecture/garbage-collection/#foreground-deletion for how the garbage collector interacts with this field and enforces the foreground deletion. Defaults to false. To set this field, a user needs \"delete\" permission of the owner, otherwise 422 (Unprocessable Entity) will be returned.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"apiVersion", "kind", "name", "uid"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_PartialObjectMetadata(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PartialObjectMetadata is a generic representation of any object with ObjectMeta. It allows clients to get access to a particular ObjectMeta schema without knowing the details of the version.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_pkg_apis_meta_v1_PartialObjectMetadataList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PartialObjectMetadataList contains a list of objects containing only their metadata", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "items contains each of the included items.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.PartialObjectMetadata"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "k8s.io/apimachinery/pkg/apis/meta/v1.PartialObjectMetadata"}, - } -} - -func schema_pkg_apis_meta_v1_Patch(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Patch is provided to give a concrete name and type to the Kubernetes PATCH request body.", - Type: []string{"object"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_PatchOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PatchOptions may be provided when patching an API object. PatchOptions is meant to be a superset of UpdateOptions.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "dryRun": { - SchemaProps: spec.SchemaProps{ - Description: "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "force": { - SchemaProps: spec.SchemaProps{ - Description: "Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "fieldManager": { - SchemaProps: spec.SchemaProps{ - Description: "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).", - Type: []string{"string"}, - Format: "", - }, - }, - "fieldValidation": { - SchemaProps: spec.SchemaProps{ - Description: "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_Preconditions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Preconditions must be fulfilled before an operation (update, delete, etc.) is carried out.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "uid": { - SchemaProps: spec.SchemaProps{ - Description: "Specifies the target UID.", - Type: []string{"string"}, - Format: "", - }, - }, - "resourceVersion": { - SchemaProps: spec.SchemaProps{ - Description: "Specifies the target ResourceVersion", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_RootPaths(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "RootPaths lists the paths available at root. For example: \"/healthz\", \"/apis\".", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "paths": { - SchemaProps: spec.SchemaProps{ - Description: "paths are the paths available at root.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"paths"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_ServerAddressByClientCIDR(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ServerAddressByClientCIDR helps the client to determine the server address that they should use, depending on the clientCIDR that they match.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "clientCIDR": { - SchemaProps: spec.SchemaProps{ - Description: "The CIDR with which clients can match their IP to figure out the server address that they should use.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "serverAddress": { - SchemaProps: spec.SchemaProps{ - Description: "Address of this server, suitable for a client that matches the above CIDR. This can be a hostname, hostname:port, IP or IP:port.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"clientCIDR", "serverAddress"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_Status(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Status is a return value for calls that don't return other objects.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status of the operation. One of: \"Success\" or \"Failure\". More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "A human-readable description of the status of this operation.", - Type: []string{"string"}, - Format: "", - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "A machine-readable description of why this operation is in the \"Failure\" status. If this value is empty there is no information available. A Reason clarifies an HTTP status code but does not override it.", - Type: []string{"string"}, - Format: "", - }, - }, - "details": { - SchemaProps: spec.SchemaProps{ - Description: "Extended data associated with the reason. Each reason may define its own extended details. This field is optional and the data returned is not guaranteed to conform to any schema except that defined by the reason type.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.StatusDetails"), - }, - }, - "code": { - SchemaProps: spec.SchemaProps{ - Description: "Suggested HTTP return code for this status, 0 if not set.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "k8s.io/apimachinery/pkg/apis/meta/v1.StatusDetails"}, - } -} - -func schema_pkg_apis_meta_v1_StatusCause(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "StatusCause provides more information about an api.Status failure, including cases when multiple errors are encountered.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "A machine-readable description of the cause of the error. If this value is empty there is no information available.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "A human-readable description of the cause of the error. This field may be presented as-is to a reader.", - Type: []string{"string"}, - Format: "", - }, - }, - "field": { - SchemaProps: spec.SchemaProps{ - Description: "The field of the resource that has caused this error, as named by its JSON serialization. May include dot and postfix notation for nested attributes. Arrays are zero-indexed. Fields may appear more than once in an array of causes due to fields having multiple errors. Optional.\n\nExamples:\n \"name\" - the field \"name\" on the current resource\n \"items[0].name\" - the field \"name\" on the first array entry in \"items\"", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_StatusDetails(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "StatusDetails is a set of additional properties that MAY be set by the server to provide additional information about a response. The Reason field of a Status object defines what attributes will be set. Clients must ignore fields that do not match the defined type of each attribute, and should assume that any attribute may be empty, invalid, or under defined.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "The name attribute of the resource associated with the status StatusReason (when there is a single name which can be described).", - Type: []string{"string"}, - Format: "", - }, - }, - "group": { - SchemaProps: spec.SchemaProps{ - Description: "The group attribute of the resource associated with the status StatusReason.", - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "The kind attribute of the resource associated with the status StatusReason. On some operations may differ from the requested resource Kind. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "uid": { - SchemaProps: spec.SchemaProps{ - Description: "UID of the resource. (when there is a single resource which can be described). More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids", - Type: []string{"string"}, - Format: "", - }, - }, - "causes": { - SchemaProps: spec.SchemaProps{ - Description: "The Causes array includes more details associated with the StatusReason failure. Not all StatusReasons may provide detailed causes.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.StatusCause"), - }, - }, - }, - }, - }, - "retryAfterSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, the time in seconds before the operation should be retried. Some errors may indicate the client must take an alternate action - for those errors this field may indicate how long to wait before taking the alternate action.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.StatusCause"}, - } -} - -func schema_pkg_apis_meta_v1_Table(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Table is a tabular representation of a set of API resources. The server transforms the object into a set of preferred columns for quickly reviewing the objects.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "columnDefinitions": { - SchemaProps: spec.SchemaProps{ - Description: "columnDefinitions describes each column in the returned items array. The number of cells per row will always match the number of column definitions.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.TableColumnDefinition"), - }, - }, - }, - }, - }, - "rows": { - SchemaProps: spec.SchemaProps{ - Description: "rows is the list of items in the table.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.TableRow"), - }, - }, - }, - }, - }, - }, - Required: []string{"columnDefinitions", "rows"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "k8s.io/apimachinery/pkg/apis/meta/v1.TableColumnDefinition", "k8s.io/apimachinery/pkg/apis/meta/v1.TableRow"}, - } -} - -func schema_pkg_apis_meta_v1_TableColumnDefinition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "TableColumnDefinition contains information about a column returned in the Table.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "name is a human readable name for the column.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "type": { - SchemaProps: spec.SchemaProps{ - Description: "type is an OpenAPI type definition for this column, such as number, integer, string, or array. See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for more.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "format": { - SchemaProps: spec.SchemaProps{ - Description: "format is an optional OpenAPI type modifier for this column. A format modifies the type and imposes additional rules, like date or time formatting for a string. The 'name' format is applied to the primary identifier column which has type 'string' to assist in clients identifying column is the resource name. See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for more.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "description": { - SchemaProps: spec.SchemaProps{ - Description: "description is a human readable description of this column.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "priority": { - SchemaProps: spec.SchemaProps{ - Description: "priority is an integer defining the relative importance of this column compared to others. Lower numbers are considered higher priority. Columns that may be omitted in limited space scenarios should be given a higher priority.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - Required: []string{"name", "type", "format", "description", "priority"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_TableOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "TableOptions are used when a Table is requested by the caller.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "includeObject": { - SchemaProps: spec.SchemaProps{ - Description: "includeObject decides whether to include each object along with its columnar information. Specifying \"None\" will return no object, specifying \"Object\" will return the full object contents, and specifying \"Metadata\" (the default) will return the object's metadata in the PartialObjectMetadata kind in version v1beta1 of the meta.k8s.io API group.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_TableRow(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "TableRow is an individual row in a table.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "cells": { - SchemaProps: spec.SchemaProps{ - Description: "cells will be as wide as the column definitions array and may contain strings, numbers (float64 or int64), booleans, simple maps, lists, or null. See the type field of the column definition for a more detailed description.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Format: "", - }, - }, - }, - }, - }, - "conditions": { - SchemaProps: spec.SchemaProps{ - Description: "conditions describe additional status of a row that are relevant for a human user. These conditions apply to the row, not to the object, and will be specific to table output. The only defined condition type is 'Completed', for a row that indicates a resource that has run to completion and can be given less visual priority.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.TableRowCondition"), - }, - }, - }, - }, - }, - "object": { - SchemaProps: spec.SchemaProps{ - Description: "This field contains the requested additional information about each object based on the includeObject policy when requesting the Table. If \"None\", this field is empty, if \"Object\" this will be the default serialization of the object for the current API version, and if \"Metadata\" (the default) will contain the object metadata. Check the returned kind and apiVersion of the object before parsing. The media type of the object will always match the enclosing list - if this as a JSON table, these will be JSON encoded objects.", - Ref: ref("k8s.io/apimachinery/pkg/runtime.RawExtension"), - }, - }, - }, - Required: []string{"cells"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.TableRowCondition", "k8s.io/apimachinery/pkg/runtime.RawExtension"}, - } -} - -func schema_pkg_apis_meta_v1_TableRowCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "TableRowCondition allows a row to be marked with additional information.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of row condition. The only defined value is 'Completed' indicating that the object this row represents has reached a completed state and may be given less visual priority than other rows. Clients are not required to honor any conditions but should be consistent where possible about handling the conditions.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status of the condition, one of True, False, Unknown.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "(brief) machine readable reason for the condition's last transition.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "Human readable message indicating details about last transition.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_Time(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Time is a wrapper around time.Time which supports correct marshaling to YAML and JSON. Wrappers are provided for many of the factory methods that the time package offers.", - Type: v1.Time{}.OpenAPISchemaType(), - Format: v1.Time{}.OpenAPISchemaFormat(), - }, - }, - } -} - -func schema_pkg_apis_meta_v1_Timestamp(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Timestamp is a struct that is equivalent to Time, but intended for protobuf marshalling/unmarshalling. It is generated into a serialization that matches Time. Do not use in Go structs.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "seconds": { - SchemaProps: spec.SchemaProps{ - Description: "Represents seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.", - Default: 0, - Type: []string{"integer"}, - Format: "int64", - }, - }, - "nanos": { - SchemaProps: spec.SchemaProps{ - Description: "Non-negative fractions of a second at nanosecond resolution. Negative second values with fractions must still have non-negative nanos values that count forward in time. Must be from 0 to 999,999,999 inclusive. This field may be limited in precision depending on context.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - Required: []string{"seconds", "nanos"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_TypeMeta(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "TypeMeta describes an individual object in an API response or request with strings representing the type of the object and its API schema version. Structures that are versioned or persisted should inline TypeMeta.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_UpdateOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "UpdateOptions may be provided when updating an API object. All fields in UpdateOptions should also be present in PatchOptions.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "dryRun": { - SchemaProps: spec.SchemaProps{ - Description: "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "fieldManager": { - SchemaProps: spec.SchemaProps{ - Description: "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.", - Type: []string{"string"}, - Format: "", - }, - }, - "fieldValidation": { - SchemaProps: spec.SchemaProps{ - Description: "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_WatchEvent(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Event represents a single event to a watched resource.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "object": { - SchemaProps: spec.SchemaProps{ - Description: "Object is:\n * If Type is Added or Modified: the new state of the object.\n * If Type is Deleted: the state of the object immediately before deletion.\n * If Type is Error: *Status is recommended; other types may make sense\n depending on context.", - Ref: ref("k8s.io/apimachinery/pkg/runtime.RawExtension"), - }, - }, - }, - Required: []string{"type", "object"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/runtime.RawExtension"}, - } -} - -func schema_k8sio_apimachinery_pkg_runtime_RawExtension(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "RawExtension is used to hold extensions in external versions.\n\nTo use this, make a field which has RawExtension as its type in your external, versioned struct, and Object in your internal struct. You also need to register your various plugin types.\n\n// Internal package:\n\n\ttype MyAPIObject struct {\n\t\truntime.TypeMeta `json:\",inline\"`\n\t\tMyPlugin runtime.Object `json:\"myPlugin\"`\n\t}\n\n\ttype PluginA struct {\n\t\tAOption string `json:\"aOption\"`\n\t}\n\n// External package:\n\n\ttype MyAPIObject struct {\n\t\truntime.TypeMeta `json:\",inline\"`\n\t\tMyPlugin runtime.RawExtension `json:\"myPlugin\"`\n\t}\n\n\ttype PluginA struct {\n\t\tAOption string `json:\"aOption\"`\n\t}\n\n// On the wire, the JSON will look something like this:\n\n\t{\n\t\t\"kind\":\"MyAPIObject\",\n\t\t\"apiVersion\":\"v1\",\n\t\t\"myPlugin\": {\n\t\t\t\"kind\":\"PluginA\",\n\t\t\t\"aOption\":\"foo\",\n\t\t},\n\t}\n\nSo what happens? Decode first uses json or yaml to unmarshal the serialized data into your external MyAPIObject. That causes the raw JSON to be stored, but not unpacked. The next step is to copy (using pkg/conversion) into the internal struct. The runtime package's DefaultScheme has conversion functions installed which will unpack the JSON stored in RawExtension, turning it into the correct object type, and storing it in the Object. (TODO: In the case where the object is of an unknown type, a runtime.Unknown object will be created and stored.)", - Type: []string{"object"}, - }, - }, - } -} - -func schema_k8sio_apimachinery_pkg_runtime_TypeMeta(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "TypeMeta is shared by all top level objects. The proper way to use it is to inline it in your type, like this:\n\n\ttype MyAwesomeAPIObject struct {\n\t runtime.TypeMeta `json:\",inline\"`\n\t ... // other fields\n\t}\n\nfunc (obj *MyAwesomeAPIObject) SetGroupVersionKind(gvk *metav1.GroupVersionKind) { metav1.UpdateTypeMeta(obj,gvk) }; GroupVersionKind() *GroupVersionKind\n\nTypeMeta is provided here for convenience. You may use it directly from this package or define your own with the same fields.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_apimachinery_pkg_runtime_Unknown(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Unknown allows api objects with unknown types to be passed-through. This can be used to deal with the API objects from a plug-in. Unknown objects still have functioning TypeMeta features-- kind, version, etc. metadata and field mutatation.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "ContentEncoding": { - SchemaProps: spec.SchemaProps{ - Description: "ContentEncoding is encoding used to encode 'Raw' data. Unspecified means no encoding.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "ContentType": { - SchemaProps: spec.SchemaProps{ - Description: "ContentType is serialization method used to serialize 'Raw'. Unspecified means ContentTypeJSON.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"ContentEncoding", "ContentType"}, - }, - }, - } -} - -func schema_apimachinery_pkg_util_intstr_IntOrString(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.EmbedOpenAPIDefinitionIntoV2Extension(common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "IntOrString is a type that can hold an int32 or a string. When used in JSON or YAML marshalling and unmarshalling, it produces or consumes the inner type. This allows you to have, for example, a JSON field that can accept a name or number.", - OneOf: common.GenerateOpenAPIV3OneOfSchema(intstr.IntOrString{}.OpenAPIV3OneOfTypes()), - Format: intstr.IntOrString{}.OpenAPISchemaFormat(), - }, - }, - }, common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "IntOrString is a type that can hold an int32 or a string. When used in JSON or YAML marshalling and unmarshalling, it produces or consumes the inner type. This allows you to have, for example, a JSON field that can accept a name or number.", - Type: intstr.IntOrString{}.OpenAPISchemaType(), - Format: intstr.IntOrString{}.OpenAPISchemaFormat(), - }, - }, - }) -} - -func schema_k8sio_apimachinery_pkg_version_Info(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Info contains versioning information. how we'll want to distribute that information.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "major": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "minor": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "gitVersion": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "gitCommit": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "gitTreeState": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "buildDate": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "goVersion": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "compiler": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "platform": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"major", "minor", "gitVersion", "gitCommit", "gitTreeState", "buildDate", "goVersion", "compiler", "platform"}, - }, - }, - } -} - -func schema_kmodulesxyz_client_go_api_v1_CAPIClusterInfo(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "provider": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "namespace": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "clusterName": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_kmodulesxyz_client_go_api_v1_CertificatePrivateKey(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "CertificatePrivateKey contains configuration options for private keys used by the Certificate controller. This allows control of how private keys are rotated.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "encoding": { - SchemaProps: spec.SchemaProps{ - Description: "The private key cryptography standards (PKCS) encoding for this certificate's private key to be encoded in. If provided, allowed values are \"pkcs1\" and \"pkcs8\" standing for PKCS#1 and PKCS#8, respectively. Defaults to PKCS#1 if not specified. See here for the difference between the formats: https://stackoverflow.com/a/48960291", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_kmodulesxyz_client_go_api_v1_CertificateSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "alias": { - SchemaProps: spec.SchemaProps{ - Description: "Alias represents the identifier of the certificate.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "issuerRef": { - SchemaProps: spec.SchemaProps{ - Description: "IssuerRef is a reference to a Certificate Issuer.", - Ref: ref("k8s.io/api/core/v1.TypedLocalObjectReference"), - }, - }, - "secretName": { - SchemaProps: spec.SchemaProps{ - Description: "Specifies the k8s secret name that holds the certificates. Default to --cert.", - Type: []string{"string"}, - Format: "", - }, - }, - "subject": { - SchemaProps: spec.SchemaProps{ - Description: "Full X509 name specification (https://golang.org/pkg/crypto/x509/pkix/#Name).", - Ref: ref("kmodules.xyz/client-go/api/v1.X509Subject"), - }, - }, - "duration": { - SchemaProps: spec.SchemaProps{ - Description: "Certificate default Duration", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Duration"), - }, - }, - "renewBefore": { - SchemaProps: spec.SchemaProps{ - Description: "Certificate renew before expiration duration", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Duration"), - }, - }, - "dnsNames": { - SchemaProps: spec.SchemaProps{ - Description: "DNSNames is a list of subject alt names to be used on the Certificate.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "ipAddresses": { - SchemaProps: spec.SchemaProps{ - Description: "IPAddresses is a list of IP addresses to be used on the Certificate", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "uris": { - SchemaProps: spec.SchemaProps{ - Description: "URIs is a list of URI subjectAltNames to be set on the Certificate.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "emailAddresses": { - SchemaProps: spec.SchemaProps{ - Description: "EmailAddresses is a list of email subjectAltNames to be set on the Certificate.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "privateKey": { - SchemaProps: spec.SchemaProps{ - Description: "Options to control private keys used for the Certificate.", - Ref: ref("kmodules.xyz/client-go/api/v1.CertificatePrivateKey"), - }, - }, - }, - Required: []string{"alias"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.TypedLocalObjectReference", "k8s.io/apimachinery/pkg/apis/meta/v1.Duration", "kmodules.xyz/client-go/api/v1.CertificatePrivateKey", "kmodules.xyz/client-go/api/v1.X509Subject"}, - } -} - -func schema_kmodulesxyz_client_go_api_v1_ClusterMetadata(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "uid": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "displayName": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "provider": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"uid"}, - }, - }, - } -} - -func schema_kmodulesxyz_client_go_api_v1_Condition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Condition defines an observation of a object operational state.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of condition in CamelCase or in foo.example.com/CamelCase. Many .condition.type values are consistent across resources like Available, but because arbitrary util can be useful (see .node.status.util), the ability to deconflict is important.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status of the condition, one of True, False, Unknown.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "observedGeneration": { - SchemaProps: spec.SchemaProps{ - Description: "If set, this represents the .metadata.generation that the condition was set based upon. For instance, if .metadata.generation is currently 12, but the .status.condition[x].observedGeneration is 9, the condition is out of date with respect to the current state of the instance.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "severity": { - SchemaProps: spec.SchemaProps{ - Description: "Severity provides an explicit classification of Reason code, so the users or machines can immediately understand the current situation and act accordingly. The Severity field MUST be set only when Status=False.", - Type: []string{"string"}, - Format: "", - }, - }, - "lastTransitionTime": { - SchemaProps: spec.SchemaProps{ - Description: "Last time the condition transitioned from one status to another. This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "The reason for the condition's last transition in CamelCase. The specific API may choose whether this field is considered a guaranteed API. This field may not be empty.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "A human-readable message indicating details about the transition. This field may be empty.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status", "lastTransitionTime"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_kmodulesxyz_client_go_api_v1_HealthCheckSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "HealthCheckSpec defines attributes of the health check", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "periodSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "How often (in seconds) to perform the health check. Default to 10 seconds. Minimum value is 1.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "timeoutSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Number of seconds after which the probe times out. Defaults to 10 second. Minimum value is 1. It should be less than the periodSeconds.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "failureThreshold": { - SchemaProps: spec.SchemaProps{ - Description: "Minimum consecutive failures for the health check to be considered failed after having succeeded. Defaults to 1. Minimum value is 1.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "disableWriteCheck": { - SchemaProps: spec.SchemaProps{ - Description: "Whether to disable write check on database. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_kmodulesxyz_client_go_api_v1_ImageInfo(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "image": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "lineages": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/client-go/api/v1.Lineage"), - }, - }, - }, - }, - }, - "pullCredentials": { - SchemaProps: spec.SchemaProps{ - Ref: ref("kmodules.xyz/client-go/api/v1.PullCredentials"), - }, - }, - }, - Required: []string{"image"}, - }, - }, - Dependencies: []string{ - "kmodules.xyz/client-go/api/v1.Lineage", "kmodules.xyz/client-go/api/v1.PullCredentials"}, - } -} - -func schema_kmodulesxyz_client_go_api_v1_Lineage(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "chain": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/client-go/api/v1.ObjectInfo"), - }, - }, - }, - }, - }, - "containers": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "kmodules.xyz/client-go/api/v1.ObjectInfo"}, - } -} - -func schema_kmodulesxyz_client_go_api_v1_ObjectID(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "group": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "namespace": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_kmodulesxyz_client_go_api_v1_ObjectInfo(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "resource": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/client-go/api/v1.ResourceID"), - }, - }, - "ref": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/client-go/api/v1.ObjectReference"), - }, - }, - }, - Required: []string{"resource", "ref"}, - }, - }, - Dependencies: []string{ - "kmodules.xyz/client-go/api/v1.ObjectReference", "kmodules.xyz/client-go/api/v1.ResourceID"}, - } -} - -func schema_kmodulesxyz_client_go_api_v1_ObjectReference(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ObjectReference contains enough information to let you inspect or modify the referred object.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "namespace": { - SchemaProps: spec.SchemaProps{ - Description: "Namespace of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/", - Type: []string{"string"}, - Format: "", - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name"}, - }, - }, - } -} - -func schema_kmodulesxyz_client_go_api_v1_PullCredentials(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "namespace": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "serviceAccountName": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "secretRefs": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - }, - }, - }, - }, - Required: []string{"namespace"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LocalObjectReference"}, - } -} - -func schema_kmodulesxyz_client_go_api_v1_ReadonlyHealthCheckSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ReadonlyHealthCheckSpec defines attributes of the health check using only read-only checks", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "periodSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "How often (in seconds) to perform the health check. Default to 10 seconds. Minimum value is 1.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "timeoutSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Number of seconds after which the probe times out. Defaults to 10 second. Minimum value is 1. It should be less than the periodSeconds.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "failureThreshold": { - SchemaProps: spec.SchemaProps{ - Description: "Minimum consecutive failures for the health check to be considered failed after having succeeded. Defaults to 1. Minimum value is 1.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - }, - }, - } -} - -func schema_kmodulesxyz_client_go_api_v1_ResourceID(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ResourceID identifies a resource", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "group": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "version": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name is the plural name of the resource to serve. It must match the name of the CustomResourceDefinition-registration too: plural.group and it must be all lowercase.", - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is the serialized kind of the resource. It is normally CamelCase and singular.", - Type: []string{"string"}, - Format: "", - }, - }, - "scope": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"group"}, - }, - }, - } -} - -func schema_kmodulesxyz_client_go_api_v1_TLSConfig(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "issuerRef": { - SchemaProps: spec.SchemaProps{ - Description: "IssuerRef is a reference to a Certificate Issuer.", - Ref: ref("k8s.io/api/core/v1.TypedLocalObjectReference"), - }, - }, - "certificates": { - SchemaProps: spec.SchemaProps{ - Description: "Certificate provides server and/or client certificate options used by application pods. These options are passed to a cert-manager Certificate object. xref: https://github.com/jetstack/cert-manager/blob/v0.16.0/pkg/apis/certmanager/v1beta1/types_certificate.go#L82-L162", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/client-go/api/v1.CertificateSpec"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.TypedLocalObjectReference", "kmodules.xyz/client-go/api/v1.CertificateSpec"}, - } -} - -func schema_kmodulesxyz_client_go_api_v1_TimeOfDay(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "TimeOfDay is a wrapper around time.Time which supports correct marshaling to YAML and JSON. Wrappers are provided for many of the factory methods that the time package offers.", - Type: apiv1.TimeOfDay{}.OpenAPISchemaType(), - Format: apiv1.TimeOfDay{}.OpenAPISchemaFormat(), - }, - }, - } -} - -func schema_kmodulesxyz_client_go_api_v1_TypedObjectReference(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "TypedObjectReference represents an typed namespaced object.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "apiGroup": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "namespace": { - SchemaProps: spec.SchemaProps{ - Description: "Namespace of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/", - Type: []string{"string"}, - Format: "", - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name"}, - }, - }, - } -} - -func schema_kmodulesxyz_client_go_api_v1_X509Subject(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "X509Subject Full X509 name specification", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "organizations": { - SchemaProps: spec.SchemaProps{ - Description: "Organizations to be used on the Certificate.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "countries": { - SchemaProps: spec.SchemaProps{ - Description: "Countries to be used on the CertificateSpec.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "organizationalUnits": { - SchemaProps: spec.SchemaProps{ - Description: "Organizational Units to be used on the CertificateSpec.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "localities": { - SchemaProps: spec.SchemaProps{ - Description: "Cities to be used on the CertificateSpec.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "provinces": { - SchemaProps: spec.SchemaProps{ - Description: "State/Provinces to be used on the CertificateSpec.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "streetAddresses": { - SchemaProps: spec.SchemaProps{ - Description: "Street addresses to be used on the CertificateSpec.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "postalCodes": { - SchemaProps: spec.SchemaProps{ - Description: "Postal codes to be used on the CertificateSpec.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "serialNumber": { - SchemaProps: spec.SchemaProps{ - Description: "Serial number to be used on the CertificateSpec.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_kmodulesxyz_client_go_api_v1_stringSetMerger(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - }, - }, - } -} diff --git a/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/register.go b/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/register.go deleted file mode 100644 index 68d0514f1..000000000 --- a/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/register.go +++ /dev/null @@ -1,62 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import ( - "go.bytebuilders.dev/license-proxyserver/apis/proxyserver" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -var SchemeGroupVersion = schema.GroupVersion{Group: proxyserver.GroupName, Version: "v1alpha1"} - -var ( - // TODO: move SchemeBuilder with zz_generated.deepcopy.go to k8s.io/api. - // localSchemeBuilder and AddToScheme will stay in k8s.io/kubernetes. - SchemeBuilder runtime.SchemeBuilder - localSchemeBuilder = &SchemeBuilder - AddToScheme = localSchemeBuilder.AddToScheme -) - -func init() { - // We only register manually written functions here. The registration of the - // generated functions takes place in the generated files. The separation - // makes the code compile even when the generated files are missing. - localSchemeBuilder.Register(addKnownTypes) -} - -// Resource takes an unqualified resource and returns a Group qualified GroupResource -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} - -// Adds the list of known types to api.Scheme. -func addKnownTypes(scheme *runtime.Scheme) error { - scheme.AddKnownTypes(SchemeGroupVersion, - &LicenseRequest{}, - &LicenseStatusList{}, - &LicenseStatus{}, - ) - - scheme.AddKnownTypes(SchemeGroupVersion, - &metav1.Status{}, - ) - metav1.AddToGroupVersion(scheme, SchemeGroupVersion) - return nil -} diff --git a/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/zz_generated.deepcopy.go b/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/zz_generated.deepcopy.go deleted file mode 100644 index 06906c4da..000000000 --- a/vendor/go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1/zz_generated.deepcopy.go +++ /dev/null @@ -1,265 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright AppsCode Inc. and Contributors. - -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. -*/ - -// Code generated by deepcopy-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - licensesv1alpha1 "go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1" - - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in ExtraValue) DeepCopyInto(out *ExtraValue) { - { - in := &in - *out = make(ExtraValue, len(*in)) - copy(*out, *in) - return - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExtraValue. -func (in ExtraValue) DeepCopy() ExtraValue { - if in == nil { - return nil - } - out := new(ExtraValue) - in.DeepCopyInto(out) - return *out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *LicenseRequest) DeepCopyInto(out *LicenseRequest) { - *out = *in - out.TypeMeta = in.TypeMeta - if in.Request != nil { - in, out := &in.Request, &out.Request - *out = new(LicenseRequestRequest) - (*in).DeepCopyInto(*out) - } - if in.Response != nil { - in, out := &in.Response, &out.Response - *out = new(LicenseRequestResponse) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LicenseRequest. -func (in *LicenseRequest) DeepCopy() *LicenseRequest { - if in == nil { - return nil - } - out := new(LicenseRequest) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *LicenseRequest) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *LicenseRequestRequest) DeepCopyInto(out *LicenseRequestRequest) { - *out = *in - if in.Features != nil { - in, out := &in.Features, &out.Features - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LicenseRequestRequest. -func (in *LicenseRequestRequest) DeepCopy() *LicenseRequestRequest { - if in == nil { - return nil - } - out := new(LicenseRequestRequest) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *LicenseRequestResponse) DeepCopyInto(out *LicenseRequestResponse) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LicenseRequestResponse. -func (in *LicenseRequestResponse) DeepCopy() *LicenseRequestResponse { - if in == nil { - return nil - } - out := new(LicenseRequestResponse) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *LicenseStatus) DeepCopyInto(out *LicenseStatus) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LicenseStatus. -func (in *LicenseStatus) DeepCopy() *LicenseStatus { - if in == nil { - return nil - } - out := new(LicenseStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *LicenseStatus) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *LicenseStatusList) DeepCopyInto(out *LicenseStatusList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]LicenseStatus, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LicenseStatusList. -func (in *LicenseStatusList) DeepCopy() *LicenseStatusList { - if in == nil { - return nil - } - out := new(LicenseStatusList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *LicenseStatusList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *LicenseStatusSpec) DeepCopyInto(out *LicenseStatusSpec) { - *out = *in - if in.Feature != nil { - in, out := &in.Feature, &out.Feature - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.User != nil { - in, out := &in.User, &out.User - *out = new(UserInfo) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LicenseStatusSpec. -func (in *LicenseStatusSpec) DeepCopy() *LicenseStatusSpec { - if in == nil { - return nil - } - out := new(LicenseStatusSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *LicenseStatusStatus) DeepCopyInto(out *LicenseStatusStatus) { - *out = *in - if in.Contract != nil { - in, out := &in.Contract, &out.Contract - *out = new(licensesv1alpha1.Contract) - (*in).DeepCopyInto(*out) - } - in.License.DeepCopyInto(&out.License) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LicenseStatusStatus. -func (in *LicenseStatusStatus) DeepCopy() *LicenseStatusStatus { - if in == nil { - return nil - } - out := new(LicenseStatusStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *UserInfo) DeepCopyInto(out *UserInfo) { - *out = *in - if in.Groups != nil { - in, out := &in.Groups, &out.Groups - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Extra != nil { - in, out := &in.Extra, &out.Extra - *out = make(map[string]ExtraValue, len(*in)) - for key, val := range *in { - var outVal []string - if val == nil { - (*out)[key] = nil - } else { - in, out := &val, &outVal - *out = make(ExtraValue, len(*in)) - copy(*out, *in) - } - (*out)[key] = outVal - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new UserInfo. -func (in *UserInfo) DeepCopy() *UserInfo { - if in == nil { - return nil - } - out := new(UserInfo) - in.DeepCopyInto(out) - return out -} diff --git a/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/clientset.go b/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/clientset.go deleted file mode 100644 index 90d3acd56..000000000 --- a/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/clientset.go +++ /dev/null @@ -1,120 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors. - -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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package versioned - -import ( - "fmt" - "net/http" - - proxyserverv1alpha1 "go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1" - discovery "k8s.io/client-go/discovery" - rest "k8s.io/client-go/rest" - flowcontrol "k8s.io/client-go/util/flowcontrol" -) - -type Interface interface { - Discovery() discovery.DiscoveryInterface - ProxyserverV1alpha1() proxyserverv1alpha1.ProxyserverV1alpha1Interface -} - -// Clientset contains the clients for groups. -type Clientset struct { - *discovery.DiscoveryClient - proxyserverV1alpha1 *proxyserverv1alpha1.ProxyserverV1alpha1Client -} - -// ProxyserverV1alpha1 retrieves the ProxyserverV1alpha1Client -func (c *Clientset) ProxyserverV1alpha1() proxyserverv1alpha1.ProxyserverV1alpha1Interface { - return c.proxyserverV1alpha1 -} - -// Discovery retrieves the DiscoveryClient -func (c *Clientset) Discovery() discovery.DiscoveryInterface { - if c == nil { - return nil - } - return c.DiscoveryClient -} - -// NewForConfig creates a new Clientset for the given config. -// If config's RateLimiter is not set and QPS and Burst are acceptable, -// NewForConfig will generate a rate-limiter in configShallowCopy. -// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), -// where httpClient was generated with rest.HTTPClientFor(c). -func NewForConfig(c *rest.Config) (*Clientset, error) { - configShallowCopy := *c - - if configShallowCopy.UserAgent == "" { - configShallowCopy.UserAgent = rest.DefaultKubernetesUserAgent() - } - - // share the transport between all clients - httpClient, err := rest.HTTPClientFor(&configShallowCopy) - if err != nil { - return nil, err - } - - return NewForConfigAndClient(&configShallowCopy, httpClient) -} - -// NewForConfigAndClient creates a new Clientset for the given config and http client. -// Note the http client provided takes precedence over the configured transport values. -// If config's RateLimiter is not set and QPS and Burst are acceptable, -// NewForConfigAndClient will generate a rate-limiter in configShallowCopy. -func NewForConfigAndClient(c *rest.Config, httpClient *http.Client) (*Clientset, error) { - configShallowCopy := *c - if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 { - if configShallowCopy.Burst <= 0 { - return nil, fmt.Errorf("burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0") - } - configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst) - } - - var cs Clientset - var err error - cs.proxyserverV1alpha1, err = proxyserverv1alpha1.NewForConfigAndClient(&configShallowCopy, httpClient) - if err != nil { - return nil, err - } - - cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfigAndClient(&configShallowCopy, httpClient) - if err != nil { - return nil, err - } - return &cs, nil -} - -// NewForConfigOrDie creates a new Clientset for the given config and -// panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *Clientset { - cs, err := NewForConfig(c) - if err != nil { - panic(err) - } - return cs -} - -// New creates a new Clientset for the given RESTClient. -func New(c rest.Interface) *Clientset { - var cs Clientset - cs.proxyserverV1alpha1 = proxyserverv1alpha1.New(c) - - cs.DiscoveryClient = discovery.NewDiscoveryClient(c) - return &cs -} diff --git a/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/scheme/doc.go b/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/scheme/doc.go deleted file mode 100644 index 3c7f0c401..000000000 --- a/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/scheme/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors. - -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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -// This package contains the scheme of the automatically generated clientset. -package scheme diff --git a/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/scheme/register.go b/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/scheme/register.go deleted file mode 100644 index b3d159c40..000000000 --- a/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/scheme/register.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors. - -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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package scheme - -import ( - proxyserverv1alpha1 "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - serializer "k8s.io/apimachinery/pkg/runtime/serializer" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" -) - -var Scheme = runtime.NewScheme() -var Codecs = serializer.NewCodecFactory(Scheme) -var ParameterCodec = runtime.NewParameterCodec(Scheme) -var localSchemeBuilder = runtime.SchemeBuilder{ - proxyserverv1alpha1.AddToScheme, -} - -// AddToScheme adds all types of this clientset into the given scheme. This allows composition -// of clientsets, like in: -// -// import ( -// "k8s.io/client-go/kubernetes" -// clientsetscheme "k8s.io/client-go/kubernetes/scheme" -// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" -// ) -// -// kclientset, _ := kubernetes.NewForConfig(c) -// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) -// -// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types -// correctly. -var AddToScheme = localSchemeBuilder.AddToScheme - -func init() { - v1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"}) - utilruntime.Must(AddToScheme(Scheme)) -} diff --git a/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1/doc.go b/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1/doc.go deleted file mode 100644 index 76a39c90a..000000000 --- a/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors. - -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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -// This package has the automatically generated typed clients. -package v1alpha1 diff --git a/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1/generated_expansion.go b/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1/generated_expansion.go deleted file mode 100644 index edc8b7a0a..000000000 --- a/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1/generated_expansion.go +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors. - -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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -type LicenseRequestExpansion interface{} - -type LicenseStatusExpansion interface{} diff --git a/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1/licenserequest.go b/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1/licenserequest.go deleted file mode 100644 index 470233126..000000000 --- a/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1/licenserequest.go +++ /dev/null @@ -1,64 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors. - -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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - "context" - - v1alpha1 "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1" - scheme "go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - rest "k8s.io/client-go/rest" -) - -// LicenseRequestsGetter has a method to return a LicenseRequestInterface. -// A group's client should implement this interface. -type LicenseRequestsGetter interface { - LicenseRequests() LicenseRequestInterface -} - -// LicenseRequestInterface has methods to work with LicenseRequest resources. -type LicenseRequestInterface interface { - Create(ctx context.Context, licenseRequest *v1alpha1.LicenseRequest, opts v1.CreateOptions) (*v1alpha1.LicenseRequest, error) - LicenseRequestExpansion -} - -// licenseRequests implements LicenseRequestInterface -type licenseRequests struct { - client rest.Interface -} - -// newLicenseRequests returns a LicenseRequests -func newLicenseRequests(c *ProxyserverV1alpha1Client) *licenseRequests { - return &licenseRequests{ - client: c.RESTClient(), - } -} - -// Create takes the representation of a licenseRequest and creates it. Returns the server's representation of the licenseRequest, and an error, if there is any. -func (c *licenseRequests) Create(ctx context.Context, licenseRequest *v1alpha1.LicenseRequest, opts v1.CreateOptions) (result *v1alpha1.LicenseRequest, err error) { - result = &v1alpha1.LicenseRequest{} - err = c.client.Post(). - Resource("licenserequests"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(licenseRequest). - Do(ctx). - Into(result) - return -} diff --git a/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1/licensestatus.go b/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1/licensestatus.go deleted file mode 100644 index 4935fe740..000000000 --- a/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1/licensestatus.go +++ /dev/null @@ -1,82 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors. - -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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - "context" - "time" - - v1alpha1 "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1" - scheme "go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - rest "k8s.io/client-go/rest" -) - -// LicenseStatusesGetter has a method to return a LicenseStatusInterface. -// A group's client should implement this interface. -type LicenseStatusesGetter interface { - LicenseStatuses() LicenseStatusInterface -} - -// LicenseStatusInterface has methods to work with LicenseStatus resources. -type LicenseStatusInterface interface { - Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.LicenseStatus, error) - List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.LicenseStatusList, error) - LicenseStatusExpansion -} - -// licenseStatuses implements LicenseStatusInterface -type licenseStatuses struct { - client rest.Interface -} - -// newLicenseStatuses returns a LicenseStatuses -func newLicenseStatuses(c *ProxyserverV1alpha1Client) *licenseStatuses { - return &licenseStatuses{ - client: c.RESTClient(), - } -} - -// Get takes name of the licenseStatus, and returns the corresponding licenseStatus object, and an error if there is any. -func (c *licenseStatuses) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.LicenseStatus, err error) { - result = &v1alpha1.LicenseStatus{} - err = c.client.Get(). - Resource("licensestatuses"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of LicenseStatuses that match those selectors. -func (c *licenseStatuses) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.LicenseStatusList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1alpha1.LicenseStatusList{} - err = c.client.Get(). - Resource("licensestatuses"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} diff --git a/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1/proxyserver_client.go b/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1/proxyserver_client.go deleted file mode 100644 index e5b9f6ff0..000000000 --- a/vendor/go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1/proxyserver_client.go +++ /dev/null @@ -1,112 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors. - -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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - "net/http" - - v1alpha1 "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1" - "go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/scheme" - rest "k8s.io/client-go/rest" -) - -type ProxyserverV1alpha1Interface interface { - RESTClient() rest.Interface - LicenseRequestsGetter - LicenseStatusesGetter -} - -// ProxyserverV1alpha1Client is used to interact with features provided by the proxyserver.licenses.appscode.com group. -type ProxyserverV1alpha1Client struct { - restClient rest.Interface -} - -func (c *ProxyserverV1alpha1Client) LicenseRequests() LicenseRequestInterface { - return newLicenseRequests(c) -} - -func (c *ProxyserverV1alpha1Client) LicenseStatuses() LicenseStatusInterface { - return newLicenseStatuses(c) -} - -// NewForConfig creates a new ProxyserverV1alpha1Client for the given config. -// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), -// where httpClient was generated with rest.HTTPClientFor(c). -func NewForConfig(c *rest.Config) (*ProxyserverV1alpha1Client, error) { - config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } - httpClient, err := rest.HTTPClientFor(&config) - if err != nil { - return nil, err - } - return NewForConfigAndClient(&config, httpClient) -} - -// NewForConfigAndClient creates a new ProxyserverV1alpha1Client for the given config and http client. -// Note the http client provided takes precedence over the configured transport values. -func NewForConfigAndClient(c *rest.Config, h *http.Client) (*ProxyserverV1alpha1Client, error) { - config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } - client, err := rest.RESTClientForConfigAndClient(&config, h) - if err != nil { - return nil, err - } - return &ProxyserverV1alpha1Client{client}, nil -} - -// NewForConfigOrDie creates a new ProxyserverV1alpha1Client for the given config and -// panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *ProxyserverV1alpha1Client { - client, err := NewForConfig(c) - if err != nil { - panic(err) - } - return client -} - -// New creates a new ProxyserverV1alpha1Client for the given RESTClient. -func New(c rest.Interface) *ProxyserverV1alpha1Client { - return &ProxyserverV1alpha1Client{c} -} - -func setConfigDefaults(config *rest.Config) error { - gv := v1alpha1.SchemeGroupVersion - config.GroupVersion = &gv - config.APIPath = "/apis" - config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() - - if config.UserAgent == "" { - config.UserAgent = rest.DefaultKubernetesUserAgent() - } - - return nil -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *ProxyserverV1alpha1Client) RESTClient() rest.Interface { - if c == nil { - return nil - } - return c.restClient -} diff --git a/vendor/go.bytebuilders.dev/license-verifier/.gitignore b/vendor/go.bytebuilders.dev/license-verifier/.gitignore deleted file mode 100644 index 8c65b9bc4..000000000 --- a/vendor/go.bytebuilders.dev/license-verifier/.gitignore +++ /dev/null @@ -1,19 +0,0 @@ -# Binaries for programs and plugins -*.exe -*.exe~ -*.dll -*.so -*.dylib - -# Test binary, built with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -# Dependency directories (remove the comment below to include it) -vendor/ - -.idea/ -.vscode/ -.DS_Store diff --git a/vendor/go.bytebuilders.dev/license-verifier/LICENSE b/vendor/go.bytebuilders.dev/license-verifier/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/vendor/go.bytebuilders.dev/license-verifier/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - 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 "[]" - 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 - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/go.bytebuilders.dev/license-verifier/Makefile b/vendor/go.bytebuilders.dev/license-verifier/Makefile deleted file mode 100644 index 0c6cb92fb..000000000 --- a/vendor/go.bytebuilders.dev/license-verifier/Makefile +++ /dev/null @@ -1,279 +0,0 @@ -# Copyright AppsCode Inc. and Contributors -# -# 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. - -SHELL=/bin/bash -o pipefail - -GO_PKG := go.bytebuilders.dev -REPO := $(notdir $(shell pwd)) -BIN := license-verifier -COMPRESS ?= no - -# Produce CRDs that work back to Kubernetes 1.11 (no version conversion) -CRD_OPTIONS ?= "crd:maxDescLen=0,generateEmbeddedObjectMeta=true,allowDangerousTypes=true" -CODE_GENERATOR_IMAGE ?= ghcr.io/appscode/gengo:release-1.29 -API_GROUPS ?= licenses:v1alpha1 - -# Where to push the docker image. -REGISTRY ?= bytebuilders - -# This version-strategy uses git tags to set the version string -git_branch := $(shell git rev-parse --abbrev-ref HEAD) -git_tag := $(shell git describe --exact-match --abbrev=0 2>/dev/null || echo "") -commit_hash := $(shell git rev-parse --verify HEAD) -commit_timestamp := $(shell date --date="@$$(git show -s --format=%ct)" --utc +%FT%T) - -VERSION := $(shell git describe --tags --always --dirty) -version_strategy := commit_hash -ifdef git_tag - VERSION := $(git_tag) - version_strategy := tag -else - ifeq (,$(findstring $(git_branch),master HEAD)) - ifneq (,$(patsubst release-%,,$(git_branch))) - VERSION := $(git_branch) - version_strategy := branch - endif - endif -endif - -### -### These variables should not need tweaking. -### - -SRC_PKGS := apis info client # directories which hold app source excluding tests (not vendored) -SRC_DIRS := $(SRC_PKGS) *.go # directories which hold app source (not vendored) - -DOCKER_PLATFORMS := linux/amd64 linux/arm linux/arm64 -BIN_PLATFORMS := $(DOCKER_PLATFORMS) windows/amd64 darwin/amd64 - -# Used internally. Users should pass GOOS and/or GOARCH. -OS := $(if $(GOOS),$(GOOS),$(shell go env GOOS)) -ARCH := $(if $(GOARCH),$(GOARCH),$(shell go env GOARCH)) - -BASEIMAGE_PROD ?= gcr.io/distroless/static-debian11 -BASEIMAGE_DBG ?= debian:bullseye - -GO_VERSION ?= 1.21 -BUILD_IMAGE ?= ghcr.io/appscode/golang-dev:$(GO_VERSION) - -OUTBIN = bin/$(OS)_$(ARCH)/$(BIN) -ifeq ($(OS),windows) - OUTBIN = bin/$(OS)_$(ARCH)/$(BIN).exe -endif - -# Directories that we need created to build/test. -BUILD_DIRS := bin/$(OS)_$(ARCH) \ - .go/bin/$(OS)_$(ARCH) \ - .go/cache \ - hack/config \ - $(HOME)/.credentials \ - $(HOME)/.kube \ - $(HOME)/.minikube - -DOCKERFILE_TEST = Dockerfile.test - -DOCKER_REPO_ROOT := /go/src/$(GO_PKG)/$(REPO) - -# If you want to build all binaries, see the 'all-build' rule. -# If you want to build all containers, see the 'all-container' rule. -# If you want to build AND push all containers, see the 'all-push' rule. -all: fmt build - -# For the following OS/ARCH expansions, we transform OS/ARCH into OS_ARCH -# because make pattern rules don't match with embedded '/' characters. - -build-%: - @$(MAKE) build \ - --no-print-directory \ - GOOS=$(firstword $(subst _, ,$*)) \ - GOARCH=$(lastword $(subst _, ,$*)) - -all-build: $(addprefix build-, $(subst /,_, $(BIN_PLATFORMS))) - -version: - @echo ::set-output name=version::$(VERSION) - @echo ::set-output name=version_strategy::$(version_strategy) - @echo ::set-output name=git_tag::$(git_tag) - @echo ::set-output name=git_branch::$(git_branch) - @echo ::set-output name=commit_hash::$(commit_hash) - @echo ::set-output name=commit_timestamp::$(commit_timestamp) - -# Generate a typed clientset -.PHONY: clientset -clientset: - @docker run --rm \ - -u $$(id -u):$$(id -g) \ - -v /tmp:/.cache \ - -v $$(pwd):$(DOCKER_REPO_ROOT) \ - -w $(DOCKER_REPO_ROOT) \ - --env HTTP_PROXY=$(HTTP_PROXY) \ - --env HTTPS_PROXY=$(HTTPS_PROXY) \ - $(CODE_GENERATOR_IMAGE) \ - /go/src/k8s.io/code-generator/generate-groups.sh \ - deepcopy-gen \ - $(GO_PKG)/$(REPO)/client \ - $(GO_PKG)/$(REPO)/apis \ - "$(API_GROUPS)" \ - --go-header-file "./hack/license/go.txt" - -.PHONY: gen -gen: clientset - -fmt: $(BUILD_DIRS) - @docker run \ - -i \ - --rm \ - -u $$(id -u):$$(id -g) \ - -v $$(pwd):/src \ - -w /src \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin/$(OS)_$(ARCH) \ - -v $$(pwd)/.go/cache:/.cache \ - --env HTTP_PROXY=$(HTTP_PROXY) \ - --env HTTPS_PROXY=$(HTTPS_PROXY) \ - $(BUILD_IMAGE) \ - /bin/bash -c " \ - REPO_PKG=$(GO_PKG) \ - ./hack/fmt.sh $(SRC_DIRS) \ - " - -build: $(OUTBIN) - -.PHONY: .go/$(OUTBIN) -$(OUTBIN): $(BUILD_DIRS) - @echo "making $(OUTBIN)" - @docker run \ - -i \ - --rm \ - -u $$(id -u):$$(id -g) \ - -v $$(pwd):/src \ - -w /src \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin/$(OS)_$(ARCH) \ - -v $$(pwd)/.go/cache:/.cache \ - --env HTTP_PROXY=$(HTTP_PROXY) \ - --env HTTPS_PROXY=$(HTTPS_PROXY) \ - $(BUILD_IMAGE) \ - /bin/bash -c " \ - ARCH=$(ARCH) \ - OS=$(OS) \ - VERSION=$(VERSION) \ - version_strategy=$(version_strategy) \ - git_branch=$(git_branch) \ - git_tag=$(git_tag) \ - commit_hash=$(commit_hash) \ - commit_timestamp=$(commit_timestamp) \ - ./hack/build.sh \ - " - @echo - -.PHONY: test -test: unit-tests - -unit-tests: $(BUILD_DIRS) - @docker run \ - -i \ - --rm \ - -u $$(id -u):$$(id -g) \ - -v $$(pwd):/src \ - -w /src \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin/$(OS)_$(ARCH) \ - -v $$(pwd)/.go/cache:/.cache \ - --env HTTP_PROXY=$(HTTP_PROXY) \ - --env HTTPS_PROXY=$(HTTPS_PROXY) \ - $(BUILD_IMAGE) \ - /bin/bash -c " \ - ARCH=$(ARCH) \ - OS=$(OS) \ - VERSION=$(VERSION) \ - ./hack/test.sh $(SRC_PKGS) \ - " - -ADDTL_LINTERS := goconst,gofmt,goimports,unparam - -.PHONY: lint -lint: $(BUILD_DIRS) - @echo "running linter" - @docker run \ - -i \ - --rm \ - -u $$(id -u):$$(id -g) \ - -v $$(pwd):/src \ - -w /src \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin/$(OS)_$(ARCH) \ - -v $$(pwd)/.go/cache:/.cache \ - --env HTTP_PROXY=$(HTTP_PROXY) \ - --env HTTPS_PROXY=$(HTTPS_PROXY) \ - --env GO111MODULE=on \ - --env GOFLAGS="-mod=vendor" \ - $(BUILD_IMAGE) \ - golangci-lint run --enable $(ADDTL_LINTERS) --deadline=10m --skip-files="generated.*\.go$\" --skip-dirs-use-default --skip-dirs=client,vendor - -$(BUILD_DIRS): - @mkdir -p $@ - -.PHONY: dev -dev: gen fmt push - -.PHONY: verify -verify: verify-gen verify-modules - -.PHONY: verify-modules -verify-modules: - GO111MODULE=on go mod tidy - GO111MODULE=on go mod vendor - @if !(git diff --exit-code HEAD); then \ - echo "go module files are out of date"; exit 1; \ - fi - -.PHONY: verify-gen -verify-gen: gen fmt - @if !(git diff --exit-code HEAD); then \ - echo "generated files are out of date, run make gen"; exit 1; \ - fi - -.PHONY: add-license -add-license: - @echo "Adding license header" - @docker run --rm \ - -u $$(id -u):$$(id -g) \ - -v /tmp:/.cache \ - -v $$(pwd):$(DOCKER_REPO_ROOT) \ - -w $(DOCKER_REPO_ROOT) \ - --env HTTP_PROXY=$(HTTP_PROXY) \ - --env HTTPS_PROXY=$(HTTPS_PROXY) \ - $(BUILD_IMAGE) \ - ltag -t "./hack/license" --excludes "vendor contrib libbuild" -v - -.PHONY: check-license -check-license: - @echo "Checking files for license header" - @docker run --rm \ - -u $$(id -u):$$(id -g) \ - -v /tmp:/.cache \ - -v $$(pwd):$(DOCKER_REPO_ROOT) \ - -w $(DOCKER_REPO_ROOT) \ - --env HTTP_PROXY=$(HTTP_PROXY) \ - --env HTTPS_PROXY=$(HTTPS_PROXY) \ - $(BUILD_IMAGE) \ - ltag -t "./hack/license" --excludes "vendor contrib libbuild" --check -v - -.PHONY: ci -ci: verify check-license lint build unit-tests #cover - -.PHONY: clean -clean: - rm -rf .go bin diff --git a/vendor/go.bytebuilders.dev/license-verifier/README.md b/vendor/go.bytebuilders.dev/license-verifier/README.md deleted file mode 100644 index 47c08bb70..000000000 --- a/vendor/go.bytebuilders.dev/license-verifier/README.md +++ /dev/null @@ -1,4 +0,0 @@ -[![PkgGoDev](https://pkg.go.dev/badge/go.bytebuilders.dev/license-verifier)](https://pkg.go.dev/go.bytebuilders.dev/license-verifier) - -# license-verifier -Library for verifying license diff --git a/vendor/go.bytebuilders.dev/license-verifier/apis/licenses/register.go b/vendor/go.bytebuilders.dev/license-verifier/apis/licenses/register.go deleted file mode 100644 index 444e532df..000000000 --- a/vendor/go.bytebuilders.dev/license-verifier/apis/licenses/register.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 licenses - -// GroupName is the group name use in this package -const GroupName = "licenses.appscode.com" diff --git a/vendor/go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1/doc.go b/vendor/go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1/doc.go deleted file mode 100644 index f3bdff002..000000000 --- a/vendor/go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1/doc.go +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 is the v1alpha1 version of the API. - -// +k8s:deepcopy-gen=package,register -// +k8s:conversion-gen=go.bytebuilders.dev/license-verifier/apis/licenses -// +k8s:openapi-gen=true -// +k8s:defaulter-gen=TypeMeta - -// +groupName=licenses.appscode.com -package v1alpha1 diff --git a/vendor/go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1/helper.go b/vendor/go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1/helper.go deleted file mode 100644 index 0221b461b..000000000 --- a/vendor/go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1/helper.go +++ /dev/null @@ -1,62 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -func (l License) DisableAnalytics() bool { - return len(l.FeatureFlags) > 0 && l.FeatureFlags["DisableAnalytics"] == "true" -} - -func (i *License) Less(j *License) bool { - if i == nil { - return true - } else if j == nil { - return false - } - - iRank := rankTier(i.TierName) - jRank := rankTier(j.TierName) - if iRank != jRank { - return iRank < jRank - } - - if i.NotBefore == nil { - return true - } else if j.NotBefore == nil { - return false - } - if !i.NotBefore.Equal(j.NotBefore) { - return i.NotBefore.Before(j.NotBefore) - } - - if i.NotAfter == nil { - return true - } else if j.NotAfter == nil { - return false - } - return i.NotAfter.Before(j.NotAfter) -} - -func rankTier(t string) int { - // prefer enterprise licenses in a min priority queue - if t == "enterprise" { - return 0 - } else if t == "" { - return 2 - } else { - return 1 - } -} diff --git a/vendor/go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1/register.go b/vendor/go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1/register.go deleted file mode 100644 index 3dc4f93d6..000000000 --- a/vendor/go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1/register.go +++ /dev/null @@ -1,60 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import ( - "go.bytebuilders.dev/license-verifier/apis/licenses" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -var SchemeGroupVersion = schema.GroupVersion{Group: licenses.GroupName, Version: "v1alpha1"} - -var ( - // TODO: move SchemeBuilder with zz_generated.deepcopy.go to k8s.io/api. - // localSchemeBuilder and AddToScheme will stay in k8s.io/kubernetes. - SchemeBuilder runtime.SchemeBuilder - localSchemeBuilder = &SchemeBuilder - AddToScheme = localSchemeBuilder.AddToScheme -) - -func init() { - // We only register manually written functions here. The registration of the - // generated functions takes place in the generated files. The separation - // makes the code compile even when the generated files are missing. - localSchemeBuilder.Register(addKnownTypes) -} - -// Resource takes an unqualified resource and returns a Group qualified GroupResource -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} - -// Adds the list of known types to api.Scheme. -func addKnownTypes(scheme *runtime.Scheme) error { - scheme.AddKnownTypes(SchemeGroupVersion, - &License{}, - ) - - scheme.AddKnownTypes(SchemeGroupVersion, - &metav1.Status{}, - ) - metav1.AddToGroupVersion(scheme, SchemeGroupVersion) - return nil -} diff --git a/vendor/go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1/types.go b/vendor/go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1/types.go deleted file mode 100644 index eb8d56217..000000000 --- a/vendor/go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1/types.go +++ /dev/null @@ -1,64 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// License defines a AppsCode product license info. -type License struct { - metav1.TypeMeta `json:",inline,omitempty"` - - Data []byte `json:"-"` - Issuer string `json:"issuer,omitempty"` // byte.builders - ProductLine string `json:"productLine,omitempty"` - TierName string `json:"tierName,omitempty"` - PlanName string `json:"planName,omitempty"` - Features []string `json:"features,omitempty"` - FeatureFlags map[string]string `json:"featureFlags,omitempty"` - Clusters []string `json:"clusters,omitempty"` // cluster_id ? - User *User `json:"user,omitempty"` - NotBefore *metav1.Time `json:"notBefore,omitempty"` // start of subscription start - NotAfter *metav1.Time `json:"notAfter,omitempty"` // if set, use this - ID string `json:"id,omitempty"` // license ID - Status LicenseStatus `json:"status"` - Reason string `json:"reason"` -} - -type User struct { - Name string `json:"name"` - Email string `json:"email"` -} - -// +kubebuilder:validation:Enum=unknown;active;invalid;canceled -type LicenseStatus string - -const ( - LicenseUnknown LicenseStatus = "unknown" - LicenseActive LicenseStatus = "active" - LicenseInvalid LicenseStatus = "invalid" - LicenseCanceled LicenseStatus = "canceled" -) - -type Contract struct { - ID string `json:"id"` - StartTimestamp metav1.Time `json:"startTimestamp"` - ExpiryTimestamp metav1.Time `json:"expiryTimestamp"` -} diff --git a/vendor/go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1/zz_generated.deepcopy.go b/vendor/go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1/zz_generated.deepcopy.go deleted file mode 100644 index a191107c0..000000000 --- a/vendor/go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1/zz_generated.deepcopy.go +++ /dev/null @@ -1,120 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright AppsCode Inc. and Contributors - -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. -*/ - -// Code generated by deepcopy-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Contract) DeepCopyInto(out *Contract) { - *out = *in - in.StartTimestamp.DeepCopyInto(&out.StartTimestamp) - in.ExpiryTimestamp.DeepCopyInto(&out.ExpiryTimestamp) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Contract. -func (in *Contract) DeepCopy() *Contract { - if in == nil { - return nil - } - out := new(Contract) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *License) DeepCopyInto(out *License) { - *out = *in - out.TypeMeta = in.TypeMeta - if in.Data != nil { - in, out := &in.Data, &out.Data - *out = make([]byte, len(*in)) - copy(*out, *in) - } - if in.Features != nil { - in, out := &in.Features, &out.Features - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.FeatureFlags != nil { - in, out := &in.FeatureFlags, &out.FeatureFlags - *out = make(map[string]string, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - if in.Clusters != nil { - in, out := &in.Clusters, &out.Clusters - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.User != nil { - in, out := &in.User, &out.User - *out = new(User) - **out = **in - } - if in.NotBefore != nil { - in, out := &in.NotBefore, &out.NotBefore - *out = (*in).DeepCopy() - } - if in.NotAfter != nil { - in, out := &in.NotAfter, &out.NotAfter - *out = (*in).DeepCopy() - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new License. -func (in *License) DeepCopy() *License { - if in == nil { - return nil - } - out := new(License) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *License) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *User) DeepCopyInto(out *User) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new User. -func (in *User) DeepCopy() *User { - if in == nil { - return nil - } - out := new(User) - in.DeepCopyInto(out) - return out -} diff --git a/vendor/go.bytebuilders.dev/license-verifier/info/lib.go b/vendor/go.bytebuilders.dev/license-verifier/info/lib.go deleted file mode 100644 index 060595e63..000000000 --- a/vendor/go.bytebuilders.dev/license-verifier/info/lib.go +++ /dev/null @@ -1,192 +0,0 @@ -/* -Copyright AppsCode Inc. - -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 info - -import ( - "bytes" - "crypto/x509" - "encoding/pem" - "errors" - "io" - "net/http" - "net/url" - "path" - "strconv" - "strings" - "unicode" - - "go.bytebuilders.dev/license-verifier/apis/licenses" - - "github.com/PuerkitoBio/purell" - apierrors "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/sets" -) - -var ( - EnforceLicense string - LicenseCA string - - ProductOwnerName string - ProductOwnerUID string - - ProductName string // This has been renamed to Features - ProductUID string - - QADomain = "appscode.ninja" - ProdDomain = "appscode.com" - DeprecatedProdDomain = "byte.builders" - - registrationAPIPath = "api/v1/register" - LicenseIssuerAPIPath = "api/v1/license/issue" -) - -func Features() []string { - return ParseFeatures(ProductName) -} - -func ParseFeatures(features string) []string { - out := strings.FieldsFunc(features, func(r rune) bool { - return unicode.IsSpace(r) || r == ',' || r == ';' - }) - return sets.NewString(out...).List() -} - -func SkipLicenseVerification() bool { - v, _ := strconv.ParseBool(EnforceLicense) - return !v -} - -func MustRegistrationAPIEndpoint() string { - r, err := RegistrationAPIEndpoint() - if err != nil { - panic(err) - } - return r -} - -func RegistrationAPIEndpoint(override ...string) (string, error) { - u, err := APIServerAddress(override...) - if err != nil { - return "", err - } - u.Path = path.Join(u.Path, registrationAPIPath) - return u.String(), nil -} - -func MustLicenseIssuerAPIEndpoint() string { - r, err := LicenseIssuerAPIEndpoint() - if err != nil { - panic(err) - } - return r -} - -func LicenseIssuerAPIEndpoint(override ...string) (string, error) { - u, err := APIServerAddress(override...) - if err != nil { - return "", err - } - u.Path = path.Join(u.Path, LicenseIssuerAPIPath) - return u.String(), nil -} - -func MustAPIServerAddress() *url.URL { - u, err := APIServerAddress() - if err != nil { - panic(err) - } - return u -} - -func APIServerAddress(override ...string) (*url.URL, error) { - if len(override) > 0 && override[0] != "" { - nu, err := purell.NormalizeURLString(override[0], - purell.FlagsUsuallySafeGreedy|purell.FlagRemoveDuplicateSlashes) - if err != nil { - return nil, err - } - return url.Parse(nu) - } - - if SkipLicenseVerification() { - return url.Parse("https://api." + QADomain) - } - return url.Parse("https://api." + ProdDomain) -} - -func HostedEndpoint(u string) (bool, error) { - nu, err := purell.NormalizeURLString(u, - purell.FlagsUsuallySafeGreedy|purell.FlagRemoveDuplicateSlashes) - if err != nil { - return false, err - } - u2, err := url.Parse(nu) - if err != nil { - return false, err - } - return HostedDomain(u2.Hostname()), nil -} - -func HostedDomain(d string) bool { - return d == ProdDomain || - d == DeprecatedProdDomain || - d == QADomain || - strings.HasSuffix(d, "."+ProdDomain) || - strings.HasSuffix(d, "."+DeprecatedProdDomain) || - strings.HasSuffix(d, "."+QADomain) -} - -func LoadLicenseCA() ([]byte, error) { - if LicenseCA != "" { - return []byte(LicenseCA), nil - } - - resp, err := http.Get("https://licenses.appscode.com/certificates/ca.crt") - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var buf bytes.Buffer - _, err = io.Copy(&buf, resp.Body) - if err != nil { - return nil, err - } - - if resp.StatusCode != http.StatusOK { - return nil, apierrors.NewGenericServerResponse( - resp.StatusCode, - http.MethodPost, - schema.GroupResource{Group: licenses.GroupName, Resource: "License"}, - "LicenseCA", - buf.String(), - 0, - false, - ) - } - return buf.Bytes(), nil -} - -func ParseCertificate(data []byte) (*x509.Certificate, error) { - block, _ := pem.Decode(data) - if block == nil { - // This probably is a JWT token, should be check for that when ready - return nil, errors.New("failed to parse certificate PEM") - } - return x509.ParseCertificate(block.Bytes) -} diff --git a/vendor/go.bytebuilders.dev/license-verifier/kubernetes/.gitignore b/vendor/go.bytebuilders.dev/license-verifier/kubernetes/.gitignore deleted file mode 100644 index 874028e78..000000000 --- a/vendor/go.bytebuilders.dev/license-verifier/kubernetes/.gitignore +++ /dev/null @@ -1,37 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof - -/bin -/.go - -/.idea -/.markdownlint.json -/.vscode -/apiserver.local.config -/coverage.txt -/dist -/hack/config/.env -/test/e2e/junit.xml -/test/e2e/report.xml - -.terraform -*.tfstate* diff --git a/vendor/go.bytebuilders.dev/license-verifier/kubernetes/LICENSE b/vendor/go.bytebuilders.dev/license-verifier/kubernetes/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/vendor/go.bytebuilders.dev/license-verifier/kubernetes/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - 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 "[]" - 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 - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/go.bytebuilders.dev/license-verifier/kubernetes/Makefile b/vendor/go.bytebuilders.dev/license-verifier/kubernetes/Makefile deleted file mode 100644 index 10b65999d..000000000 --- a/vendor/go.bytebuilders.dev/license-verifier/kubernetes/Makefile +++ /dev/null @@ -1,279 +0,0 @@ -# Copyright AppsCode Inc. and Contributors -# -# 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. - -SHELL=/bin/bash -o pipefail - -GO_PKG := go.bytebuilders.dev/license-verifier -REPO := $(notdir $(shell pwd)) -BIN := kubernetes -COMPRESS ?= no - -# Produce CRDs that work back to Kubernetes 1.11 (no version conversion) -CRD_OPTIONS ?= "crd:maxDescLen=0,generateEmbeddedObjectMeta=true,allowDangerousTypes=true" -CODE_GENERATOR_IMAGE ?= appscode/gengo:release-1.25 -API_GROUPS ?= licenses:v1alpha1 - -# Where to push the docker image. -REGISTRY ?= bytebuilders - -# This version-strategy uses git tags to set the version string -git_branch := $(shell git rev-parse --abbrev-ref HEAD) -git_tag := $(shell git describe --exact-match --abbrev=0 2>/dev/null || echo "") -commit_hash := $(shell git rev-parse --verify HEAD) -commit_timestamp := $(shell date --date="@$$(git show -s --format=%ct)" --utc +%FT%T) - -VERSION := $(shell git describe --tags --always --dirty) -version_strategy := commit_hash -ifdef git_tag - VERSION := $(git_tag) - version_strategy := tag -else - ifeq (,$(findstring $(git_branch),master HEAD)) - ifneq (,$(patsubst release-%,,$(git_branch))) - VERSION := $(git_branch) - version_strategy := branch - endif - endif -endif - -### -### These variables should not need tweaking. -### - -SRC_PKGS := # directories which hold app source excluding tests (not vendored) -SRC_DIRS := $(SRC_PKGS) *.go # directories which hold app source (not vendored) - -DOCKER_PLATFORMS := linux/amd64 linux/arm linux/arm64 -BIN_PLATFORMS := $(DOCKER_PLATFORMS) windows/amd64 darwin/amd64 - -# Used internally. Users should pass GOOS and/or GOARCH. -OS := $(if $(GOOS),$(GOOS),$(shell go env GOOS)) -ARCH := $(if $(GOARCH),$(GOARCH),$(shell go env GOARCH)) - -BASEIMAGE_PROD ?= gcr.io/distroless/static -BASEIMAGE_DBG ?= debian:stretch - -GO_VERSION ?= 1.20 -BUILD_IMAGE ?= ghcr.io/appscode/golang-dev:$(GO_VERSION) - -OUTBIN = bin/$(OS)_$(ARCH)/$(BIN) -ifeq ($(OS),windows) - OUTBIN = bin/$(OS)_$(ARCH)/$(BIN).exe -endif - -# Directories that we need created to build/test. -BUILD_DIRS := bin/$(OS)_$(ARCH) \ - .go/bin/$(OS)_$(ARCH) \ - .go/cache \ - hack/config \ - $(HOME)/.credentials \ - $(HOME)/.kube \ - $(HOME)/.minikube - -DOCKERFILE_TEST = Dockerfile.test - -DOCKER_REPO_ROOT := /go/src/$(GO_PKG)/$(REPO) - -# If you want to build all binaries, see the 'all-build' rule. -# If you want to build all containers, see the 'all-container' rule. -# If you want to build AND push all containers, see the 'all-push' rule. -all: fmt build - -# For the following OS/ARCH expansions, we transform OS/ARCH into OS_ARCH -# because make pattern rules don't match with embedded '/' characters. - -build-%: - @$(MAKE) build \ - --no-print-directory \ - GOOS=$(firstword $(subst _, ,$*)) \ - GOARCH=$(lastword $(subst _, ,$*)) - -all-build: $(addprefix build-, $(subst /,_, $(BIN_PLATFORMS))) - -version: - @echo ::set-output name=version::$(VERSION) - @echo ::set-output name=version_strategy::$(version_strategy) - @echo ::set-output name=git_tag::$(git_tag) - @echo ::set-output name=git_branch::$(git_branch) - @echo ::set-output name=commit_hash::$(commit_hash) - @echo ::set-output name=commit_timestamp::$(commit_timestamp) - -# Generate a typed clientset -.PHONY: clientset -clientset: - @docker run --rm \ - -u $$(id -u):$$(id -g) \ - -v /tmp:/.cache \ - -v $$(pwd):$(DOCKER_REPO_ROOT) \ - -w $(DOCKER_REPO_ROOT) \ - --env HTTP_PROXY=$(HTTP_PROXY) \ - --env HTTPS_PROXY=$(HTTPS_PROXY) \ - $(CODE_GENERATOR_IMAGE) \ - /go/src/k8s.io/code-generator/generate-groups.sh \ - deepcopy-gen \ - $(GO_PKG)/$(REPO)/client \ - $(GO_PKG)/$(REPO)/apis \ - "$(API_GROUPS)" \ - --go-header-file "./hack/license/go.txt" - -.PHONY: gen -gen: clientset - -fmt: $(BUILD_DIRS) - @docker run \ - -i \ - --rm \ - -u $$(id -u):$$(id -g) \ - -v $$(pwd):/src \ - -w /src \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin/$(OS)_$(ARCH) \ - -v $$(pwd)/.go/cache:/.cache \ - --env HTTP_PROXY=$(HTTP_PROXY) \ - --env HTTPS_PROXY=$(HTTPS_PROXY) \ - $(BUILD_IMAGE) \ - /bin/bash -c " \ - REPO_PKG=$(GO_PKG) \ - ./hack/fmt.sh $(SRC_DIRS) \ - " - -build: $(OUTBIN) - -.PHONY: .go/$(OUTBIN) -$(OUTBIN): $(BUILD_DIRS) - @echo "making $(OUTBIN)" - @docker run \ - -i \ - --rm \ - -u $$(id -u):$$(id -g) \ - -v $$(pwd):/src \ - -w /src \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin/$(OS)_$(ARCH) \ - -v $$(pwd)/.go/cache:/.cache \ - --env HTTP_PROXY=$(HTTP_PROXY) \ - --env HTTPS_PROXY=$(HTTPS_PROXY) \ - $(BUILD_IMAGE) \ - /bin/bash -c " \ - ARCH=$(ARCH) \ - OS=$(OS) \ - VERSION=$(VERSION) \ - version_strategy=$(version_strategy) \ - git_branch=$(git_branch) \ - git_tag=$(git_tag) \ - commit_hash=$(commit_hash) \ - commit_timestamp=$(commit_timestamp) \ - ./hack/build.sh \ - " - @echo - -.PHONY: test -test: unit-tests - -unit-tests: $(BUILD_DIRS) - @docker run \ - -i \ - --rm \ - -u $$(id -u):$$(id -g) \ - -v $$(pwd):/src \ - -w /src \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin/$(OS)_$(ARCH) \ - -v $$(pwd)/.go/cache:/.cache \ - --env HTTP_PROXY=$(HTTP_PROXY) \ - --env HTTPS_PROXY=$(HTTPS_PROXY) \ - $(BUILD_IMAGE) \ - /bin/bash -c " \ - ARCH=$(ARCH) \ - OS=$(OS) \ - VERSION=$(VERSION) \ - ./hack/test.sh $(SRC_PKGS) \ - " - -ADDTL_LINTERS := goconst,gofmt,goimports,unparam - -.PHONY: lint -lint: $(BUILD_DIRS) - @echo "running linter" - @docker run \ - -i \ - --rm \ - -u $$(id -u):$$(id -g) \ - -v $$(pwd):/src \ - -w /src \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin/$(OS)_$(ARCH) \ - -v $$(pwd)/.go/cache:/.cache \ - --env HTTP_PROXY=$(HTTP_PROXY) \ - --env HTTPS_PROXY=$(HTTPS_PROXY) \ - --env GO111MODULE=on \ - --env GOFLAGS="-mod=vendor" \ - $(BUILD_IMAGE) \ - golangci-lint run --enable $(ADDTL_LINTERS) --deadline=10m --skip-files="generated.*\.go$\" --skip-dirs-use-default --skip-dirs=client,vendor - -$(BUILD_DIRS): - @mkdir -p $@ - -.PHONY: dev -dev: gen fmt push - -.PHONY: verify -verify: verify-modules verify-gen - -.PHONY: verify-modules -verify-modules: - GO111MODULE=on go mod tidy - GO111MODULE=on go mod vendor - @if !(git diff --exit-code HEAD); then \ - echo "go module files are out of date"; exit 1; \ - fi - -.PHONY: verify-gen -verify-gen: gen fmt - @if !(git diff --exit-code HEAD); then \ - echo "generated files are out of date, run make gen"; exit 1; \ - fi - -.PHONY: add-license -add-license: - @echo "Adding license header" - @docker run --rm \ - -u $$(id -u):$$(id -g) \ - -v /tmp:/.cache \ - -v $$(pwd):$(DOCKER_REPO_ROOT) \ - -w $(DOCKER_REPO_ROOT) \ - --env HTTP_PROXY=$(HTTP_PROXY) \ - --env HTTPS_PROXY=$(HTTPS_PROXY) \ - $(BUILD_IMAGE) \ - ltag -t "./hack/license" --excludes "vendor contrib libbuild" -v - -.PHONY: check-license -check-license: - @echo "Checking files for license header" - @docker run --rm \ - -u $$(id -u):$$(id -g) \ - -v /tmp:/.cache \ - -v $$(pwd):$(DOCKER_REPO_ROOT) \ - -w $(DOCKER_REPO_ROOT) \ - --env HTTP_PROXY=$(HTTP_PROXY) \ - --env HTTPS_PROXY=$(HTTPS_PROXY) \ - $(BUILD_IMAGE) \ - ltag -t "./hack/license" --excludes "vendor contrib libbuild" --check -v - -.PHONY: ci -ci: verify check-license lint build unit-tests #cover - -.PHONY: clean -clean: - rm -rf .go bin diff --git a/vendor/go.bytebuilders.dev/license-verifier/kubernetes/lib.go b/vendor/go.bytebuilders.dev/license-verifier/kubernetes/lib.go deleted file mode 100644 index 860720831..000000000 --- a/vendor/go.bytebuilders.dev/license-verifier/kubernetes/lib.go +++ /dev/null @@ -1,412 +0,0 @@ -/* -Copyright AppsCode Inc. - -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 kubernetes - -import ( - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "os" - "strings" - "syscall" - "time" - - "go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1" - "go.bytebuilders.dev/license-verifier/info" - - "github.com/pkg/errors" - proxyserver "go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1" - proxyclient "go.bytebuilders.dev/license-proxyserver/client/clientset/versioned" - verifier "go.bytebuilders.dev/license-verifier" - core "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/apiserver/pkg/server/mux" - "k8s.io/client-go/kubernetes" - clientscheme "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/reference" - "k8s.io/klog/v2" - "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset" - core_util "kmodules.xyz/client-go/core/v1" - "kmodules.xyz/client-go/discovery" - "kmodules.xyz/client-go/dynamic" - "kmodules.xyz/client-go/meta" - "kmodules.xyz/client-go/tools/clusterid" -) - -const ( - EventSourceLicenseVerifier = "License Verifier" - EventReasonLicenseVerificationFailed = "License Verification Failed" - - licensePath = "/appscode/license" - licenseCheckInterval = 1 * time.Hour -) - -type LicenseEnforcer struct { - licenseFile string - opts verifier.VerifyOptions - config *rest.Config - kc kubernetes.Interface -} - -// NewLicenseEnforcer returns a newly created license enforcer -func NewLicenseEnforcer(config *rest.Config, licenseFile string) (*LicenseEnforcer, error) { - le := LicenseEnforcer{ - config: config, - licenseFile: licenseFile, - opts: verifier.VerifyOptions{ - Features: info.ProductName, - }, - } - - caData, err := info.LoadLicenseCA() - if err != nil { - return &le, err - } - le.opts.CACert, err = info.ParseCertificate(caData) - if err != nil { - return &le, err - } - return &le, nil -} - -func MustLicenseEnforcer(config *rest.Config, licenseFile string) *LicenseEnforcer { - le, err := NewLicenseEnforcer(config, licenseFile) - if err != nil { - panic("failed to instantiate license enforcer, err:" + err.Error()) - } - return le -} - -func (le *LicenseEnforcer) getLicense() ([]byte, error) { - licenseBytes, err := os.ReadFile(le.licenseFile) - if errors.Is(err, os.ErrNotExist) || (err == nil && le.invalidLicense(licenseBytes)) { - req := proxyserver.LicenseRequest{ - TypeMeta: metav1.TypeMeta{}, - Request: &proxyserver.LicenseRequestRequest{ - Features: info.Features(), - }, - } - pc, err := proxyclient.NewForConfig(le.config) - if err != nil { - return nil, errors.Wrap(err, "failed create client for license-proxyserver") - } - resp, err := pc.ProxyserverV1alpha1().LicenseRequests().Create(context.TODO(), &req, metav1.CreateOptions{}) - if err != nil { - return nil, errors.Wrap(err, "failed to read license") - } - licenseBytes = []byte(resp.Response.License) - } else if err != nil { - return nil, errors.Wrap(err, "failed to read license") - } - return licenseBytes, nil -} - -func (le *LicenseEnforcer) invalidLicense(license []byte) bool { - le.opts.License = license - // We don't want to acquire license from license-proxyserver is the license file - // contains a valid license for a different product. - // We want to acquire license-proxyserver is a previously valid license has not expired. - // So, we don't check features in the license found is license file. - l, err := verifier.ParseLicense(le.opts.ParserOptions) - return sets.NewString(l.Features...).HasAny(info.ParseFeatures(le.opts.Features)...) && err != nil -} - -func (le *LicenseEnforcer) createClients() (err error) { - if le.kc == nil { - le.kc, err = kubernetes.NewForConfig(le.config) - } - return err -} - -func (le *LicenseEnforcer) acquireLicense() (err error) { - le.opts.License, err = le.getLicense() - return err -} - -func (le *LicenseEnforcer) readClusterUID() (err error) { - if le.opts.ClusterUID != "" { - return - } - le.opts.ClusterUID, err = clusterid.ClusterUID(le.kc.CoreV1().Namespaces()) - return err -} - -func (le *LicenseEnforcer) handleLicenseVerificationFailure(licenseErr error) error { - // Send interrupt so that all go-routines shut-down gracefully - // https://pracucci.com/graceful-shutdown-of-kubernetes-pods.html - // https://linuxhandbook.com/sigterm-vs-sigkill/ - // https://pracucci.com/graceful-shutdown-of-kubernetes-pods.html - //nolint:errcheck - defer func() { - // Need to send signal twice because - // we catch the first INT/TERM signal - // ref: https://github.com/kubernetes/apiserver/blob/8d97c871d91c75b81b8b4c438f4dd1eaa7f35052/pkg/server/signal.go#L47-L51 - _ = syscall.Kill(syscall.Getpid(), syscall.SIGTERM) - time.Sleep(30 * time.Second) - _ = syscall.Kill(syscall.Getpid(), syscall.SIGKILL) - }() - - // Log licenseInfo verification failure - klog.Errorln("Failed to verify license. Reason: ", licenseErr.Error()) - - // Read the namespace of current pod - namespace := meta.PodNamespace() - - // Find the root owner of this pod - owner, _, err := dynamic.DetectWorkload( - context.TODO(), - le.config, - core.SchemeGroupVersion.WithResource(core.ResourcePods.String()), - namespace, - meta.PodName(), - ) - if err != nil { - return err - } - ref, err := reference.GetReference(clientscheme.Scheme, owner) - if err != nil { - return err - } - eventMeta := metav1.ObjectMeta{ - Name: meta.NameWithSuffix(owner.GetName(), "license"), - Namespace: namespace, - } - // Create an event against the root owner specifying that the license verification failed - _, _, err = core_util.CreateOrPatchEvent(context.TODO(), le.kc, eventMeta, func(in *core.Event) *core.Event { - in.InvolvedObject = *ref - in.Type = core.EventTypeWarning - in.Source = core.EventSource{Component: EventSourceLicenseVerifier} - in.Reason = EventReasonLicenseVerificationFailed - in.Message = fmt.Sprintf("Failed to verify license. Reason: %s", licenseErr.Error()) - - if in.FirstTimestamp.IsZero() { - in.FirstTimestamp = metav1.Now() - } - in.LastTimestamp = metav1.Now() - in.Count = in.Count + 1 - - return in - }, metav1.PatchOptions{}) - return err -} - -// Install adds the License info handler -func (le *LicenseEnforcer) Install(c *mux.PathRecorderMux) { - // Create Kubernetes client - err := le.createClients() - if err != nil { - klog.Fatal(err) - return - } - c.Handle(licensePath, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("x-content-type-options", "nosniff") - - utilruntime.Must(json.NewEncoder(w).Encode(le.LoadLicense())) - })) -} - -func (le *LicenseEnforcer) LoadLicense() v1alpha1.License { - utilruntime.Must(le.createClients()) - - // Read cluster UID (UID of the "kube-system" namespace) - err := le.readClusterUID() - if err != nil { - license, _ := verifier.BadLicense(err) - return license - } - // Read license from file - err = le.acquireLicense() - if err != nil { - license, _ := verifier.BadLicense(err) - return license - } - license, _ := verifier.CheckLicense(le.opts) - return license -} - -// VerifyLicensePeriodically periodically verifies whether the provided license is valid for the current cluster or not. -func VerifyLicensePeriodically(config *rest.Config, licenseFile string, stopCh <-chan struct{}) error { - if info.SkipLicenseVerification() { - klog.Infoln("License verification skipped") - return nil - } - - le, err := NewLicenseEnforcer(config, licenseFile) - if err != nil { - return le.handleLicenseVerificationFailure(err) - } - if err := verifyLicensePeriodically(le, licenseFile, stopCh); err != nil { - return le.handleLicenseVerificationFailure(err) - } - return nil -} - -func verifyLicensePeriodically(le *LicenseEnforcer, licenseFile string, stopCh <-chan struct{}) error { - // Create Kubernetes client - err := le.createClients() - if err != nil { - return err - } - // Read cluster UID (UID of the "kube-system" namespace) - err = le.readClusterUID() - if err != nil { - return err - } - - // Periodically verify license with 1 hour interval - fn := func() (done bool, err error) { - klog.V(8).Infoln("Verifying license.......") - // Read license from file - err = le.acquireLicense() - if err != nil { - return false, err - } - // Validate license - _, err = verifier.CheckLicense(le.opts) - if err != nil { - return false, err - } - klog.Infoln("Successfully verified license!") - // return false so that the loop never ends - return false, nil - } - - return wait.PollImmediateUntil(licenseCheckInterval, fn, stopCh) -} - -// CheckLicenseFile verifies whether the provided license is valid for the current cluster or not. -func CheckLicenseFile(config *rest.Config, licenseFile string) error { - if info.SkipLicenseVerification() { - klog.Infoln("License verification skipped") - return nil - } - - klog.V(8).Infoln("Verifying license.......") - le, err := NewLicenseEnforcer(config, licenseFile) - if err != nil { - return le.handleLicenseVerificationFailure(err) - } - if err := checkLicenseFile(le); err != nil { - return le.handleLicenseVerificationFailure(err) - } - return nil -} - -func checkLicenseFile(le *LicenseEnforcer) error { - // Create Kubernetes client - err := le.createClients() - if err != nil { - return err - } - // Read cluster UID (UID of the "kube-system" namespace) - err = le.readClusterUID() - if err != nil { - return err - } - // Read license from file - err = le.acquireLicense() - if err != nil { - return err - } - // Validate license - _, err = verifier.CheckLicense(le.opts) - if err != nil { - return err - } - klog.Infoln("Successfully verified license!") - return nil -} - -// CheckLicenseEndpoint verifies whether the provided api server has a valid license is valid for features. -func CheckLicenseEndpoint(config *rest.Config, apiServiceName string, features []string) error { - aggrClient, err := clientset.NewForConfig(config) - if err != nil { - return err - } - - apiSvc, err := aggrClient.ApiregistrationV1().APIServices().Get(context.TODO(), apiServiceName, metav1.GetOptions{}) - if err != nil { - return err - } - - c2 := *config - c2.CAData = apiSvc.Spec.CABundle - c2.Insecure = apiSvc.Spec.InsecureSkipTLSVerify - rt, err := rest.TransportFor(&c2) - if err != nil { - return err - } - hc := http.Client{ - Transport: rt, - Timeout: 30 * time.Second, - } - - u, err := url.Parse(fmt.Sprintf("https://%s.%s.svc", apiSvc.Spec.Service.Name, apiSvc.Spec.Service.Namespace)) - if err != nil { - return err - } - u.Path = licensePath - - resp, err := hc.Get(u.String()) - if err != nil { - return err - } - defer resp.Body.Close() - - data, err := io.ReadAll(resp.Body) - if err != nil { - return err - } - - var license v1alpha1.License - err = json.Unmarshal(data, &license) - if err != nil { - return err - } - - if license.Status != v1alpha1.LicenseActive { - return fmt.Errorf("license %s is not active, status: %s, reason: %s", license.ID, license.Status, license.Reason) - } - - if !sets.NewString(license.Features...).HasAny(features...) { - return fmt.Errorf("license %s is not valid for products %q", license.ID, strings.Join(features, ",")) - } - return nil -} - -func LicenseProvided(cfg *rest.Config, licenseFile string) bool { - if licenseFile != "" { - return true - } - - if cfg != nil { - ok, _ := discovery.HasGVK( - kubernetes.NewForConfigOrDie(cfg).Discovery(), - proxyserver.SchemeGroupVersion.String(), - proxyserver.ResourceKindLicenseRequest) - return ok - } - return false -} diff --git a/vendor/go.bytebuilders.dev/license-verifier/lib.go b/vendor/go.bytebuilders.dev/license-verifier/lib.go deleted file mode 100644 index 7ad58044c..000000000 --- a/vendor/go.bytebuilders.dev/license-verifier/lib.go +++ /dev/null @@ -1,214 +0,0 @@ -/* -Copyright AppsCode Inc. - -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 verifier - -import ( - "crypto/x509" - "fmt" - "strings" - - "go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1" - "go.bytebuilders.dev/license-verifier/info" - - "github.com/pkg/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/sets" -) - -type Options struct { - ClusterUID string `json:"clusterUID"` - Features string `json:"features"` - CACert []byte `json:"caCert,omitempty"` - License []byte `json:"license"` -} - -type ParserOptions struct { - ClusterUID string - CACert *x509.Certificate - License []byte -} - -type VerifyOptions struct { - ParserOptions - Features string -} - -func ParseLicense(opts ParserOptions) (v1alpha1.License, error) { - cert, err := info.ParseCertificate(opts.License) - if err != nil { - return BadLicense(err) - } - - roots := x509.NewCertPool() - roots.AddCert(opts.CACert) - - crtopts := x509.VerifyOptions{ - DNSName: opts.ClusterUID, - Roots: roots, - KeyUsages: []x509.ExtKeyUsage{ - x509.ExtKeyUsageClientAuth, - }, - } - - // wildcard certificate - if strings.HasPrefix(cert.Subject.CommonName, "*.") { - if len(opts.CACert.Subject.Organization) > 0 { - crtopts.DNSName = "*." + opts.CACert.Subject.Organization[0] - } - } - - license := v1alpha1.License{ - TypeMeta: metav1.TypeMeta{ - APIVersion: v1alpha1.SchemeGroupVersion.String(), - Kind: "License", - }, - Data: opts.License, - Issuer: "byte.builders", - Clusters: cert.DNSNames, - NotBefore: &metav1.Time{Time: cert.NotBefore}, - NotAfter: &metav1.Time{Time: cert.NotAfter}, - ID: cert.SerialNumber.String(), - Features: cert.Subject.Organization, - } - if len(cert.Subject.OrganizationalUnit) > 0 { - license.PlanName = cert.Subject.OrganizationalUnit[0] - } else { - // old certificate, so plan name auto detected from feature - // ref: https://github.com/appscode/offline-license-server/blob/v0.0.20/pkg/server/constants.go#L50-L59 - features := sets.NewString(cert.Subject.Organization...) - if features.Has("kubedb-enterprise") { - license.PlanName = "kubedb-enterprise" - } else if features.Has("kubedb-community") { - license.PlanName = "kubedb-community" - } else if features.Has("stash-enterprise") { - license.PlanName = "stash-enterprise" - } else if features.Has("stash-community") { - license.PlanName = "stash-community" - } - } - if len(cert.Subject.Country) > 0 { - license.ProductLine = cert.Subject.Country[0] - } - if len(cert.Subject.Province) > 0 { - license.TierName = cert.Subject.Province[0] - } - if license.ProductLine == "" || license.TierName == "" { - parts := strings.SplitN(license.PlanName, "-", 2) - if len(parts) > 0 { - license.ProductLine = parts[0] - } - if len(parts) > 1 { - license.TierName = parts[1] - } - } - license.FeatureFlags = map[string]string{} - for _, ff := range cert.Subject.Locality { - parts := strings.SplitN(ff, "=", 2) - if len(parts) == 2 { - license.FeatureFlags[parts[0]] = parts[1] - } - } - - var user *v1alpha1.User - for _, e := range cert.EmailAddresses { - parts := strings.FieldsFunc(e, func(r rune) bool { - return r == '<' || r == '>' - }) - if len(parts) == 0 { - continue - } - - if len(parts) == 1 { - email := strings.TrimSpace(parts[0]) - if user == nil { - user = &v1alpha1.User{ - Name: "", - Email: email, - } - } else if user.Email != email { - return BadLicense(fmt.Errorf("license issued to multiple emails %s", strings.Join(cert.EmailAddresses, ";"))) - } - } else { // == 2 - email := strings.TrimSpace(parts[1]) - if user == nil { - user = &v1alpha1.User{ - Name: strings.TrimSpace(parts[0]), - Email: email, - } - } else if user.Email != email { - return BadLicense(fmt.Errorf("license issued to multiple emails %s", strings.Join(cert.EmailAddresses, ";"))) - } - } - } - license.User = user - - // ref: https://github.com/appscode/gitea/blob/master/models/stripe_license.go#L117-L126 - if _, err := cert.Verify(crtopts); err != nil { - e2 := errors.Wrap(err, "failed to verify certificate") - license.Status = v1alpha1.LicenseInvalid - license.Reason = e2.Error() - return license, e2 - } - license.Status = v1alpha1.LicenseActive - return license, nil -} - -func CheckLicense(opts VerifyOptions) (v1alpha1.License, error) { - license, err := ParseLicense(opts.ParserOptions) - if err != nil { - return license, err - } - if !sets.NewString(license.Features...).HasAny(info.ParseFeatures(opts.Features)...) { - e2 := fmt.Errorf("license was not issued for %s", opts.Features) - license.Status = v1alpha1.LicenseInvalid - license.Reason = e2.Error() - return license, e2 - } - license.Status = v1alpha1.LicenseActive - return license, nil -} - -func VerifyLicense(opts Options) (v1alpha1.License, error) { - caCert, err := info.ParseCertificate(opts.CACert) - if err != nil { - return BadLicense(err) - } - - return CheckLicense(VerifyOptions{ - ParserOptions: ParserOptions{ - ClusterUID: opts.ClusterUID, - CACert: caCert, - License: opts.License, - }, - Features: opts.Features, - }) -} - -func BadLicense(err error) (v1alpha1.License, error) { - if err == nil { - // This should never happen - panic(err) - } - return v1alpha1.License{ - TypeMeta: metav1.TypeMeta{ - APIVersion: v1alpha1.SchemeGroupVersion.String(), - Kind: "License", - }, - Status: v1alpha1.LicenseUnknown, - Reason: err.Error(), - }, err -} diff --git a/vendor/golang.org/x/crypto/blake2b/blake2b.go b/vendor/golang.org/x/crypto/blake2b/blake2b.go deleted file mode 100644 index d2e98d429..000000000 --- a/vendor/golang.org/x/crypto/blake2b/blake2b.go +++ /dev/null @@ -1,291 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package blake2b implements the BLAKE2b hash algorithm defined by RFC 7693 -// and the extendable output function (XOF) BLAKE2Xb. -// -// BLAKE2b is optimized for 64-bit platforms—including NEON-enabled ARMs—and -// produces digests of any size between 1 and 64 bytes. -// For a detailed specification of BLAKE2b see https://blake2.net/blake2.pdf -// and for BLAKE2Xb see https://blake2.net/blake2x.pdf -// -// If you aren't sure which function you need, use BLAKE2b (Sum512 or New512). -// If you need a secret-key MAC (message authentication code), use the New512 -// function with a non-nil key. -// -// BLAKE2X is a construction to compute hash values larger than 64 bytes. It -// can produce hash values between 0 and 4 GiB. -package blake2b - -import ( - "encoding/binary" - "errors" - "hash" -) - -const ( - // The blocksize of BLAKE2b in bytes. - BlockSize = 128 - // The hash size of BLAKE2b-512 in bytes. - Size = 64 - // The hash size of BLAKE2b-384 in bytes. - Size384 = 48 - // The hash size of BLAKE2b-256 in bytes. - Size256 = 32 -) - -var ( - useAVX2 bool - useAVX bool - useSSE4 bool -) - -var ( - errKeySize = errors.New("blake2b: invalid key size") - errHashSize = errors.New("blake2b: invalid hash size") -) - -var iv = [8]uint64{ - 0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, - 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179, -} - -// Sum512 returns the BLAKE2b-512 checksum of the data. -func Sum512(data []byte) [Size]byte { - var sum [Size]byte - checkSum(&sum, Size, data) - return sum -} - -// Sum384 returns the BLAKE2b-384 checksum of the data. -func Sum384(data []byte) [Size384]byte { - var sum [Size]byte - var sum384 [Size384]byte - checkSum(&sum, Size384, data) - copy(sum384[:], sum[:Size384]) - return sum384 -} - -// Sum256 returns the BLAKE2b-256 checksum of the data. -func Sum256(data []byte) [Size256]byte { - var sum [Size]byte - var sum256 [Size256]byte - checkSum(&sum, Size256, data) - copy(sum256[:], sum[:Size256]) - return sum256 -} - -// New512 returns a new hash.Hash computing the BLAKE2b-512 checksum. A non-nil -// key turns the hash into a MAC. The key must be between zero and 64 bytes long. -func New512(key []byte) (hash.Hash, error) { return newDigest(Size, key) } - -// New384 returns a new hash.Hash computing the BLAKE2b-384 checksum. A non-nil -// key turns the hash into a MAC. The key must be between zero and 64 bytes long. -func New384(key []byte) (hash.Hash, error) { return newDigest(Size384, key) } - -// New256 returns a new hash.Hash computing the BLAKE2b-256 checksum. A non-nil -// key turns the hash into a MAC. The key must be between zero and 64 bytes long. -func New256(key []byte) (hash.Hash, error) { return newDigest(Size256, key) } - -// New returns a new hash.Hash computing the BLAKE2b checksum with a custom length. -// A non-nil key turns the hash into a MAC. The key must be between zero and 64 bytes long. -// The hash size can be a value between 1 and 64 but it is highly recommended to use -// values equal or greater than: -// - 32 if BLAKE2b is used as a hash function (The key is zero bytes long). -// - 16 if BLAKE2b is used as a MAC function (The key is at least 16 bytes long). -// When the key is nil, the returned hash.Hash implements BinaryMarshaler -// and BinaryUnmarshaler for state (de)serialization as documented by hash.Hash. -func New(size int, key []byte) (hash.Hash, error) { return newDigest(size, key) } - -func newDigest(hashSize int, key []byte) (*digest, error) { - if hashSize < 1 || hashSize > Size { - return nil, errHashSize - } - if len(key) > Size { - return nil, errKeySize - } - d := &digest{ - size: hashSize, - keyLen: len(key), - } - copy(d.key[:], key) - d.Reset() - return d, nil -} - -func checkSum(sum *[Size]byte, hashSize int, data []byte) { - h := iv - h[0] ^= uint64(hashSize) | (1 << 16) | (1 << 24) - var c [2]uint64 - - if length := len(data); length > BlockSize { - n := length &^ (BlockSize - 1) - if length == n { - n -= BlockSize - } - hashBlocks(&h, &c, 0, data[:n]) - data = data[n:] - } - - var block [BlockSize]byte - offset := copy(block[:], data) - remaining := uint64(BlockSize - offset) - if c[0] < remaining { - c[1]-- - } - c[0] -= remaining - - hashBlocks(&h, &c, 0xFFFFFFFFFFFFFFFF, block[:]) - - for i, v := range h[:(hashSize+7)/8] { - binary.LittleEndian.PutUint64(sum[8*i:], v) - } -} - -type digest struct { - h [8]uint64 - c [2]uint64 - size int - block [BlockSize]byte - offset int - - key [BlockSize]byte - keyLen int -} - -const ( - magic = "b2b" - marshaledSize = len(magic) + 8*8 + 2*8 + 1 + BlockSize + 1 -) - -func (d *digest) MarshalBinary() ([]byte, error) { - if d.keyLen != 0 { - return nil, errors.New("crypto/blake2b: cannot marshal MACs") - } - b := make([]byte, 0, marshaledSize) - b = append(b, magic...) - for i := 0; i < 8; i++ { - b = appendUint64(b, d.h[i]) - } - b = appendUint64(b, d.c[0]) - b = appendUint64(b, d.c[1]) - // Maximum value for size is 64 - b = append(b, byte(d.size)) - b = append(b, d.block[:]...) - b = append(b, byte(d.offset)) - return b, nil -} - -func (d *digest) UnmarshalBinary(b []byte) error { - if len(b) < len(magic) || string(b[:len(magic)]) != magic { - return errors.New("crypto/blake2b: invalid hash state identifier") - } - if len(b) != marshaledSize { - return errors.New("crypto/blake2b: invalid hash state size") - } - b = b[len(magic):] - for i := 0; i < 8; i++ { - b, d.h[i] = consumeUint64(b) - } - b, d.c[0] = consumeUint64(b) - b, d.c[1] = consumeUint64(b) - d.size = int(b[0]) - b = b[1:] - copy(d.block[:], b[:BlockSize]) - b = b[BlockSize:] - d.offset = int(b[0]) - return nil -} - -func (d *digest) BlockSize() int { return BlockSize } - -func (d *digest) Size() int { return d.size } - -func (d *digest) Reset() { - d.h = iv - d.h[0] ^= uint64(d.size) | (uint64(d.keyLen) << 8) | (1 << 16) | (1 << 24) - d.offset, d.c[0], d.c[1] = 0, 0, 0 - if d.keyLen > 0 { - d.block = d.key - d.offset = BlockSize - } -} - -func (d *digest) Write(p []byte) (n int, err error) { - n = len(p) - - if d.offset > 0 { - remaining := BlockSize - d.offset - if n <= remaining { - d.offset += copy(d.block[d.offset:], p) - return - } - copy(d.block[d.offset:], p[:remaining]) - hashBlocks(&d.h, &d.c, 0, d.block[:]) - d.offset = 0 - p = p[remaining:] - } - - if length := len(p); length > BlockSize { - nn := length &^ (BlockSize - 1) - if length == nn { - nn -= BlockSize - } - hashBlocks(&d.h, &d.c, 0, p[:nn]) - p = p[nn:] - } - - if len(p) > 0 { - d.offset += copy(d.block[:], p) - } - - return -} - -func (d *digest) Sum(sum []byte) []byte { - var hash [Size]byte - d.finalize(&hash) - return append(sum, hash[:d.size]...) -} - -func (d *digest) finalize(hash *[Size]byte) { - var block [BlockSize]byte - copy(block[:], d.block[:d.offset]) - remaining := uint64(BlockSize - d.offset) - - c := d.c - if c[0] < remaining { - c[1]-- - } - c[0] -= remaining - - h := d.h - hashBlocks(&h, &c, 0xFFFFFFFFFFFFFFFF, block[:]) - - for i, v := range h { - binary.LittleEndian.PutUint64(hash[8*i:], v) - } -} - -func appendUint64(b []byte, x uint64) []byte { - var a [8]byte - binary.BigEndian.PutUint64(a[:], x) - return append(b, a[:]...) -} - -func appendUint32(b []byte, x uint32) []byte { - var a [4]byte - binary.BigEndian.PutUint32(a[:], x) - return append(b, a[:]...) -} - -func consumeUint64(b []byte) ([]byte, uint64) { - x := binary.BigEndian.Uint64(b) - return b[8:], x -} - -func consumeUint32(b []byte) ([]byte, uint32) { - x := binary.BigEndian.Uint32(b) - return b[4:], x -} diff --git a/vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.go b/vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.go deleted file mode 100644 index 199c21d27..000000000 --- a/vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build amd64 && gc && !purego - -package blake2b - -import "golang.org/x/sys/cpu" - -func init() { - useAVX2 = cpu.X86.HasAVX2 - useAVX = cpu.X86.HasAVX - useSSE4 = cpu.X86.HasSSE41 -} - -//go:noescape -func hashBlocksAVX2(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) - -//go:noescape -func hashBlocksAVX(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) - -//go:noescape -func hashBlocksSSE4(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) - -func hashBlocks(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) { - switch { - case useAVX2: - hashBlocksAVX2(h, c, flag, blocks) - case useAVX: - hashBlocksAVX(h, c, flag, blocks) - case useSSE4: - hashBlocksSSE4(h, c, flag, blocks) - default: - hashBlocksGeneric(h, c, flag, blocks) - } -} diff --git a/vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.s b/vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.s deleted file mode 100644 index 9ae8206c2..000000000 --- a/vendor/golang.org/x/crypto/blake2b/blake2bAVX2_amd64.s +++ /dev/null @@ -1,744 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build amd64 && gc && !purego - -#include "textflag.h" - -DATA ·AVX2_iv0<>+0x00(SB)/8, $0x6a09e667f3bcc908 -DATA ·AVX2_iv0<>+0x08(SB)/8, $0xbb67ae8584caa73b -DATA ·AVX2_iv0<>+0x10(SB)/8, $0x3c6ef372fe94f82b -DATA ·AVX2_iv0<>+0x18(SB)/8, $0xa54ff53a5f1d36f1 -GLOBL ·AVX2_iv0<>(SB), (NOPTR+RODATA), $32 - -DATA ·AVX2_iv1<>+0x00(SB)/8, $0x510e527fade682d1 -DATA ·AVX2_iv1<>+0x08(SB)/8, $0x9b05688c2b3e6c1f -DATA ·AVX2_iv1<>+0x10(SB)/8, $0x1f83d9abfb41bd6b -DATA ·AVX2_iv1<>+0x18(SB)/8, $0x5be0cd19137e2179 -GLOBL ·AVX2_iv1<>(SB), (NOPTR+RODATA), $32 - -DATA ·AVX2_c40<>+0x00(SB)/8, $0x0201000706050403 -DATA ·AVX2_c40<>+0x08(SB)/8, $0x0a09080f0e0d0c0b -DATA ·AVX2_c40<>+0x10(SB)/8, $0x0201000706050403 -DATA ·AVX2_c40<>+0x18(SB)/8, $0x0a09080f0e0d0c0b -GLOBL ·AVX2_c40<>(SB), (NOPTR+RODATA), $32 - -DATA ·AVX2_c48<>+0x00(SB)/8, $0x0100070605040302 -DATA ·AVX2_c48<>+0x08(SB)/8, $0x09080f0e0d0c0b0a -DATA ·AVX2_c48<>+0x10(SB)/8, $0x0100070605040302 -DATA ·AVX2_c48<>+0x18(SB)/8, $0x09080f0e0d0c0b0a -GLOBL ·AVX2_c48<>(SB), (NOPTR+RODATA), $32 - -DATA ·AVX_iv0<>+0x00(SB)/8, $0x6a09e667f3bcc908 -DATA ·AVX_iv0<>+0x08(SB)/8, $0xbb67ae8584caa73b -GLOBL ·AVX_iv0<>(SB), (NOPTR+RODATA), $16 - -DATA ·AVX_iv1<>+0x00(SB)/8, $0x3c6ef372fe94f82b -DATA ·AVX_iv1<>+0x08(SB)/8, $0xa54ff53a5f1d36f1 -GLOBL ·AVX_iv1<>(SB), (NOPTR+RODATA), $16 - -DATA ·AVX_iv2<>+0x00(SB)/8, $0x510e527fade682d1 -DATA ·AVX_iv2<>+0x08(SB)/8, $0x9b05688c2b3e6c1f -GLOBL ·AVX_iv2<>(SB), (NOPTR+RODATA), $16 - -DATA ·AVX_iv3<>+0x00(SB)/8, $0x1f83d9abfb41bd6b -DATA ·AVX_iv3<>+0x08(SB)/8, $0x5be0cd19137e2179 -GLOBL ·AVX_iv3<>(SB), (NOPTR+RODATA), $16 - -DATA ·AVX_c40<>+0x00(SB)/8, $0x0201000706050403 -DATA ·AVX_c40<>+0x08(SB)/8, $0x0a09080f0e0d0c0b -GLOBL ·AVX_c40<>(SB), (NOPTR+RODATA), $16 - -DATA ·AVX_c48<>+0x00(SB)/8, $0x0100070605040302 -DATA ·AVX_c48<>+0x08(SB)/8, $0x09080f0e0d0c0b0a -GLOBL ·AVX_c48<>(SB), (NOPTR+RODATA), $16 - -#define VPERMQ_0x39_Y1_Y1 BYTE $0xc4; BYTE $0xe3; BYTE $0xfd; BYTE $0x00; BYTE $0xc9; BYTE $0x39 -#define VPERMQ_0x93_Y1_Y1 BYTE $0xc4; BYTE $0xe3; BYTE $0xfd; BYTE $0x00; BYTE $0xc9; BYTE $0x93 -#define VPERMQ_0x4E_Y2_Y2 BYTE $0xc4; BYTE $0xe3; BYTE $0xfd; BYTE $0x00; BYTE $0xd2; BYTE $0x4e -#define VPERMQ_0x93_Y3_Y3 BYTE $0xc4; BYTE $0xe3; BYTE $0xfd; BYTE $0x00; BYTE $0xdb; BYTE $0x93 -#define VPERMQ_0x39_Y3_Y3 BYTE $0xc4; BYTE $0xe3; BYTE $0xfd; BYTE $0x00; BYTE $0xdb; BYTE $0x39 - -#define ROUND_AVX2(m0, m1, m2, m3, t, c40, c48) \ - VPADDQ m0, Y0, Y0; \ - VPADDQ Y1, Y0, Y0; \ - VPXOR Y0, Y3, Y3; \ - VPSHUFD $-79, Y3, Y3; \ - VPADDQ Y3, Y2, Y2; \ - VPXOR Y2, Y1, Y1; \ - VPSHUFB c40, Y1, Y1; \ - VPADDQ m1, Y0, Y0; \ - VPADDQ Y1, Y0, Y0; \ - VPXOR Y0, Y3, Y3; \ - VPSHUFB c48, Y3, Y3; \ - VPADDQ Y3, Y2, Y2; \ - VPXOR Y2, Y1, Y1; \ - VPADDQ Y1, Y1, t; \ - VPSRLQ $63, Y1, Y1; \ - VPXOR t, Y1, Y1; \ - VPERMQ_0x39_Y1_Y1; \ - VPERMQ_0x4E_Y2_Y2; \ - VPERMQ_0x93_Y3_Y3; \ - VPADDQ m2, Y0, Y0; \ - VPADDQ Y1, Y0, Y0; \ - VPXOR Y0, Y3, Y3; \ - VPSHUFD $-79, Y3, Y3; \ - VPADDQ Y3, Y2, Y2; \ - VPXOR Y2, Y1, Y1; \ - VPSHUFB c40, Y1, Y1; \ - VPADDQ m3, Y0, Y0; \ - VPADDQ Y1, Y0, Y0; \ - VPXOR Y0, Y3, Y3; \ - VPSHUFB c48, Y3, Y3; \ - VPADDQ Y3, Y2, Y2; \ - VPXOR Y2, Y1, Y1; \ - VPADDQ Y1, Y1, t; \ - VPSRLQ $63, Y1, Y1; \ - VPXOR t, Y1, Y1; \ - VPERMQ_0x39_Y3_Y3; \ - VPERMQ_0x4E_Y2_Y2; \ - VPERMQ_0x93_Y1_Y1 - -#define VMOVQ_SI_X11_0 BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x1E -#define VMOVQ_SI_X12_0 BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x26 -#define VMOVQ_SI_X13_0 BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x2E -#define VMOVQ_SI_X14_0 BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x36 -#define VMOVQ_SI_X15_0 BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x3E - -#define VMOVQ_SI_X11(n) BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x5E; BYTE $n -#define VMOVQ_SI_X12(n) BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x66; BYTE $n -#define VMOVQ_SI_X13(n) BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x6E; BYTE $n -#define VMOVQ_SI_X14(n) BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x76; BYTE $n -#define VMOVQ_SI_X15(n) BYTE $0xC5; BYTE $0x7A; BYTE $0x7E; BYTE $0x7E; BYTE $n - -#define VPINSRQ_1_SI_X11_0 BYTE $0xC4; BYTE $0x63; BYTE $0xA1; BYTE $0x22; BYTE $0x1E; BYTE $0x01 -#define VPINSRQ_1_SI_X12_0 BYTE $0xC4; BYTE $0x63; BYTE $0x99; BYTE $0x22; BYTE $0x26; BYTE $0x01 -#define VPINSRQ_1_SI_X13_0 BYTE $0xC4; BYTE $0x63; BYTE $0x91; BYTE $0x22; BYTE $0x2E; BYTE $0x01 -#define VPINSRQ_1_SI_X14_0 BYTE $0xC4; BYTE $0x63; BYTE $0x89; BYTE $0x22; BYTE $0x36; BYTE $0x01 -#define VPINSRQ_1_SI_X15_0 BYTE $0xC4; BYTE $0x63; BYTE $0x81; BYTE $0x22; BYTE $0x3E; BYTE $0x01 - -#define VPINSRQ_1_SI_X11(n) BYTE $0xC4; BYTE $0x63; BYTE $0xA1; BYTE $0x22; BYTE $0x5E; BYTE $n; BYTE $0x01 -#define VPINSRQ_1_SI_X12(n) BYTE $0xC4; BYTE $0x63; BYTE $0x99; BYTE $0x22; BYTE $0x66; BYTE $n; BYTE $0x01 -#define VPINSRQ_1_SI_X13(n) BYTE $0xC4; BYTE $0x63; BYTE $0x91; BYTE $0x22; BYTE $0x6E; BYTE $n; BYTE $0x01 -#define VPINSRQ_1_SI_X14(n) BYTE $0xC4; BYTE $0x63; BYTE $0x89; BYTE $0x22; BYTE $0x76; BYTE $n; BYTE $0x01 -#define VPINSRQ_1_SI_X15(n) BYTE $0xC4; BYTE $0x63; BYTE $0x81; BYTE $0x22; BYTE $0x7E; BYTE $n; BYTE $0x01 - -#define VMOVQ_R8_X15 BYTE $0xC4; BYTE $0x41; BYTE $0xF9; BYTE $0x6E; BYTE $0xF8 -#define VPINSRQ_1_R9_X15 BYTE $0xC4; BYTE $0x43; BYTE $0x81; BYTE $0x22; BYTE $0xF9; BYTE $0x01 - -// load msg: Y12 = (i0, i1, i2, i3) -// i0, i1, i2, i3 must not be 0 -#define LOAD_MSG_AVX2_Y12(i0, i1, i2, i3) \ - VMOVQ_SI_X12(i0*8); \ - VMOVQ_SI_X11(i2*8); \ - VPINSRQ_1_SI_X12(i1*8); \ - VPINSRQ_1_SI_X11(i3*8); \ - VINSERTI128 $1, X11, Y12, Y12 - -// load msg: Y13 = (i0, i1, i2, i3) -// i0, i1, i2, i3 must not be 0 -#define LOAD_MSG_AVX2_Y13(i0, i1, i2, i3) \ - VMOVQ_SI_X13(i0*8); \ - VMOVQ_SI_X11(i2*8); \ - VPINSRQ_1_SI_X13(i1*8); \ - VPINSRQ_1_SI_X11(i3*8); \ - VINSERTI128 $1, X11, Y13, Y13 - -// load msg: Y14 = (i0, i1, i2, i3) -// i0, i1, i2, i3 must not be 0 -#define LOAD_MSG_AVX2_Y14(i0, i1, i2, i3) \ - VMOVQ_SI_X14(i0*8); \ - VMOVQ_SI_X11(i2*8); \ - VPINSRQ_1_SI_X14(i1*8); \ - VPINSRQ_1_SI_X11(i3*8); \ - VINSERTI128 $1, X11, Y14, Y14 - -// load msg: Y15 = (i0, i1, i2, i3) -// i0, i1, i2, i3 must not be 0 -#define LOAD_MSG_AVX2_Y15(i0, i1, i2, i3) \ - VMOVQ_SI_X15(i0*8); \ - VMOVQ_SI_X11(i2*8); \ - VPINSRQ_1_SI_X15(i1*8); \ - VPINSRQ_1_SI_X11(i3*8); \ - VINSERTI128 $1, X11, Y15, Y15 - -#define LOAD_MSG_AVX2_0_2_4_6_1_3_5_7_8_10_12_14_9_11_13_15() \ - VMOVQ_SI_X12_0; \ - VMOVQ_SI_X11(4*8); \ - VPINSRQ_1_SI_X12(2*8); \ - VPINSRQ_1_SI_X11(6*8); \ - VINSERTI128 $1, X11, Y12, Y12; \ - LOAD_MSG_AVX2_Y13(1, 3, 5, 7); \ - LOAD_MSG_AVX2_Y14(8, 10, 12, 14); \ - LOAD_MSG_AVX2_Y15(9, 11, 13, 15) - -#define LOAD_MSG_AVX2_14_4_9_13_10_8_15_6_1_0_11_5_12_2_7_3() \ - LOAD_MSG_AVX2_Y12(14, 4, 9, 13); \ - LOAD_MSG_AVX2_Y13(10, 8, 15, 6); \ - VMOVQ_SI_X11(11*8); \ - VPSHUFD $0x4E, 0*8(SI), X14; \ - VPINSRQ_1_SI_X11(5*8); \ - VINSERTI128 $1, X11, Y14, Y14; \ - LOAD_MSG_AVX2_Y15(12, 2, 7, 3) - -#define LOAD_MSG_AVX2_11_12_5_15_8_0_2_13_10_3_7_9_14_6_1_4() \ - VMOVQ_SI_X11(5*8); \ - VMOVDQU 11*8(SI), X12; \ - VPINSRQ_1_SI_X11(15*8); \ - VINSERTI128 $1, X11, Y12, Y12; \ - VMOVQ_SI_X13(8*8); \ - VMOVQ_SI_X11(2*8); \ - VPINSRQ_1_SI_X13_0; \ - VPINSRQ_1_SI_X11(13*8); \ - VINSERTI128 $1, X11, Y13, Y13; \ - LOAD_MSG_AVX2_Y14(10, 3, 7, 9); \ - LOAD_MSG_AVX2_Y15(14, 6, 1, 4) - -#define LOAD_MSG_AVX2_7_3_13_11_9_1_12_14_2_5_4_15_6_10_0_8() \ - LOAD_MSG_AVX2_Y12(7, 3, 13, 11); \ - LOAD_MSG_AVX2_Y13(9, 1, 12, 14); \ - LOAD_MSG_AVX2_Y14(2, 5, 4, 15); \ - VMOVQ_SI_X15(6*8); \ - VMOVQ_SI_X11_0; \ - VPINSRQ_1_SI_X15(10*8); \ - VPINSRQ_1_SI_X11(8*8); \ - VINSERTI128 $1, X11, Y15, Y15 - -#define LOAD_MSG_AVX2_9_5_2_10_0_7_4_15_14_11_6_3_1_12_8_13() \ - LOAD_MSG_AVX2_Y12(9, 5, 2, 10); \ - VMOVQ_SI_X13_0; \ - VMOVQ_SI_X11(4*8); \ - VPINSRQ_1_SI_X13(7*8); \ - VPINSRQ_1_SI_X11(15*8); \ - VINSERTI128 $1, X11, Y13, Y13; \ - LOAD_MSG_AVX2_Y14(14, 11, 6, 3); \ - LOAD_MSG_AVX2_Y15(1, 12, 8, 13) - -#define LOAD_MSG_AVX2_2_6_0_8_12_10_11_3_4_7_15_1_13_5_14_9() \ - VMOVQ_SI_X12(2*8); \ - VMOVQ_SI_X11_0; \ - VPINSRQ_1_SI_X12(6*8); \ - VPINSRQ_1_SI_X11(8*8); \ - VINSERTI128 $1, X11, Y12, Y12; \ - LOAD_MSG_AVX2_Y13(12, 10, 11, 3); \ - LOAD_MSG_AVX2_Y14(4, 7, 15, 1); \ - LOAD_MSG_AVX2_Y15(13, 5, 14, 9) - -#define LOAD_MSG_AVX2_12_1_14_4_5_15_13_10_0_6_9_8_7_3_2_11() \ - LOAD_MSG_AVX2_Y12(12, 1, 14, 4); \ - LOAD_MSG_AVX2_Y13(5, 15, 13, 10); \ - VMOVQ_SI_X14_0; \ - VPSHUFD $0x4E, 8*8(SI), X11; \ - VPINSRQ_1_SI_X14(6*8); \ - VINSERTI128 $1, X11, Y14, Y14; \ - LOAD_MSG_AVX2_Y15(7, 3, 2, 11) - -#define LOAD_MSG_AVX2_13_7_12_3_11_14_1_9_5_15_8_2_0_4_6_10() \ - LOAD_MSG_AVX2_Y12(13, 7, 12, 3); \ - LOAD_MSG_AVX2_Y13(11, 14, 1, 9); \ - LOAD_MSG_AVX2_Y14(5, 15, 8, 2); \ - VMOVQ_SI_X15_0; \ - VMOVQ_SI_X11(6*8); \ - VPINSRQ_1_SI_X15(4*8); \ - VPINSRQ_1_SI_X11(10*8); \ - VINSERTI128 $1, X11, Y15, Y15 - -#define LOAD_MSG_AVX2_6_14_11_0_15_9_3_8_12_13_1_10_2_7_4_5() \ - VMOVQ_SI_X12(6*8); \ - VMOVQ_SI_X11(11*8); \ - VPINSRQ_1_SI_X12(14*8); \ - VPINSRQ_1_SI_X11_0; \ - VINSERTI128 $1, X11, Y12, Y12; \ - LOAD_MSG_AVX2_Y13(15, 9, 3, 8); \ - VMOVQ_SI_X11(1*8); \ - VMOVDQU 12*8(SI), X14; \ - VPINSRQ_1_SI_X11(10*8); \ - VINSERTI128 $1, X11, Y14, Y14; \ - VMOVQ_SI_X15(2*8); \ - VMOVDQU 4*8(SI), X11; \ - VPINSRQ_1_SI_X15(7*8); \ - VINSERTI128 $1, X11, Y15, Y15 - -#define LOAD_MSG_AVX2_10_8_7_1_2_4_6_5_15_9_3_13_11_14_12_0() \ - LOAD_MSG_AVX2_Y12(10, 8, 7, 1); \ - VMOVQ_SI_X13(2*8); \ - VPSHUFD $0x4E, 5*8(SI), X11; \ - VPINSRQ_1_SI_X13(4*8); \ - VINSERTI128 $1, X11, Y13, Y13; \ - LOAD_MSG_AVX2_Y14(15, 9, 3, 13); \ - VMOVQ_SI_X15(11*8); \ - VMOVQ_SI_X11(12*8); \ - VPINSRQ_1_SI_X15(14*8); \ - VPINSRQ_1_SI_X11_0; \ - VINSERTI128 $1, X11, Y15, Y15 - -// func hashBlocksAVX2(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) -TEXT ·hashBlocksAVX2(SB), 4, $320-48 // frame size = 288 + 32 byte alignment - MOVQ h+0(FP), AX - MOVQ c+8(FP), BX - MOVQ flag+16(FP), CX - MOVQ blocks_base+24(FP), SI - MOVQ blocks_len+32(FP), DI - - MOVQ SP, DX - ADDQ $31, DX - ANDQ $~31, DX - - MOVQ CX, 16(DX) - XORQ CX, CX - MOVQ CX, 24(DX) - - VMOVDQU ·AVX2_c40<>(SB), Y4 - VMOVDQU ·AVX2_c48<>(SB), Y5 - - VMOVDQU 0(AX), Y8 - VMOVDQU 32(AX), Y9 - VMOVDQU ·AVX2_iv0<>(SB), Y6 - VMOVDQU ·AVX2_iv1<>(SB), Y7 - - MOVQ 0(BX), R8 - MOVQ 8(BX), R9 - MOVQ R9, 8(DX) - -loop: - ADDQ $128, R8 - MOVQ R8, 0(DX) - CMPQ R8, $128 - JGE noinc - INCQ R9 - MOVQ R9, 8(DX) - -noinc: - VMOVDQA Y8, Y0 - VMOVDQA Y9, Y1 - VMOVDQA Y6, Y2 - VPXOR 0(DX), Y7, Y3 - - LOAD_MSG_AVX2_0_2_4_6_1_3_5_7_8_10_12_14_9_11_13_15() - VMOVDQA Y12, 32(DX) - VMOVDQA Y13, 64(DX) - VMOVDQA Y14, 96(DX) - VMOVDQA Y15, 128(DX) - ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) - LOAD_MSG_AVX2_14_4_9_13_10_8_15_6_1_0_11_5_12_2_7_3() - VMOVDQA Y12, 160(DX) - VMOVDQA Y13, 192(DX) - VMOVDQA Y14, 224(DX) - VMOVDQA Y15, 256(DX) - - ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) - LOAD_MSG_AVX2_11_12_5_15_8_0_2_13_10_3_7_9_14_6_1_4() - ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) - LOAD_MSG_AVX2_7_3_13_11_9_1_12_14_2_5_4_15_6_10_0_8() - ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) - LOAD_MSG_AVX2_9_5_2_10_0_7_4_15_14_11_6_3_1_12_8_13() - ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) - LOAD_MSG_AVX2_2_6_0_8_12_10_11_3_4_7_15_1_13_5_14_9() - ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) - LOAD_MSG_AVX2_12_1_14_4_5_15_13_10_0_6_9_8_7_3_2_11() - ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) - LOAD_MSG_AVX2_13_7_12_3_11_14_1_9_5_15_8_2_0_4_6_10() - ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) - LOAD_MSG_AVX2_6_14_11_0_15_9_3_8_12_13_1_10_2_7_4_5() - ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) - LOAD_MSG_AVX2_10_8_7_1_2_4_6_5_15_9_3_13_11_14_12_0() - ROUND_AVX2(Y12, Y13, Y14, Y15, Y10, Y4, Y5) - - ROUND_AVX2(32(DX), 64(DX), 96(DX), 128(DX), Y10, Y4, Y5) - ROUND_AVX2(160(DX), 192(DX), 224(DX), 256(DX), Y10, Y4, Y5) - - VPXOR Y0, Y8, Y8 - VPXOR Y1, Y9, Y9 - VPXOR Y2, Y8, Y8 - VPXOR Y3, Y9, Y9 - - LEAQ 128(SI), SI - SUBQ $128, DI - JNE loop - - MOVQ R8, 0(BX) - MOVQ R9, 8(BX) - - VMOVDQU Y8, 0(AX) - VMOVDQU Y9, 32(AX) - VZEROUPPER - - RET - -#define VPUNPCKLQDQ_X2_X2_X15 BYTE $0xC5; BYTE $0x69; BYTE $0x6C; BYTE $0xFA -#define VPUNPCKLQDQ_X3_X3_X15 BYTE $0xC5; BYTE $0x61; BYTE $0x6C; BYTE $0xFB -#define VPUNPCKLQDQ_X7_X7_X15 BYTE $0xC5; BYTE $0x41; BYTE $0x6C; BYTE $0xFF -#define VPUNPCKLQDQ_X13_X13_X15 BYTE $0xC4; BYTE $0x41; BYTE $0x11; BYTE $0x6C; BYTE $0xFD -#define VPUNPCKLQDQ_X14_X14_X15 BYTE $0xC4; BYTE $0x41; BYTE $0x09; BYTE $0x6C; BYTE $0xFE - -#define VPUNPCKHQDQ_X15_X2_X2 BYTE $0xC4; BYTE $0xC1; BYTE $0x69; BYTE $0x6D; BYTE $0xD7 -#define VPUNPCKHQDQ_X15_X3_X3 BYTE $0xC4; BYTE $0xC1; BYTE $0x61; BYTE $0x6D; BYTE $0xDF -#define VPUNPCKHQDQ_X15_X6_X6 BYTE $0xC4; BYTE $0xC1; BYTE $0x49; BYTE $0x6D; BYTE $0xF7 -#define VPUNPCKHQDQ_X15_X7_X7 BYTE $0xC4; BYTE $0xC1; BYTE $0x41; BYTE $0x6D; BYTE $0xFF -#define VPUNPCKHQDQ_X15_X3_X2 BYTE $0xC4; BYTE $0xC1; BYTE $0x61; BYTE $0x6D; BYTE $0xD7 -#define VPUNPCKHQDQ_X15_X7_X6 BYTE $0xC4; BYTE $0xC1; BYTE $0x41; BYTE $0x6D; BYTE $0xF7 -#define VPUNPCKHQDQ_X15_X13_X3 BYTE $0xC4; BYTE $0xC1; BYTE $0x11; BYTE $0x6D; BYTE $0xDF -#define VPUNPCKHQDQ_X15_X13_X7 BYTE $0xC4; BYTE $0xC1; BYTE $0x11; BYTE $0x6D; BYTE $0xFF - -#define SHUFFLE_AVX() \ - VMOVDQA X6, X13; \ - VMOVDQA X2, X14; \ - VMOVDQA X4, X6; \ - VPUNPCKLQDQ_X13_X13_X15; \ - VMOVDQA X5, X4; \ - VMOVDQA X6, X5; \ - VPUNPCKHQDQ_X15_X7_X6; \ - VPUNPCKLQDQ_X7_X7_X15; \ - VPUNPCKHQDQ_X15_X13_X7; \ - VPUNPCKLQDQ_X3_X3_X15; \ - VPUNPCKHQDQ_X15_X2_X2; \ - VPUNPCKLQDQ_X14_X14_X15; \ - VPUNPCKHQDQ_X15_X3_X3; \ - -#define SHUFFLE_AVX_INV() \ - VMOVDQA X2, X13; \ - VMOVDQA X4, X14; \ - VPUNPCKLQDQ_X2_X2_X15; \ - VMOVDQA X5, X4; \ - VPUNPCKHQDQ_X15_X3_X2; \ - VMOVDQA X14, X5; \ - VPUNPCKLQDQ_X3_X3_X15; \ - VMOVDQA X6, X14; \ - VPUNPCKHQDQ_X15_X13_X3; \ - VPUNPCKLQDQ_X7_X7_X15; \ - VPUNPCKHQDQ_X15_X6_X6; \ - VPUNPCKLQDQ_X14_X14_X15; \ - VPUNPCKHQDQ_X15_X7_X7; \ - -#define HALF_ROUND_AVX(v0, v1, v2, v3, v4, v5, v6, v7, m0, m1, m2, m3, t0, c40, c48) \ - VPADDQ m0, v0, v0; \ - VPADDQ v2, v0, v0; \ - VPADDQ m1, v1, v1; \ - VPADDQ v3, v1, v1; \ - VPXOR v0, v6, v6; \ - VPXOR v1, v7, v7; \ - VPSHUFD $-79, v6, v6; \ - VPSHUFD $-79, v7, v7; \ - VPADDQ v6, v4, v4; \ - VPADDQ v7, v5, v5; \ - VPXOR v4, v2, v2; \ - VPXOR v5, v3, v3; \ - VPSHUFB c40, v2, v2; \ - VPSHUFB c40, v3, v3; \ - VPADDQ m2, v0, v0; \ - VPADDQ v2, v0, v0; \ - VPADDQ m3, v1, v1; \ - VPADDQ v3, v1, v1; \ - VPXOR v0, v6, v6; \ - VPXOR v1, v7, v7; \ - VPSHUFB c48, v6, v6; \ - VPSHUFB c48, v7, v7; \ - VPADDQ v6, v4, v4; \ - VPADDQ v7, v5, v5; \ - VPXOR v4, v2, v2; \ - VPXOR v5, v3, v3; \ - VPADDQ v2, v2, t0; \ - VPSRLQ $63, v2, v2; \ - VPXOR t0, v2, v2; \ - VPADDQ v3, v3, t0; \ - VPSRLQ $63, v3, v3; \ - VPXOR t0, v3, v3 - -// load msg: X12 = (i0, i1), X13 = (i2, i3), X14 = (i4, i5), X15 = (i6, i7) -// i0, i1, i2, i3, i4, i5, i6, i7 must not be 0 -#define LOAD_MSG_AVX(i0, i1, i2, i3, i4, i5, i6, i7) \ - VMOVQ_SI_X12(i0*8); \ - VMOVQ_SI_X13(i2*8); \ - VMOVQ_SI_X14(i4*8); \ - VMOVQ_SI_X15(i6*8); \ - VPINSRQ_1_SI_X12(i1*8); \ - VPINSRQ_1_SI_X13(i3*8); \ - VPINSRQ_1_SI_X14(i5*8); \ - VPINSRQ_1_SI_X15(i7*8) - -// load msg: X12 = (0, 2), X13 = (4, 6), X14 = (1, 3), X15 = (5, 7) -#define LOAD_MSG_AVX_0_2_4_6_1_3_5_7() \ - VMOVQ_SI_X12_0; \ - VMOVQ_SI_X13(4*8); \ - VMOVQ_SI_X14(1*8); \ - VMOVQ_SI_X15(5*8); \ - VPINSRQ_1_SI_X12(2*8); \ - VPINSRQ_1_SI_X13(6*8); \ - VPINSRQ_1_SI_X14(3*8); \ - VPINSRQ_1_SI_X15(7*8) - -// load msg: X12 = (1, 0), X13 = (11, 5), X14 = (12, 2), X15 = (7, 3) -#define LOAD_MSG_AVX_1_0_11_5_12_2_7_3() \ - VPSHUFD $0x4E, 0*8(SI), X12; \ - VMOVQ_SI_X13(11*8); \ - VMOVQ_SI_X14(12*8); \ - VMOVQ_SI_X15(7*8); \ - VPINSRQ_1_SI_X13(5*8); \ - VPINSRQ_1_SI_X14(2*8); \ - VPINSRQ_1_SI_X15(3*8) - -// load msg: X12 = (11, 12), X13 = (5, 15), X14 = (8, 0), X15 = (2, 13) -#define LOAD_MSG_AVX_11_12_5_15_8_0_2_13() \ - VMOVDQU 11*8(SI), X12; \ - VMOVQ_SI_X13(5*8); \ - VMOVQ_SI_X14(8*8); \ - VMOVQ_SI_X15(2*8); \ - VPINSRQ_1_SI_X13(15*8); \ - VPINSRQ_1_SI_X14_0; \ - VPINSRQ_1_SI_X15(13*8) - -// load msg: X12 = (2, 5), X13 = (4, 15), X14 = (6, 10), X15 = (0, 8) -#define LOAD_MSG_AVX_2_5_4_15_6_10_0_8() \ - VMOVQ_SI_X12(2*8); \ - VMOVQ_SI_X13(4*8); \ - VMOVQ_SI_X14(6*8); \ - VMOVQ_SI_X15_0; \ - VPINSRQ_1_SI_X12(5*8); \ - VPINSRQ_1_SI_X13(15*8); \ - VPINSRQ_1_SI_X14(10*8); \ - VPINSRQ_1_SI_X15(8*8) - -// load msg: X12 = (9, 5), X13 = (2, 10), X14 = (0, 7), X15 = (4, 15) -#define LOAD_MSG_AVX_9_5_2_10_0_7_4_15() \ - VMOVQ_SI_X12(9*8); \ - VMOVQ_SI_X13(2*8); \ - VMOVQ_SI_X14_0; \ - VMOVQ_SI_X15(4*8); \ - VPINSRQ_1_SI_X12(5*8); \ - VPINSRQ_1_SI_X13(10*8); \ - VPINSRQ_1_SI_X14(7*8); \ - VPINSRQ_1_SI_X15(15*8) - -// load msg: X12 = (2, 6), X13 = (0, 8), X14 = (12, 10), X15 = (11, 3) -#define LOAD_MSG_AVX_2_6_0_8_12_10_11_3() \ - VMOVQ_SI_X12(2*8); \ - VMOVQ_SI_X13_0; \ - VMOVQ_SI_X14(12*8); \ - VMOVQ_SI_X15(11*8); \ - VPINSRQ_1_SI_X12(6*8); \ - VPINSRQ_1_SI_X13(8*8); \ - VPINSRQ_1_SI_X14(10*8); \ - VPINSRQ_1_SI_X15(3*8) - -// load msg: X12 = (0, 6), X13 = (9, 8), X14 = (7, 3), X15 = (2, 11) -#define LOAD_MSG_AVX_0_6_9_8_7_3_2_11() \ - MOVQ 0*8(SI), X12; \ - VPSHUFD $0x4E, 8*8(SI), X13; \ - MOVQ 7*8(SI), X14; \ - MOVQ 2*8(SI), X15; \ - VPINSRQ_1_SI_X12(6*8); \ - VPINSRQ_1_SI_X14(3*8); \ - VPINSRQ_1_SI_X15(11*8) - -// load msg: X12 = (6, 14), X13 = (11, 0), X14 = (15, 9), X15 = (3, 8) -#define LOAD_MSG_AVX_6_14_11_0_15_9_3_8() \ - MOVQ 6*8(SI), X12; \ - MOVQ 11*8(SI), X13; \ - MOVQ 15*8(SI), X14; \ - MOVQ 3*8(SI), X15; \ - VPINSRQ_1_SI_X12(14*8); \ - VPINSRQ_1_SI_X13_0; \ - VPINSRQ_1_SI_X14(9*8); \ - VPINSRQ_1_SI_X15(8*8) - -// load msg: X12 = (5, 15), X13 = (8, 2), X14 = (0, 4), X15 = (6, 10) -#define LOAD_MSG_AVX_5_15_8_2_0_4_6_10() \ - MOVQ 5*8(SI), X12; \ - MOVQ 8*8(SI), X13; \ - MOVQ 0*8(SI), X14; \ - MOVQ 6*8(SI), X15; \ - VPINSRQ_1_SI_X12(15*8); \ - VPINSRQ_1_SI_X13(2*8); \ - VPINSRQ_1_SI_X14(4*8); \ - VPINSRQ_1_SI_X15(10*8) - -// load msg: X12 = (12, 13), X13 = (1, 10), X14 = (2, 7), X15 = (4, 5) -#define LOAD_MSG_AVX_12_13_1_10_2_7_4_5() \ - VMOVDQU 12*8(SI), X12; \ - MOVQ 1*8(SI), X13; \ - MOVQ 2*8(SI), X14; \ - VPINSRQ_1_SI_X13(10*8); \ - VPINSRQ_1_SI_X14(7*8); \ - VMOVDQU 4*8(SI), X15 - -// load msg: X12 = (15, 9), X13 = (3, 13), X14 = (11, 14), X15 = (12, 0) -#define LOAD_MSG_AVX_15_9_3_13_11_14_12_0() \ - MOVQ 15*8(SI), X12; \ - MOVQ 3*8(SI), X13; \ - MOVQ 11*8(SI), X14; \ - MOVQ 12*8(SI), X15; \ - VPINSRQ_1_SI_X12(9*8); \ - VPINSRQ_1_SI_X13(13*8); \ - VPINSRQ_1_SI_X14(14*8); \ - VPINSRQ_1_SI_X15_0 - -// func hashBlocksAVX(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) -TEXT ·hashBlocksAVX(SB), 4, $288-48 // frame size = 272 + 16 byte alignment - MOVQ h+0(FP), AX - MOVQ c+8(FP), BX - MOVQ flag+16(FP), CX - MOVQ blocks_base+24(FP), SI - MOVQ blocks_len+32(FP), DI - - MOVQ SP, R10 - ADDQ $15, R10 - ANDQ $~15, R10 - - VMOVDQU ·AVX_c40<>(SB), X0 - VMOVDQU ·AVX_c48<>(SB), X1 - VMOVDQA X0, X8 - VMOVDQA X1, X9 - - VMOVDQU ·AVX_iv3<>(SB), X0 - VMOVDQA X0, 0(R10) - XORQ CX, 0(R10) // 0(R10) = ·AVX_iv3 ^ (CX || 0) - - VMOVDQU 0(AX), X10 - VMOVDQU 16(AX), X11 - VMOVDQU 32(AX), X2 - VMOVDQU 48(AX), X3 - - MOVQ 0(BX), R8 - MOVQ 8(BX), R9 - -loop: - ADDQ $128, R8 - CMPQ R8, $128 - JGE noinc - INCQ R9 - -noinc: - VMOVQ_R8_X15 - VPINSRQ_1_R9_X15 - - VMOVDQA X10, X0 - VMOVDQA X11, X1 - VMOVDQU ·AVX_iv0<>(SB), X4 - VMOVDQU ·AVX_iv1<>(SB), X5 - VMOVDQU ·AVX_iv2<>(SB), X6 - - VPXOR X15, X6, X6 - VMOVDQA 0(R10), X7 - - LOAD_MSG_AVX_0_2_4_6_1_3_5_7() - VMOVDQA X12, 16(R10) - VMOVDQA X13, 32(R10) - VMOVDQA X14, 48(R10) - VMOVDQA X15, 64(R10) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX() - LOAD_MSG_AVX(8, 10, 12, 14, 9, 11, 13, 15) - VMOVDQA X12, 80(R10) - VMOVDQA X13, 96(R10) - VMOVDQA X14, 112(R10) - VMOVDQA X15, 128(R10) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX_INV() - - LOAD_MSG_AVX(14, 4, 9, 13, 10, 8, 15, 6) - VMOVDQA X12, 144(R10) - VMOVDQA X13, 160(R10) - VMOVDQA X14, 176(R10) - VMOVDQA X15, 192(R10) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX() - LOAD_MSG_AVX_1_0_11_5_12_2_7_3() - VMOVDQA X12, 208(R10) - VMOVDQA X13, 224(R10) - VMOVDQA X14, 240(R10) - VMOVDQA X15, 256(R10) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX_INV() - - LOAD_MSG_AVX_11_12_5_15_8_0_2_13() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX() - LOAD_MSG_AVX(10, 3, 7, 9, 14, 6, 1, 4) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX_INV() - - LOAD_MSG_AVX(7, 3, 13, 11, 9, 1, 12, 14) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX() - LOAD_MSG_AVX_2_5_4_15_6_10_0_8() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX_INV() - - LOAD_MSG_AVX_9_5_2_10_0_7_4_15() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX() - LOAD_MSG_AVX(14, 11, 6, 3, 1, 12, 8, 13) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX_INV() - - LOAD_MSG_AVX_2_6_0_8_12_10_11_3() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX() - LOAD_MSG_AVX(4, 7, 15, 1, 13, 5, 14, 9) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX_INV() - - LOAD_MSG_AVX(12, 1, 14, 4, 5, 15, 13, 10) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX() - LOAD_MSG_AVX_0_6_9_8_7_3_2_11() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX_INV() - - LOAD_MSG_AVX(13, 7, 12, 3, 11, 14, 1, 9) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX() - LOAD_MSG_AVX_5_15_8_2_0_4_6_10() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX_INV() - - LOAD_MSG_AVX_6_14_11_0_15_9_3_8() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX() - LOAD_MSG_AVX_12_13_1_10_2_7_4_5() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX_INV() - - LOAD_MSG_AVX(10, 8, 7, 1, 2, 4, 6, 5) - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX() - LOAD_MSG_AVX_15_9_3_13_11_14_12_0() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, X12, X13, X14, X15, X15, X8, X9) - SHUFFLE_AVX_INV() - - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, 16(R10), 32(R10), 48(R10), 64(R10), X15, X8, X9) - SHUFFLE_AVX() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, 80(R10), 96(R10), 112(R10), 128(R10), X15, X8, X9) - SHUFFLE_AVX_INV() - - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, 144(R10), 160(R10), 176(R10), 192(R10), X15, X8, X9) - SHUFFLE_AVX() - HALF_ROUND_AVX(X0, X1, X2, X3, X4, X5, X6, X7, 208(R10), 224(R10), 240(R10), 256(R10), X15, X8, X9) - SHUFFLE_AVX_INV() - - VMOVDQU 32(AX), X14 - VMOVDQU 48(AX), X15 - VPXOR X0, X10, X10 - VPXOR X1, X11, X11 - VPXOR X2, X14, X14 - VPXOR X3, X15, X15 - VPXOR X4, X10, X10 - VPXOR X5, X11, X11 - VPXOR X6, X14, X2 - VPXOR X7, X15, X3 - VMOVDQU X2, 32(AX) - VMOVDQU X3, 48(AX) - - LEAQ 128(SI), SI - SUBQ $128, DI - JNE loop - - VMOVDQU X10, 0(AX) - VMOVDQU X11, 16(AX) - - MOVQ R8, 0(BX) - MOVQ R9, 8(BX) - VZEROUPPER - - RET diff --git a/vendor/golang.org/x/crypto/blake2b/blake2b_amd64.s b/vendor/golang.org/x/crypto/blake2b/blake2b_amd64.s deleted file mode 100644 index adfac00c1..000000000 --- a/vendor/golang.org/x/crypto/blake2b/blake2b_amd64.s +++ /dev/null @@ -1,278 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build amd64 && gc && !purego - -#include "textflag.h" - -DATA ·iv0<>+0x00(SB)/8, $0x6a09e667f3bcc908 -DATA ·iv0<>+0x08(SB)/8, $0xbb67ae8584caa73b -GLOBL ·iv0<>(SB), (NOPTR+RODATA), $16 - -DATA ·iv1<>+0x00(SB)/8, $0x3c6ef372fe94f82b -DATA ·iv1<>+0x08(SB)/8, $0xa54ff53a5f1d36f1 -GLOBL ·iv1<>(SB), (NOPTR+RODATA), $16 - -DATA ·iv2<>+0x00(SB)/8, $0x510e527fade682d1 -DATA ·iv2<>+0x08(SB)/8, $0x9b05688c2b3e6c1f -GLOBL ·iv2<>(SB), (NOPTR+RODATA), $16 - -DATA ·iv3<>+0x00(SB)/8, $0x1f83d9abfb41bd6b -DATA ·iv3<>+0x08(SB)/8, $0x5be0cd19137e2179 -GLOBL ·iv3<>(SB), (NOPTR+RODATA), $16 - -DATA ·c40<>+0x00(SB)/8, $0x0201000706050403 -DATA ·c40<>+0x08(SB)/8, $0x0a09080f0e0d0c0b -GLOBL ·c40<>(SB), (NOPTR+RODATA), $16 - -DATA ·c48<>+0x00(SB)/8, $0x0100070605040302 -DATA ·c48<>+0x08(SB)/8, $0x09080f0e0d0c0b0a -GLOBL ·c48<>(SB), (NOPTR+RODATA), $16 - -#define SHUFFLE(v2, v3, v4, v5, v6, v7, t1, t2) \ - MOVO v4, t1; \ - MOVO v5, v4; \ - MOVO t1, v5; \ - MOVO v6, t1; \ - PUNPCKLQDQ v6, t2; \ - PUNPCKHQDQ v7, v6; \ - PUNPCKHQDQ t2, v6; \ - PUNPCKLQDQ v7, t2; \ - MOVO t1, v7; \ - MOVO v2, t1; \ - PUNPCKHQDQ t2, v7; \ - PUNPCKLQDQ v3, t2; \ - PUNPCKHQDQ t2, v2; \ - PUNPCKLQDQ t1, t2; \ - PUNPCKHQDQ t2, v3 - -#define SHUFFLE_INV(v2, v3, v4, v5, v6, v7, t1, t2) \ - MOVO v4, t1; \ - MOVO v5, v4; \ - MOVO t1, v5; \ - MOVO v2, t1; \ - PUNPCKLQDQ v2, t2; \ - PUNPCKHQDQ v3, v2; \ - PUNPCKHQDQ t2, v2; \ - PUNPCKLQDQ v3, t2; \ - MOVO t1, v3; \ - MOVO v6, t1; \ - PUNPCKHQDQ t2, v3; \ - PUNPCKLQDQ v7, t2; \ - PUNPCKHQDQ t2, v6; \ - PUNPCKLQDQ t1, t2; \ - PUNPCKHQDQ t2, v7 - -#define HALF_ROUND(v0, v1, v2, v3, v4, v5, v6, v7, m0, m1, m2, m3, t0, c40, c48) \ - PADDQ m0, v0; \ - PADDQ m1, v1; \ - PADDQ v2, v0; \ - PADDQ v3, v1; \ - PXOR v0, v6; \ - PXOR v1, v7; \ - PSHUFD $0xB1, v6, v6; \ - PSHUFD $0xB1, v7, v7; \ - PADDQ v6, v4; \ - PADDQ v7, v5; \ - PXOR v4, v2; \ - PXOR v5, v3; \ - PSHUFB c40, v2; \ - PSHUFB c40, v3; \ - PADDQ m2, v0; \ - PADDQ m3, v1; \ - PADDQ v2, v0; \ - PADDQ v3, v1; \ - PXOR v0, v6; \ - PXOR v1, v7; \ - PSHUFB c48, v6; \ - PSHUFB c48, v7; \ - PADDQ v6, v4; \ - PADDQ v7, v5; \ - PXOR v4, v2; \ - PXOR v5, v3; \ - MOVOU v2, t0; \ - PADDQ v2, t0; \ - PSRLQ $63, v2; \ - PXOR t0, v2; \ - MOVOU v3, t0; \ - PADDQ v3, t0; \ - PSRLQ $63, v3; \ - PXOR t0, v3 - -#define LOAD_MSG(m0, m1, m2, m3, src, i0, i1, i2, i3, i4, i5, i6, i7) \ - MOVQ i0*8(src), m0; \ - PINSRQ $1, i1*8(src), m0; \ - MOVQ i2*8(src), m1; \ - PINSRQ $1, i3*8(src), m1; \ - MOVQ i4*8(src), m2; \ - PINSRQ $1, i5*8(src), m2; \ - MOVQ i6*8(src), m3; \ - PINSRQ $1, i7*8(src), m3 - -// func hashBlocksSSE4(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) -TEXT ·hashBlocksSSE4(SB), 4, $288-48 // frame size = 272 + 16 byte alignment - MOVQ h+0(FP), AX - MOVQ c+8(FP), BX - MOVQ flag+16(FP), CX - MOVQ blocks_base+24(FP), SI - MOVQ blocks_len+32(FP), DI - - MOVQ SP, R10 - ADDQ $15, R10 - ANDQ $~15, R10 - - MOVOU ·iv3<>(SB), X0 - MOVO X0, 0(R10) - XORQ CX, 0(R10) // 0(R10) = ·iv3 ^ (CX || 0) - - MOVOU ·c40<>(SB), X13 - MOVOU ·c48<>(SB), X14 - - MOVOU 0(AX), X12 - MOVOU 16(AX), X15 - - MOVQ 0(BX), R8 - MOVQ 8(BX), R9 - -loop: - ADDQ $128, R8 - CMPQ R8, $128 - JGE noinc - INCQ R9 - -noinc: - MOVQ R8, X8 - PINSRQ $1, R9, X8 - - MOVO X12, X0 - MOVO X15, X1 - MOVOU 32(AX), X2 - MOVOU 48(AX), X3 - MOVOU ·iv0<>(SB), X4 - MOVOU ·iv1<>(SB), X5 - MOVOU ·iv2<>(SB), X6 - - PXOR X8, X6 - MOVO 0(R10), X7 - - LOAD_MSG(X8, X9, X10, X11, SI, 0, 2, 4, 6, 1, 3, 5, 7) - MOVO X8, 16(R10) - MOVO X9, 32(R10) - MOVO X10, 48(R10) - MOVO X11, 64(R10) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - LOAD_MSG(X8, X9, X10, X11, SI, 8, 10, 12, 14, 9, 11, 13, 15) - MOVO X8, 80(R10) - MOVO X9, 96(R10) - MOVO X10, 112(R10) - MOVO X11, 128(R10) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - LOAD_MSG(X8, X9, X10, X11, SI, 14, 4, 9, 13, 10, 8, 15, 6) - MOVO X8, 144(R10) - MOVO X9, 160(R10) - MOVO X10, 176(R10) - MOVO X11, 192(R10) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - LOAD_MSG(X8, X9, X10, X11, SI, 1, 0, 11, 5, 12, 2, 7, 3) - MOVO X8, 208(R10) - MOVO X9, 224(R10) - MOVO X10, 240(R10) - MOVO X11, 256(R10) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - LOAD_MSG(X8, X9, X10, X11, SI, 11, 12, 5, 15, 8, 0, 2, 13) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - LOAD_MSG(X8, X9, X10, X11, SI, 10, 3, 7, 9, 14, 6, 1, 4) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - LOAD_MSG(X8, X9, X10, X11, SI, 7, 3, 13, 11, 9, 1, 12, 14) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - LOAD_MSG(X8, X9, X10, X11, SI, 2, 5, 4, 15, 6, 10, 0, 8) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - LOAD_MSG(X8, X9, X10, X11, SI, 9, 5, 2, 10, 0, 7, 4, 15) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - LOAD_MSG(X8, X9, X10, X11, SI, 14, 11, 6, 3, 1, 12, 8, 13) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - LOAD_MSG(X8, X9, X10, X11, SI, 2, 6, 0, 8, 12, 10, 11, 3) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - LOAD_MSG(X8, X9, X10, X11, SI, 4, 7, 15, 1, 13, 5, 14, 9) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - LOAD_MSG(X8, X9, X10, X11, SI, 12, 1, 14, 4, 5, 15, 13, 10) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - LOAD_MSG(X8, X9, X10, X11, SI, 0, 6, 9, 8, 7, 3, 2, 11) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - LOAD_MSG(X8, X9, X10, X11, SI, 13, 7, 12, 3, 11, 14, 1, 9) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - LOAD_MSG(X8, X9, X10, X11, SI, 5, 15, 8, 2, 0, 4, 6, 10) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - LOAD_MSG(X8, X9, X10, X11, SI, 6, 14, 11, 0, 15, 9, 3, 8) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - LOAD_MSG(X8, X9, X10, X11, SI, 12, 13, 1, 10, 2, 7, 4, 5) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - LOAD_MSG(X8, X9, X10, X11, SI, 10, 8, 7, 1, 2, 4, 6, 5) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - LOAD_MSG(X8, X9, X10, X11, SI, 15, 9, 3, 13, 11, 14, 12, 0) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, 16(R10), 32(R10), 48(R10), 64(R10), X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, 80(R10), 96(R10), 112(R10), 128(R10), X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, 144(R10), 160(R10), 176(R10), 192(R10), X11, X13, X14) - SHUFFLE(X2, X3, X4, X5, X6, X7, X8, X9) - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, 208(R10), 224(R10), 240(R10), 256(R10), X11, X13, X14) - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, X8, X9) - - MOVOU 32(AX), X10 - MOVOU 48(AX), X11 - PXOR X0, X12 - PXOR X1, X15 - PXOR X2, X10 - PXOR X3, X11 - PXOR X4, X12 - PXOR X5, X15 - PXOR X6, X10 - PXOR X7, X11 - MOVOU X10, 32(AX) - MOVOU X11, 48(AX) - - LEAQ 128(SI), SI - SUBQ $128, DI - JNE loop - - MOVOU X12, 0(AX) - MOVOU X15, 16(AX) - - MOVQ R8, 0(BX) - MOVQ R9, 8(BX) - - RET diff --git a/vendor/golang.org/x/crypto/blake2b/blake2b_generic.go b/vendor/golang.org/x/crypto/blake2b/blake2b_generic.go deleted file mode 100644 index 3168a8aa3..000000000 --- a/vendor/golang.org/x/crypto/blake2b/blake2b_generic.go +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package blake2b - -import ( - "encoding/binary" - "math/bits" -) - -// the precomputed values for BLAKE2b -// there are 12 16-byte arrays - one for each round -// the entries are calculated from the sigma constants. -var precomputed = [12][16]byte{ - {0, 2, 4, 6, 1, 3, 5, 7, 8, 10, 12, 14, 9, 11, 13, 15}, - {14, 4, 9, 13, 10, 8, 15, 6, 1, 0, 11, 5, 12, 2, 7, 3}, - {11, 12, 5, 15, 8, 0, 2, 13, 10, 3, 7, 9, 14, 6, 1, 4}, - {7, 3, 13, 11, 9, 1, 12, 14, 2, 5, 4, 15, 6, 10, 0, 8}, - {9, 5, 2, 10, 0, 7, 4, 15, 14, 11, 6, 3, 1, 12, 8, 13}, - {2, 6, 0, 8, 12, 10, 11, 3, 4, 7, 15, 1, 13, 5, 14, 9}, - {12, 1, 14, 4, 5, 15, 13, 10, 0, 6, 9, 8, 7, 3, 2, 11}, - {13, 7, 12, 3, 11, 14, 1, 9, 5, 15, 8, 2, 0, 4, 6, 10}, - {6, 14, 11, 0, 15, 9, 3, 8, 12, 13, 1, 10, 2, 7, 4, 5}, - {10, 8, 7, 1, 2, 4, 6, 5, 15, 9, 3, 13, 11, 14, 12, 0}, - {0, 2, 4, 6, 1, 3, 5, 7, 8, 10, 12, 14, 9, 11, 13, 15}, // equal to the first - {14, 4, 9, 13, 10, 8, 15, 6, 1, 0, 11, 5, 12, 2, 7, 3}, // equal to the second -} - -func hashBlocksGeneric(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) { - var m [16]uint64 - c0, c1 := c[0], c[1] - - for i := 0; i < len(blocks); { - c0 += BlockSize - if c0 < BlockSize { - c1++ - } - - v0, v1, v2, v3, v4, v5, v6, v7 := h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7] - v8, v9, v10, v11, v12, v13, v14, v15 := iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7] - v12 ^= c0 - v13 ^= c1 - v14 ^= flag - - for j := range m { - m[j] = binary.LittleEndian.Uint64(blocks[i:]) - i += 8 - } - - for j := range precomputed { - s := &(precomputed[j]) - - v0 += m[s[0]] - v0 += v4 - v12 ^= v0 - v12 = bits.RotateLeft64(v12, -32) - v8 += v12 - v4 ^= v8 - v4 = bits.RotateLeft64(v4, -24) - v1 += m[s[1]] - v1 += v5 - v13 ^= v1 - v13 = bits.RotateLeft64(v13, -32) - v9 += v13 - v5 ^= v9 - v5 = bits.RotateLeft64(v5, -24) - v2 += m[s[2]] - v2 += v6 - v14 ^= v2 - v14 = bits.RotateLeft64(v14, -32) - v10 += v14 - v6 ^= v10 - v6 = bits.RotateLeft64(v6, -24) - v3 += m[s[3]] - v3 += v7 - v15 ^= v3 - v15 = bits.RotateLeft64(v15, -32) - v11 += v15 - v7 ^= v11 - v7 = bits.RotateLeft64(v7, -24) - - v0 += m[s[4]] - v0 += v4 - v12 ^= v0 - v12 = bits.RotateLeft64(v12, -16) - v8 += v12 - v4 ^= v8 - v4 = bits.RotateLeft64(v4, -63) - v1 += m[s[5]] - v1 += v5 - v13 ^= v1 - v13 = bits.RotateLeft64(v13, -16) - v9 += v13 - v5 ^= v9 - v5 = bits.RotateLeft64(v5, -63) - v2 += m[s[6]] - v2 += v6 - v14 ^= v2 - v14 = bits.RotateLeft64(v14, -16) - v10 += v14 - v6 ^= v10 - v6 = bits.RotateLeft64(v6, -63) - v3 += m[s[7]] - v3 += v7 - v15 ^= v3 - v15 = bits.RotateLeft64(v15, -16) - v11 += v15 - v7 ^= v11 - v7 = bits.RotateLeft64(v7, -63) - - v0 += m[s[8]] - v0 += v5 - v15 ^= v0 - v15 = bits.RotateLeft64(v15, -32) - v10 += v15 - v5 ^= v10 - v5 = bits.RotateLeft64(v5, -24) - v1 += m[s[9]] - v1 += v6 - v12 ^= v1 - v12 = bits.RotateLeft64(v12, -32) - v11 += v12 - v6 ^= v11 - v6 = bits.RotateLeft64(v6, -24) - v2 += m[s[10]] - v2 += v7 - v13 ^= v2 - v13 = bits.RotateLeft64(v13, -32) - v8 += v13 - v7 ^= v8 - v7 = bits.RotateLeft64(v7, -24) - v3 += m[s[11]] - v3 += v4 - v14 ^= v3 - v14 = bits.RotateLeft64(v14, -32) - v9 += v14 - v4 ^= v9 - v4 = bits.RotateLeft64(v4, -24) - - v0 += m[s[12]] - v0 += v5 - v15 ^= v0 - v15 = bits.RotateLeft64(v15, -16) - v10 += v15 - v5 ^= v10 - v5 = bits.RotateLeft64(v5, -63) - v1 += m[s[13]] - v1 += v6 - v12 ^= v1 - v12 = bits.RotateLeft64(v12, -16) - v11 += v12 - v6 ^= v11 - v6 = bits.RotateLeft64(v6, -63) - v2 += m[s[14]] - v2 += v7 - v13 ^= v2 - v13 = bits.RotateLeft64(v13, -16) - v8 += v13 - v7 ^= v8 - v7 = bits.RotateLeft64(v7, -63) - v3 += m[s[15]] - v3 += v4 - v14 ^= v3 - v14 = bits.RotateLeft64(v14, -16) - v9 += v14 - v4 ^= v9 - v4 = bits.RotateLeft64(v4, -63) - - } - - h[0] ^= v0 ^ v8 - h[1] ^= v1 ^ v9 - h[2] ^= v2 ^ v10 - h[3] ^= v3 ^ v11 - h[4] ^= v4 ^ v12 - h[5] ^= v5 ^ v13 - h[6] ^= v6 ^ v14 - h[7] ^= v7 ^ v15 - } - c[0], c[1] = c0, c1 -} diff --git a/vendor/golang.org/x/crypto/blake2b/blake2b_ref.go b/vendor/golang.org/x/crypto/blake2b/blake2b_ref.go deleted file mode 100644 index 6e28668cd..000000000 --- a/vendor/golang.org/x/crypto/blake2b/blake2b_ref.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !amd64 || purego || !gc - -package blake2b - -func hashBlocks(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) { - hashBlocksGeneric(h, c, flag, blocks) -} diff --git a/vendor/golang.org/x/crypto/blake2b/blake2x.go b/vendor/golang.org/x/crypto/blake2b/blake2x.go deleted file mode 100644 index 52c414db0..000000000 --- a/vendor/golang.org/x/crypto/blake2b/blake2x.go +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package blake2b - -import ( - "encoding/binary" - "errors" - "io" -) - -// XOF defines the interface to hash functions that -// support arbitrary-length output. -type XOF interface { - // Write absorbs more data into the hash's state. It panics if called - // after Read. - io.Writer - - // Read reads more output from the hash. It returns io.EOF if the limit - // has been reached. - io.Reader - - // Clone returns a copy of the XOF in its current state. - Clone() XOF - - // Reset resets the XOF to its initial state. - Reset() -} - -// OutputLengthUnknown can be used as the size argument to NewXOF to indicate -// the length of the output is not known in advance. -const OutputLengthUnknown = 0 - -// magicUnknownOutputLength is a magic value for the output size that indicates -// an unknown number of output bytes. -const magicUnknownOutputLength = (1 << 32) - 1 - -// maxOutputLength is the absolute maximum number of bytes to produce when the -// number of output bytes is unknown. -const maxOutputLength = (1 << 32) * 64 - -// NewXOF creates a new variable-output-length hash. The hash either produce a -// known number of bytes (1 <= size < 2**32-1), or an unknown number of bytes -// (size == OutputLengthUnknown). In the latter case, an absolute limit of -// 256GiB applies. -// -// A non-nil key turns the hash into a MAC. The key must between -// zero and 32 bytes long. -func NewXOF(size uint32, key []byte) (XOF, error) { - if len(key) > Size { - return nil, errKeySize - } - if size == magicUnknownOutputLength { - // 2^32-1 indicates an unknown number of bytes and thus isn't a - // valid length. - return nil, errors.New("blake2b: XOF length too large") - } - if size == OutputLengthUnknown { - size = magicUnknownOutputLength - } - x := &xof{ - d: digest{ - size: Size, - keyLen: len(key), - }, - length: size, - } - copy(x.d.key[:], key) - x.Reset() - return x, nil -} - -type xof struct { - d digest - length uint32 - remaining uint64 - cfg, root, block [Size]byte - offset int - nodeOffset uint32 - readMode bool -} - -func (x *xof) Write(p []byte) (n int, err error) { - if x.readMode { - panic("blake2b: write to XOF after read") - } - return x.d.Write(p) -} - -func (x *xof) Clone() XOF { - clone := *x - return &clone -} - -func (x *xof) Reset() { - x.cfg[0] = byte(Size) - binary.LittleEndian.PutUint32(x.cfg[4:], uint32(Size)) // leaf length - binary.LittleEndian.PutUint32(x.cfg[12:], x.length) // XOF length - x.cfg[17] = byte(Size) // inner hash size - - x.d.Reset() - x.d.h[1] ^= uint64(x.length) << 32 - - x.remaining = uint64(x.length) - if x.remaining == magicUnknownOutputLength { - x.remaining = maxOutputLength - } - x.offset, x.nodeOffset = 0, 0 - x.readMode = false -} - -func (x *xof) Read(p []byte) (n int, err error) { - if !x.readMode { - x.d.finalize(&x.root) - x.readMode = true - } - - if x.remaining == 0 { - return 0, io.EOF - } - - n = len(p) - if uint64(n) > x.remaining { - n = int(x.remaining) - p = p[:n] - } - - if x.offset > 0 { - blockRemaining := Size - x.offset - if n < blockRemaining { - x.offset += copy(p, x.block[x.offset:]) - x.remaining -= uint64(n) - return - } - copy(p, x.block[x.offset:]) - p = p[blockRemaining:] - x.offset = 0 - x.remaining -= uint64(blockRemaining) - } - - for len(p) >= Size { - binary.LittleEndian.PutUint32(x.cfg[8:], x.nodeOffset) - x.nodeOffset++ - - x.d.initConfig(&x.cfg) - x.d.Write(x.root[:]) - x.d.finalize(&x.block) - - copy(p, x.block[:]) - p = p[Size:] - x.remaining -= uint64(Size) - } - - if todo := len(p); todo > 0 { - if x.remaining < uint64(Size) { - x.cfg[0] = byte(x.remaining) - } - binary.LittleEndian.PutUint32(x.cfg[8:], x.nodeOffset) - x.nodeOffset++ - - x.d.initConfig(&x.cfg) - x.d.Write(x.root[:]) - x.d.finalize(&x.block) - - x.offset = copy(p, x.block[:todo]) - x.remaining -= uint64(todo) - } - return -} - -func (d *digest) initConfig(cfg *[Size]byte) { - d.offset, d.c[0], d.c[1] = 0, 0, 0 - for i := range d.h { - d.h[i] = iv[i] ^ binary.LittleEndian.Uint64(cfg[i*8:]) - } -} diff --git a/vendor/golang.org/x/crypto/blake2b/register.go b/vendor/golang.org/x/crypto/blake2b/register.go deleted file mode 100644 index 54e446e1d..000000000 --- a/vendor/golang.org/x/crypto/blake2b/register.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package blake2b - -import ( - "crypto" - "hash" -) - -func init() { - newHash256 := func() hash.Hash { - h, _ := New256(nil) - return h - } - newHash384 := func() hash.Hash { - h, _ := New384(nil) - return h - } - - newHash512 := func() hash.Hash { - h, _ := New512(nil) - return h - } - - crypto.RegisterHash(crypto.BLAKE2b_256, newHash256) - crypto.RegisterHash(crypto.BLAKE2b_384, newHash384) - crypto.RegisterHash(crypto.BLAKE2b_512, newHash512) -} diff --git a/vendor/golang.org/x/crypto/curve25519/curve25519.go b/vendor/golang.org/x/crypto/curve25519/curve25519.go deleted file mode 100644 index 00f963ea2..000000000 --- a/vendor/golang.org/x/crypto/curve25519/curve25519.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package curve25519 provides an implementation of the X25519 function, which -// performs scalar multiplication on the elliptic curve known as Curve25519. -// See RFC 7748. -// -// Starting in Go 1.20, this package is a wrapper for the X25519 implementation -// in the crypto/ecdh package. -package curve25519 // import "golang.org/x/crypto/curve25519" - -// ScalarMult sets dst to the product scalar * point. -// -// Deprecated: when provided a low-order point, ScalarMult will set dst to all -// zeroes, irrespective of the scalar. Instead, use the X25519 function, which -// will return an error. -func ScalarMult(dst, scalar, point *[32]byte) { - scalarMult(dst, scalar, point) -} - -// ScalarBaseMult sets dst to the product scalar * base where base is the -// standard generator. -// -// It is recommended to use the X25519 function with Basepoint instead, as -// copying into fixed size arrays can lead to unexpected bugs. -func ScalarBaseMult(dst, scalar *[32]byte) { - scalarBaseMult(dst, scalar) -} - -const ( - // ScalarSize is the size of the scalar input to X25519. - ScalarSize = 32 - // PointSize is the size of the point input to X25519. - PointSize = 32 -) - -// Basepoint is the canonical Curve25519 generator. -var Basepoint []byte - -var basePoint = [32]byte{9} - -func init() { Basepoint = basePoint[:] } - -// X25519 returns the result of the scalar multiplication (scalar * point), -// according to RFC 7748, Section 5. scalar, point and the return value are -// slices of 32 bytes. -// -// scalar can be generated at random, for example with crypto/rand. point should -// be either Basepoint or the output of another X25519 call. -// -// If point is Basepoint (but not if it's a different slice with the same -// contents) a precomputed implementation might be used for performance. -func X25519(scalar, point []byte) ([]byte, error) { - // Outline the body of function, to let the allocation be inlined in the - // caller, and possibly avoid escaping to the heap. - var dst [32]byte - return x25519(&dst, scalar, point) -} diff --git a/vendor/golang.org/x/crypto/curve25519/curve25519_compat.go b/vendor/golang.org/x/crypto/curve25519/curve25519_compat.go deleted file mode 100644 index ba647e8d7..000000000 --- a/vendor/golang.org/x/crypto/curve25519/curve25519_compat.go +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !go1.20 - -package curve25519 - -import ( - "crypto/subtle" - "errors" - "strconv" - - "golang.org/x/crypto/curve25519/internal/field" -) - -func scalarMult(dst, scalar, point *[32]byte) { - var e [32]byte - - copy(e[:], scalar[:]) - e[0] &= 248 - e[31] &= 127 - e[31] |= 64 - - var x1, x2, z2, x3, z3, tmp0, tmp1 field.Element - x1.SetBytes(point[:]) - x2.One() - x3.Set(&x1) - z3.One() - - swap := 0 - for pos := 254; pos >= 0; pos-- { - b := e[pos/8] >> uint(pos&7) - b &= 1 - swap ^= int(b) - x2.Swap(&x3, swap) - z2.Swap(&z3, swap) - swap = int(b) - - tmp0.Subtract(&x3, &z3) - tmp1.Subtract(&x2, &z2) - x2.Add(&x2, &z2) - z2.Add(&x3, &z3) - z3.Multiply(&tmp0, &x2) - z2.Multiply(&z2, &tmp1) - tmp0.Square(&tmp1) - tmp1.Square(&x2) - x3.Add(&z3, &z2) - z2.Subtract(&z3, &z2) - x2.Multiply(&tmp1, &tmp0) - tmp1.Subtract(&tmp1, &tmp0) - z2.Square(&z2) - - z3.Mult32(&tmp1, 121666) - x3.Square(&x3) - tmp0.Add(&tmp0, &z3) - z3.Multiply(&x1, &z2) - z2.Multiply(&tmp1, &tmp0) - } - - x2.Swap(&x3, swap) - z2.Swap(&z3, swap) - - z2.Invert(&z2) - x2.Multiply(&x2, &z2) - copy(dst[:], x2.Bytes()) -} - -func scalarBaseMult(dst, scalar *[32]byte) { - checkBasepoint() - scalarMult(dst, scalar, &basePoint) -} - -func x25519(dst *[32]byte, scalar, point []byte) ([]byte, error) { - var in [32]byte - if l := len(scalar); l != 32 { - return nil, errors.New("bad scalar length: " + strconv.Itoa(l) + ", expected 32") - } - if l := len(point); l != 32 { - return nil, errors.New("bad point length: " + strconv.Itoa(l) + ", expected 32") - } - copy(in[:], scalar) - if &point[0] == &Basepoint[0] { - scalarBaseMult(dst, &in) - } else { - var base, zero [32]byte - copy(base[:], point) - scalarMult(dst, &in, &base) - if subtle.ConstantTimeCompare(dst[:], zero[:]) == 1 { - return nil, errors.New("bad input point: low order point") - } - } - return dst[:], nil -} - -func checkBasepoint() { - if subtle.ConstantTimeCompare(Basepoint, []byte{ - 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - }) != 1 { - panic("curve25519: global Basepoint value was modified") - } -} diff --git a/vendor/golang.org/x/crypto/curve25519/curve25519_go120.go b/vendor/golang.org/x/crypto/curve25519/curve25519_go120.go deleted file mode 100644 index 627df4972..000000000 --- a/vendor/golang.org/x/crypto/curve25519/curve25519_go120.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2022 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build go1.20 - -package curve25519 - -import "crypto/ecdh" - -func x25519(dst *[32]byte, scalar, point []byte) ([]byte, error) { - curve := ecdh.X25519() - pub, err := curve.NewPublicKey(point) - if err != nil { - return nil, err - } - priv, err := curve.NewPrivateKey(scalar) - if err != nil { - return nil, err - } - out, err := priv.ECDH(pub) - if err != nil { - return nil, err - } - copy(dst[:], out) - return dst[:], nil -} - -func scalarMult(dst, scalar, point *[32]byte) { - if _, err := x25519(dst, scalar[:], point[:]); err != nil { - // The only error condition for x25519 when the inputs are 32 bytes long - // is if the output would have been the all-zero value. - for i := range dst { - dst[i] = 0 - } - } -} - -func scalarBaseMult(dst, scalar *[32]byte) { - curve := ecdh.X25519() - priv, err := curve.NewPrivateKey(scalar[:]) - if err != nil { - panic("curve25519: internal error: scalarBaseMult was not 32 bytes") - } - copy(dst[:], priv.PublicKey().Bytes()) -} diff --git a/vendor/golang.org/x/crypto/curve25519/internal/field/README b/vendor/golang.org/x/crypto/curve25519/internal/field/README deleted file mode 100644 index e25bca7dc..000000000 --- a/vendor/golang.org/x/crypto/curve25519/internal/field/README +++ /dev/null @@ -1,7 +0,0 @@ -This package is kept in sync with crypto/ed25519/internal/edwards25519/field in -the standard library. - -If there are any changes in the standard library that need to be synced to this -package, run sync.sh. It will not overwrite any local changes made since the -previous sync, so it's ok to land changes in this package first, and then sync -to the standard library later. diff --git a/vendor/golang.org/x/crypto/curve25519/internal/field/fe.go b/vendor/golang.org/x/crypto/curve25519/internal/field/fe.go deleted file mode 100644 index ca841ad99..000000000 --- a/vendor/golang.org/x/crypto/curve25519/internal/field/fe.go +++ /dev/null @@ -1,416 +0,0 @@ -// Copyright (c) 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package field implements fast arithmetic modulo 2^255-19. -package field - -import ( - "crypto/subtle" - "encoding/binary" - "math/bits" -) - -// Element represents an element of the field GF(2^255-19). Note that this -// is not a cryptographically secure group, and should only be used to interact -// with edwards25519.Point coordinates. -// -// This type works similarly to math/big.Int, and all arguments and receivers -// are allowed to alias. -// -// The zero value is a valid zero element. -type Element struct { - // An element t represents the integer - // t.l0 + t.l1*2^51 + t.l2*2^102 + t.l3*2^153 + t.l4*2^204 - // - // Between operations, all limbs are expected to be lower than 2^52. - l0 uint64 - l1 uint64 - l2 uint64 - l3 uint64 - l4 uint64 -} - -const maskLow51Bits uint64 = (1 << 51) - 1 - -var feZero = &Element{0, 0, 0, 0, 0} - -// Zero sets v = 0, and returns v. -func (v *Element) Zero() *Element { - *v = *feZero - return v -} - -var feOne = &Element{1, 0, 0, 0, 0} - -// One sets v = 1, and returns v. -func (v *Element) One() *Element { - *v = *feOne - return v -} - -// reduce reduces v modulo 2^255 - 19 and returns it. -func (v *Element) reduce() *Element { - v.carryPropagate() - - // After the light reduction we now have a field element representation - // v < 2^255 + 2^13 * 19, but need v < 2^255 - 19. - - // If v >= 2^255 - 19, then v + 19 >= 2^255, which would overflow 2^255 - 1, - // generating a carry. That is, c will be 0 if v < 2^255 - 19, and 1 otherwise. - c := (v.l0 + 19) >> 51 - c = (v.l1 + c) >> 51 - c = (v.l2 + c) >> 51 - c = (v.l3 + c) >> 51 - c = (v.l4 + c) >> 51 - - // If v < 2^255 - 19 and c = 0, this will be a no-op. Otherwise, it's - // effectively applying the reduction identity to the carry. - v.l0 += 19 * c - - v.l1 += v.l0 >> 51 - v.l0 = v.l0 & maskLow51Bits - v.l2 += v.l1 >> 51 - v.l1 = v.l1 & maskLow51Bits - v.l3 += v.l2 >> 51 - v.l2 = v.l2 & maskLow51Bits - v.l4 += v.l3 >> 51 - v.l3 = v.l3 & maskLow51Bits - // no additional carry - v.l4 = v.l4 & maskLow51Bits - - return v -} - -// Add sets v = a + b, and returns v. -func (v *Element) Add(a, b *Element) *Element { - v.l0 = a.l0 + b.l0 - v.l1 = a.l1 + b.l1 - v.l2 = a.l2 + b.l2 - v.l3 = a.l3 + b.l3 - v.l4 = a.l4 + b.l4 - // Using the generic implementation here is actually faster than the - // assembly. Probably because the body of this function is so simple that - // the compiler can figure out better optimizations by inlining the carry - // propagation. TODO - return v.carryPropagateGeneric() -} - -// Subtract sets v = a - b, and returns v. -func (v *Element) Subtract(a, b *Element) *Element { - // We first add 2 * p, to guarantee the subtraction won't underflow, and - // then subtract b (which can be up to 2^255 + 2^13 * 19). - v.l0 = (a.l0 + 0xFFFFFFFFFFFDA) - b.l0 - v.l1 = (a.l1 + 0xFFFFFFFFFFFFE) - b.l1 - v.l2 = (a.l2 + 0xFFFFFFFFFFFFE) - b.l2 - v.l3 = (a.l3 + 0xFFFFFFFFFFFFE) - b.l3 - v.l4 = (a.l4 + 0xFFFFFFFFFFFFE) - b.l4 - return v.carryPropagate() -} - -// Negate sets v = -a, and returns v. -func (v *Element) Negate(a *Element) *Element { - return v.Subtract(feZero, a) -} - -// Invert sets v = 1/z mod p, and returns v. -// -// If z == 0, Invert returns v = 0. -func (v *Element) Invert(z *Element) *Element { - // Inversion is implemented as exponentiation with exponent p − 2. It uses the - // same sequence of 255 squarings and 11 multiplications as [Curve25519]. - var z2, z9, z11, z2_5_0, z2_10_0, z2_20_0, z2_50_0, z2_100_0, t Element - - z2.Square(z) // 2 - t.Square(&z2) // 4 - t.Square(&t) // 8 - z9.Multiply(&t, z) // 9 - z11.Multiply(&z9, &z2) // 11 - t.Square(&z11) // 22 - z2_5_0.Multiply(&t, &z9) // 31 = 2^5 - 2^0 - - t.Square(&z2_5_0) // 2^6 - 2^1 - for i := 0; i < 4; i++ { - t.Square(&t) // 2^10 - 2^5 - } - z2_10_0.Multiply(&t, &z2_5_0) // 2^10 - 2^0 - - t.Square(&z2_10_0) // 2^11 - 2^1 - for i := 0; i < 9; i++ { - t.Square(&t) // 2^20 - 2^10 - } - z2_20_0.Multiply(&t, &z2_10_0) // 2^20 - 2^0 - - t.Square(&z2_20_0) // 2^21 - 2^1 - for i := 0; i < 19; i++ { - t.Square(&t) // 2^40 - 2^20 - } - t.Multiply(&t, &z2_20_0) // 2^40 - 2^0 - - t.Square(&t) // 2^41 - 2^1 - for i := 0; i < 9; i++ { - t.Square(&t) // 2^50 - 2^10 - } - z2_50_0.Multiply(&t, &z2_10_0) // 2^50 - 2^0 - - t.Square(&z2_50_0) // 2^51 - 2^1 - for i := 0; i < 49; i++ { - t.Square(&t) // 2^100 - 2^50 - } - z2_100_0.Multiply(&t, &z2_50_0) // 2^100 - 2^0 - - t.Square(&z2_100_0) // 2^101 - 2^1 - for i := 0; i < 99; i++ { - t.Square(&t) // 2^200 - 2^100 - } - t.Multiply(&t, &z2_100_0) // 2^200 - 2^0 - - t.Square(&t) // 2^201 - 2^1 - for i := 0; i < 49; i++ { - t.Square(&t) // 2^250 - 2^50 - } - t.Multiply(&t, &z2_50_0) // 2^250 - 2^0 - - t.Square(&t) // 2^251 - 2^1 - t.Square(&t) // 2^252 - 2^2 - t.Square(&t) // 2^253 - 2^3 - t.Square(&t) // 2^254 - 2^4 - t.Square(&t) // 2^255 - 2^5 - - return v.Multiply(&t, &z11) // 2^255 - 21 -} - -// Set sets v = a, and returns v. -func (v *Element) Set(a *Element) *Element { - *v = *a - return v -} - -// SetBytes sets v to x, which must be a 32-byte little-endian encoding. -// -// Consistent with RFC 7748, the most significant bit (the high bit of the -// last byte) is ignored, and non-canonical values (2^255-19 through 2^255-1) -// are accepted. Note that this is laxer than specified by RFC 8032. -func (v *Element) SetBytes(x []byte) *Element { - if len(x) != 32 { - panic("edwards25519: invalid field element input size") - } - - // Bits 0:51 (bytes 0:8, bits 0:64, shift 0, mask 51). - v.l0 = binary.LittleEndian.Uint64(x[0:8]) - v.l0 &= maskLow51Bits - // Bits 51:102 (bytes 6:14, bits 48:112, shift 3, mask 51). - v.l1 = binary.LittleEndian.Uint64(x[6:14]) >> 3 - v.l1 &= maskLow51Bits - // Bits 102:153 (bytes 12:20, bits 96:160, shift 6, mask 51). - v.l2 = binary.LittleEndian.Uint64(x[12:20]) >> 6 - v.l2 &= maskLow51Bits - // Bits 153:204 (bytes 19:27, bits 152:216, shift 1, mask 51). - v.l3 = binary.LittleEndian.Uint64(x[19:27]) >> 1 - v.l3 &= maskLow51Bits - // Bits 204:251 (bytes 24:32, bits 192:256, shift 12, mask 51). - // Note: not bytes 25:33, shift 4, to avoid overread. - v.l4 = binary.LittleEndian.Uint64(x[24:32]) >> 12 - v.l4 &= maskLow51Bits - - return v -} - -// Bytes returns the canonical 32-byte little-endian encoding of v. -func (v *Element) Bytes() []byte { - // This function is outlined to make the allocations inline in the caller - // rather than happen on the heap. - var out [32]byte - return v.bytes(&out) -} - -func (v *Element) bytes(out *[32]byte) []byte { - t := *v - t.reduce() - - var buf [8]byte - for i, l := range [5]uint64{t.l0, t.l1, t.l2, t.l3, t.l4} { - bitsOffset := i * 51 - binary.LittleEndian.PutUint64(buf[:], l<= len(out) { - break - } - out[off] |= bb - } - } - - return out[:] -} - -// Equal returns 1 if v and u are equal, and 0 otherwise. -func (v *Element) Equal(u *Element) int { - sa, sv := u.Bytes(), v.Bytes() - return subtle.ConstantTimeCompare(sa, sv) -} - -// mask64Bits returns 0xffffffff if cond is 1, and 0 otherwise. -func mask64Bits(cond int) uint64 { return ^(uint64(cond) - 1) } - -// Select sets v to a if cond == 1, and to b if cond == 0. -func (v *Element) Select(a, b *Element, cond int) *Element { - m := mask64Bits(cond) - v.l0 = (m & a.l0) | (^m & b.l0) - v.l1 = (m & a.l1) | (^m & b.l1) - v.l2 = (m & a.l2) | (^m & b.l2) - v.l3 = (m & a.l3) | (^m & b.l3) - v.l4 = (m & a.l4) | (^m & b.l4) - return v -} - -// Swap swaps v and u if cond == 1 or leaves them unchanged if cond == 0, and returns v. -func (v *Element) Swap(u *Element, cond int) { - m := mask64Bits(cond) - t := m & (v.l0 ^ u.l0) - v.l0 ^= t - u.l0 ^= t - t = m & (v.l1 ^ u.l1) - v.l1 ^= t - u.l1 ^= t - t = m & (v.l2 ^ u.l2) - v.l2 ^= t - u.l2 ^= t - t = m & (v.l3 ^ u.l3) - v.l3 ^= t - u.l3 ^= t - t = m & (v.l4 ^ u.l4) - v.l4 ^= t - u.l4 ^= t -} - -// IsNegative returns 1 if v is negative, and 0 otherwise. -func (v *Element) IsNegative() int { - return int(v.Bytes()[0] & 1) -} - -// Absolute sets v to |u|, and returns v. -func (v *Element) Absolute(u *Element) *Element { - return v.Select(new(Element).Negate(u), u, u.IsNegative()) -} - -// Multiply sets v = x * y, and returns v. -func (v *Element) Multiply(x, y *Element) *Element { - feMul(v, x, y) - return v -} - -// Square sets v = x * x, and returns v. -func (v *Element) Square(x *Element) *Element { - feSquare(v, x) - return v -} - -// Mult32 sets v = x * y, and returns v. -func (v *Element) Mult32(x *Element, y uint32) *Element { - x0lo, x0hi := mul51(x.l0, y) - x1lo, x1hi := mul51(x.l1, y) - x2lo, x2hi := mul51(x.l2, y) - x3lo, x3hi := mul51(x.l3, y) - x4lo, x4hi := mul51(x.l4, y) - v.l0 = x0lo + 19*x4hi // carried over per the reduction identity - v.l1 = x1lo + x0hi - v.l2 = x2lo + x1hi - v.l3 = x3lo + x2hi - v.l4 = x4lo + x3hi - // The hi portions are going to be only 32 bits, plus any previous excess, - // so we can skip the carry propagation. - return v -} - -// mul51 returns lo + hi * 2⁵¹ = a * b. -func mul51(a uint64, b uint32) (lo uint64, hi uint64) { - mh, ml := bits.Mul64(a, uint64(b)) - lo = ml & maskLow51Bits - hi = (mh << 13) | (ml >> 51) - return -} - -// Pow22523 set v = x^((p-5)/8), and returns v. (p-5)/8 is 2^252-3. -func (v *Element) Pow22523(x *Element) *Element { - var t0, t1, t2 Element - - t0.Square(x) // x^2 - t1.Square(&t0) // x^4 - t1.Square(&t1) // x^8 - t1.Multiply(x, &t1) // x^9 - t0.Multiply(&t0, &t1) // x^11 - t0.Square(&t0) // x^22 - t0.Multiply(&t1, &t0) // x^31 - t1.Square(&t0) // x^62 - for i := 1; i < 5; i++ { // x^992 - t1.Square(&t1) - } - t0.Multiply(&t1, &t0) // x^1023 -> 1023 = 2^10 - 1 - t1.Square(&t0) // 2^11 - 2 - for i := 1; i < 10; i++ { // 2^20 - 2^10 - t1.Square(&t1) - } - t1.Multiply(&t1, &t0) // 2^20 - 1 - t2.Square(&t1) // 2^21 - 2 - for i := 1; i < 20; i++ { // 2^40 - 2^20 - t2.Square(&t2) - } - t1.Multiply(&t2, &t1) // 2^40 - 1 - t1.Square(&t1) // 2^41 - 2 - for i := 1; i < 10; i++ { // 2^50 - 2^10 - t1.Square(&t1) - } - t0.Multiply(&t1, &t0) // 2^50 - 1 - t1.Square(&t0) // 2^51 - 2 - for i := 1; i < 50; i++ { // 2^100 - 2^50 - t1.Square(&t1) - } - t1.Multiply(&t1, &t0) // 2^100 - 1 - t2.Square(&t1) // 2^101 - 2 - for i := 1; i < 100; i++ { // 2^200 - 2^100 - t2.Square(&t2) - } - t1.Multiply(&t2, &t1) // 2^200 - 1 - t1.Square(&t1) // 2^201 - 2 - for i := 1; i < 50; i++ { // 2^250 - 2^50 - t1.Square(&t1) - } - t0.Multiply(&t1, &t0) // 2^250 - 1 - t0.Square(&t0) // 2^251 - 2 - t0.Square(&t0) // 2^252 - 4 - return v.Multiply(&t0, x) // 2^252 - 3 -> x^(2^252-3) -} - -// sqrtM1 is 2^((p-1)/4), which squared is equal to -1 by Euler's Criterion. -var sqrtM1 = &Element{1718705420411056, 234908883556509, - 2233514472574048, 2117202627021982, 765476049583133} - -// SqrtRatio sets r to the non-negative square root of the ratio of u and v. -// -// If u/v is square, SqrtRatio returns r and 1. If u/v is not square, SqrtRatio -// sets r according to Section 4.3 of draft-irtf-cfrg-ristretto255-decaf448-00, -// and returns r and 0. -func (r *Element) SqrtRatio(u, v *Element) (rr *Element, wasSquare int) { - var a, b Element - - // r = (u * v3) * (u * v7)^((p-5)/8) - v2 := a.Square(v) - uv3 := b.Multiply(u, b.Multiply(v2, v)) - uv7 := a.Multiply(uv3, a.Square(v2)) - r.Multiply(uv3, r.Pow22523(uv7)) - - check := a.Multiply(v, a.Square(r)) // check = v * r^2 - - uNeg := b.Negate(u) - correctSignSqrt := check.Equal(u) - flippedSignSqrt := check.Equal(uNeg) - flippedSignSqrtI := check.Equal(uNeg.Multiply(uNeg, sqrtM1)) - - rPrime := b.Multiply(r, sqrtM1) // r_prime = SQRT_M1 * r - // r = CT_SELECT(r_prime IF flipped_sign_sqrt | flipped_sign_sqrt_i ELSE r) - r.Select(rPrime, r, flippedSignSqrt|flippedSignSqrtI) - - r.Absolute(r) // Choose the nonnegative square root. - return r, correctSignSqrt | flippedSignSqrt -} diff --git a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64.go b/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64.go deleted file mode 100644 index 70c541692..000000000 --- a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64.go +++ /dev/null @@ -1,15 +0,0 @@ -// Code generated by command: go run fe_amd64_asm.go -out ../fe_amd64.s -stubs ../fe_amd64.go -pkg field. DO NOT EDIT. - -//go:build amd64 && gc && !purego - -package field - -// feMul sets out = a * b. It works like feMulGeneric. -// -//go:noescape -func feMul(out *Element, a *Element, b *Element) - -// feSquare sets out = a * a. It works like feSquareGeneric. -// -//go:noescape -func feSquare(out *Element, a *Element) diff --git a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64.s b/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64.s deleted file mode 100644 index 60817acc4..000000000 --- a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64.s +++ /dev/null @@ -1,378 +0,0 @@ -// Code generated by command: go run fe_amd64_asm.go -out ../fe_amd64.s -stubs ../fe_amd64.go -pkg field. DO NOT EDIT. - -//go:build amd64 && gc && !purego - -#include "textflag.h" - -// func feMul(out *Element, a *Element, b *Element) -TEXT ·feMul(SB), NOSPLIT, $0-24 - MOVQ a+8(FP), CX - MOVQ b+16(FP), BX - - // r0 = a0×b0 - MOVQ (CX), AX - MULQ (BX) - MOVQ AX, DI - MOVQ DX, SI - - // r0 += 19×a1×b4 - MOVQ 8(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 32(BX) - ADDQ AX, DI - ADCQ DX, SI - - // r0 += 19×a2×b3 - MOVQ 16(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 24(BX) - ADDQ AX, DI - ADCQ DX, SI - - // r0 += 19×a3×b2 - MOVQ 24(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 16(BX) - ADDQ AX, DI - ADCQ DX, SI - - // r0 += 19×a4×b1 - MOVQ 32(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 8(BX) - ADDQ AX, DI - ADCQ DX, SI - - // r1 = a0×b1 - MOVQ (CX), AX - MULQ 8(BX) - MOVQ AX, R9 - MOVQ DX, R8 - - // r1 += a1×b0 - MOVQ 8(CX), AX - MULQ (BX) - ADDQ AX, R9 - ADCQ DX, R8 - - // r1 += 19×a2×b4 - MOVQ 16(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 32(BX) - ADDQ AX, R9 - ADCQ DX, R8 - - // r1 += 19×a3×b3 - MOVQ 24(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 24(BX) - ADDQ AX, R9 - ADCQ DX, R8 - - // r1 += 19×a4×b2 - MOVQ 32(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 16(BX) - ADDQ AX, R9 - ADCQ DX, R8 - - // r2 = a0×b2 - MOVQ (CX), AX - MULQ 16(BX) - MOVQ AX, R11 - MOVQ DX, R10 - - // r2 += a1×b1 - MOVQ 8(CX), AX - MULQ 8(BX) - ADDQ AX, R11 - ADCQ DX, R10 - - // r2 += a2×b0 - MOVQ 16(CX), AX - MULQ (BX) - ADDQ AX, R11 - ADCQ DX, R10 - - // r2 += 19×a3×b4 - MOVQ 24(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 32(BX) - ADDQ AX, R11 - ADCQ DX, R10 - - // r2 += 19×a4×b3 - MOVQ 32(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 24(BX) - ADDQ AX, R11 - ADCQ DX, R10 - - // r3 = a0×b3 - MOVQ (CX), AX - MULQ 24(BX) - MOVQ AX, R13 - MOVQ DX, R12 - - // r3 += a1×b2 - MOVQ 8(CX), AX - MULQ 16(BX) - ADDQ AX, R13 - ADCQ DX, R12 - - // r3 += a2×b1 - MOVQ 16(CX), AX - MULQ 8(BX) - ADDQ AX, R13 - ADCQ DX, R12 - - // r3 += a3×b0 - MOVQ 24(CX), AX - MULQ (BX) - ADDQ AX, R13 - ADCQ DX, R12 - - // r3 += 19×a4×b4 - MOVQ 32(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 32(BX) - ADDQ AX, R13 - ADCQ DX, R12 - - // r4 = a0×b4 - MOVQ (CX), AX - MULQ 32(BX) - MOVQ AX, R15 - MOVQ DX, R14 - - // r4 += a1×b3 - MOVQ 8(CX), AX - MULQ 24(BX) - ADDQ AX, R15 - ADCQ DX, R14 - - // r4 += a2×b2 - MOVQ 16(CX), AX - MULQ 16(BX) - ADDQ AX, R15 - ADCQ DX, R14 - - // r4 += a3×b1 - MOVQ 24(CX), AX - MULQ 8(BX) - ADDQ AX, R15 - ADCQ DX, R14 - - // r4 += a4×b0 - MOVQ 32(CX), AX - MULQ (BX) - ADDQ AX, R15 - ADCQ DX, R14 - - // First reduction chain - MOVQ $0x0007ffffffffffff, AX - SHLQ $0x0d, DI, SI - SHLQ $0x0d, R9, R8 - SHLQ $0x0d, R11, R10 - SHLQ $0x0d, R13, R12 - SHLQ $0x0d, R15, R14 - ANDQ AX, DI - IMUL3Q $0x13, R14, R14 - ADDQ R14, DI - ANDQ AX, R9 - ADDQ SI, R9 - ANDQ AX, R11 - ADDQ R8, R11 - ANDQ AX, R13 - ADDQ R10, R13 - ANDQ AX, R15 - ADDQ R12, R15 - - // Second reduction chain (carryPropagate) - MOVQ DI, SI - SHRQ $0x33, SI - MOVQ R9, R8 - SHRQ $0x33, R8 - MOVQ R11, R10 - SHRQ $0x33, R10 - MOVQ R13, R12 - SHRQ $0x33, R12 - MOVQ R15, R14 - SHRQ $0x33, R14 - ANDQ AX, DI - IMUL3Q $0x13, R14, R14 - ADDQ R14, DI - ANDQ AX, R9 - ADDQ SI, R9 - ANDQ AX, R11 - ADDQ R8, R11 - ANDQ AX, R13 - ADDQ R10, R13 - ANDQ AX, R15 - ADDQ R12, R15 - - // Store output - MOVQ out+0(FP), AX - MOVQ DI, (AX) - MOVQ R9, 8(AX) - MOVQ R11, 16(AX) - MOVQ R13, 24(AX) - MOVQ R15, 32(AX) - RET - -// func feSquare(out *Element, a *Element) -TEXT ·feSquare(SB), NOSPLIT, $0-16 - MOVQ a+8(FP), CX - - // r0 = l0×l0 - MOVQ (CX), AX - MULQ (CX) - MOVQ AX, SI - MOVQ DX, BX - - // r0 += 38×l1×l4 - MOVQ 8(CX), AX - IMUL3Q $0x26, AX, AX - MULQ 32(CX) - ADDQ AX, SI - ADCQ DX, BX - - // r0 += 38×l2×l3 - MOVQ 16(CX), AX - IMUL3Q $0x26, AX, AX - MULQ 24(CX) - ADDQ AX, SI - ADCQ DX, BX - - // r1 = 2×l0×l1 - MOVQ (CX), AX - SHLQ $0x01, AX - MULQ 8(CX) - MOVQ AX, R8 - MOVQ DX, DI - - // r1 += 38×l2×l4 - MOVQ 16(CX), AX - IMUL3Q $0x26, AX, AX - MULQ 32(CX) - ADDQ AX, R8 - ADCQ DX, DI - - // r1 += 19×l3×l3 - MOVQ 24(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 24(CX) - ADDQ AX, R8 - ADCQ DX, DI - - // r2 = 2×l0×l2 - MOVQ (CX), AX - SHLQ $0x01, AX - MULQ 16(CX) - MOVQ AX, R10 - MOVQ DX, R9 - - // r2 += l1×l1 - MOVQ 8(CX), AX - MULQ 8(CX) - ADDQ AX, R10 - ADCQ DX, R9 - - // r2 += 38×l3×l4 - MOVQ 24(CX), AX - IMUL3Q $0x26, AX, AX - MULQ 32(CX) - ADDQ AX, R10 - ADCQ DX, R9 - - // r3 = 2×l0×l3 - MOVQ (CX), AX - SHLQ $0x01, AX - MULQ 24(CX) - MOVQ AX, R12 - MOVQ DX, R11 - - // r3 += 2×l1×l2 - MOVQ 8(CX), AX - IMUL3Q $0x02, AX, AX - MULQ 16(CX) - ADDQ AX, R12 - ADCQ DX, R11 - - // r3 += 19×l4×l4 - MOVQ 32(CX), AX - IMUL3Q $0x13, AX, AX - MULQ 32(CX) - ADDQ AX, R12 - ADCQ DX, R11 - - // r4 = 2×l0×l4 - MOVQ (CX), AX - SHLQ $0x01, AX - MULQ 32(CX) - MOVQ AX, R14 - MOVQ DX, R13 - - // r4 += 2×l1×l3 - MOVQ 8(CX), AX - IMUL3Q $0x02, AX, AX - MULQ 24(CX) - ADDQ AX, R14 - ADCQ DX, R13 - - // r4 += l2×l2 - MOVQ 16(CX), AX - MULQ 16(CX) - ADDQ AX, R14 - ADCQ DX, R13 - - // First reduction chain - MOVQ $0x0007ffffffffffff, AX - SHLQ $0x0d, SI, BX - SHLQ $0x0d, R8, DI - SHLQ $0x0d, R10, R9 - SHLQ $0x0d, R12, R11 - SHLQ $0x0d, R14, R13 - ANDQ AX, SI - IMUL3Q $0x13, R13, R13 - ADDQ R13, SI - ANDQ AX, R8 - ADDQ BX, R8 - ANDQ AX, R10 - ADDQ DI, R10 - ANDQ AX, R12 - ADDQ R9, R12 - ANDQ AX, R14 - ADDQ R11, R14 - - // Second reduction chain (carryPropagate) - MOVQ SI, BX - SHRQ $0x33, BX - MOVQ R8, DI - SHRQ $0x33, DI - MOVQ R10, R9 - SHRQ $0x33, R9 - MOVQ R12, R11 - SHRQ $0x33, R11 - MOVQ R14, R13 - SHRQ $0x33, R13 - ANDQ AX, SI - IMUL3Q $0x13, R13, R13 - ADDQ R13, SI - ANDQ AX, R8 - ADDQ BX, R8 - ANDQ AX, R10 - ADDQ DI, R10 - ANDQ AX, R12 - ADDQ R9, R12 - ANDQ AX, R14 - ADDQ R11, R14 - - // Store output - MOVQ out+0(FP), AX - MOVQ SI, (AX) - MOVQ R8, 8(AX) - MOVQ R10, 16(AX) - MOVQ R12, 24(AX) - MOVQ R14, 32(AX) - RET diff --git a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64_noasm.go b/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64_noasm.go deleted file mode 100644 index 9da280d1d..000000000 --- a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_amd64_noasm.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !amd64 || !gc || purego - -package field - -func feMul(v, x, y *Element) { feMulGeneric(v, x, y) } - -func feSquare(v, x *Element) { feSquareGeneric(v, x) } diff --git a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64.go b/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64.go deleted file mode 100644 index 075fe9b92..000000000 --- a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build arm64 && gc && !purego - -package field - -//go:noescape -func carryPropagate(v *Element) - -func (v *Element) carryPropagate() *Element { - carryPropagate(v) - return v -} diff --git a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64.s b/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64.s deleted file mode 100644 index 3126a4341..000000000 --- a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64.s +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build arm64 && gc && !purego - -#include "textflag.h" - -// carryPropagate works exactly like carryPropagateGeneric and uses the -// same AND, ADD, and LSR+MADD instructions emitted by the compiler, but -// avoids loading R0-R4 twice and uses LDP and STP. -// -// See https://golang.org/issues/43145 for the main compiler issue. -// -// func carryPropagate(v *Element) -TEXT ·carryPropagate(SB),NOFRAME|NOSPLIT,$0-8 - MOVD v+0(FP), R20 - - LDP 0(R20), (R0, R1) - LDP 16(R20), (R2, R3) - MOVD 32(R20), R4 - - AND $0x7ffffffffffff, R0, R10 - AND $0x7ffffffffffff, R1, R11 - AND $0x7ffffffffffff, R2, R12 - AND $0x7ffffffffffff, R3, R13 - AND $0x7ffffffffffff, R4, R14 - - ADD R0>>51, R11, R11 - ADD R1>>51, R12, R12 - ADD R2>>51, R13, R13 - ADD R3>>51, R14, R14 - // R4>>51 * 19 + R10 -> R10 - LSR $51, R4, R21 - MOVD $19, R22 - MADD R22, R10, R21, R10 - - STP (R10, R11), 0(R20) - STP (R12, R13), 16(R20) - MOVD R14, 32(R20) - - RET diff --git a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64_noasm.go b/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64_noasm.go deleted file mode 100644 index fc029ac12..000000000 --- a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_arm64_noasm.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) 2021 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !arm64 || !gc || purego - -package field - -func (v *Element) carryPropagate() *Element { - return v.carryPropagateGeneric() -} diff --git a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_generic.go b/vendor/golang.org/x/crypto/curve25519/internal/field/fe_generic.go deleted file mode 100644 index 2671217da..000000000 --- a/vendor/golang.org/x/crypto/curve25519/internal/field/fe_generic.go +++ /dev/null @@ -1,264 +0,0 @@ -// Copyright (c) 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package field - -import "math/bits" - -// uint128 holds a 128-bit number as two 64-bit limbs, for use with the -// bits.Mul64 and bits.Add64 intrinsics. -type uint128 struct { - lo, hi uint64 -} - -// mul64 returns a * b. -func mul64(a, b uint64) uint128 { - hi, lo := bits.Mul64(a, b) - return uint128{lo, hi} -} - -// addMul64 returns v + a * b. -func addMul64(v uint128, a, b uint64) uint128 { - hi, lo := bits.Mul64(a, b) - lo, c := bits.Add64(lo, v.lo, 0) - hi, _ = bits.Add64(hi, v.hi, c) - return uint128{lo, hi} -} - -// shiftRightBy51 returns a >> 51. a is assumed to be at most 115 bits. -func shiftRightBy51(a uint128) uint64 { - return (a.hi << (64 - 51)) | (a.lo >> 51) -} - -func feMulGeneric(v, a, b *Element) { - a0 := a.l0 - a1 := a.l1 - a2 := a.l2 - a3 := a.l3 - a4 := a.l4 - - b0 := b.l0 - b1 := b.l1 - b2 := b.l2 - b3 := b.l3 - b4 := b.l4 - - // Limb multiplication works like pen-and-paper columnar multiplication, but - // with 51-bit limbs instead of digits. - // - // a4 a3 a2 a1 a0 x - // b4 b3 b2 b1 b0 = - // ------------------------ - // a4b0 a3b0 a2b0 a1b0 a0b0 + - // a4b1 a3b1 a2b1 a1b1 a0b1 + - // a4b2 a3b2 a2b2 a1b2 a0b2 + - // a4b3 a3b3 a2b3 a1b3 a0b3 + - // a4b4 a3b4 a2b4 a1b4 a0b4 = - // ---------------------------------------------- - // r8 r7 r6 r5 r4 r3 r2 r1 r0 - // - // We can then use the reduction identity (a * 2²⁵⁵ + b = a * 19 + b) to - // reduce the limbs that would overflow 255 bits. r5 * 2²⁵⁵ becomes 19 * r5, - // r6 * 2³⁰⁶ becomes 19 * r6 * 2⁵¹, etc. - // - // Reduction can be carried out simultaneously to multiplication. For - // example, we do not compute r5: whenever the result of a multiplication - // belongs to r5, like a1b4, we multiply it by 19 and add the result to r0. - // - // a4b0 a3b0 a2b0 a1b0 a0b0 + - // a3b1 a2b1 a1b1 a0b1 19×a4b1 + - // a2b2 a1b2 a0b2 19×a4b2 19×a3b2 + - // a1b3 a0b3 19×a4b3 19×a3b3 19×a2b3 + - // a0b4 19×a4b4 19×a3b4 19×a2b4 19×a1b4 = - // -------------------------------------- - // r4 r3 r2 r1 r0 - // - // Finally we add up the columns into wide, overlapping limbs. - - a1_19 := a1 * 19 - a2_19 := a2 * 19 - a3_19 := a3 * 19 - a4_19 := a4 * 19 - - // r0 = a0×b0 + 19×(a1×b4 + a2×b3 + a3×b2 + a4×b1) - r0 := mul64(a0, b0) - r0 = addMul64(r0, a1_19, b4) - r0 = addMul64(r0, a2_19, b3) - r0 = addMul64(r0, a3_19, b2) - r0 = addMul64(r0, a4_19, b1) - - // r1 = a0×b1 + a1×b0 + 19×(a2×b4 + a3×b3 + a4×b2) - r1 := mul64(a0, b1) - r1 = addMul64(r1, a1, b0) - r1 = addMul64(r1, a2_19, b4) - r1 = addMul64(r1, a3_19, b3) - r1 = addMul64(r1, a4_19, b2) - - // r2 = a0×b2 + a1×b1 + a2×b0 + 19×(a3×b4 + a4×b3) - r2 := mul64(a0, b2) - r2 = addMul64(r2, a1, b1) - r2 = addMul64(r2, a2, b0) - r2 = addMul64(r2, a3_19, b4) - r2 = addMul64(r2, a4_19, b3) - - // r3 = a0×b3 + a1×b2 + a2×b1 + a3×b0 + 19×a4×b4 - r3 := mul64(a0, b3) - r3 = addMul64(r3, a1, b2) - r3 = addMul64(r3, a2, b1) - r3 = addMul64(r3, a3, b0) - r3 = addMul64(r3, a4_19, b4) - - // r4 = a0×b4 + a1×b3 + a2×b2 + a3×b1 + a4×b0 - r4 := mul64(a0, b4) - r4 = addMul64(r4, a1, b3) - r4 = addMul64(r4, a2, b2) - r4 = addMul64(r4, a3, b1) - r4 = addMul64(r4, a4, b0) - - // After the multiplication, we need to reduce (carry) the five coefficients - // to obtain a result with limbs that are at most slightly larger than 2⁵¹, - // to respect the Element invariant. - // - // Overall, the reduction works the same as carryPropagate, except with - // wider inputs: we take the carry for each coefficient by shifting it right - // by 51, and add it to the limb above it. The top carry is multiplied by 19 - // according to the reduction identity and added to the lowest limb. - // - // The largest coefficient (r0) will be at most 111 bits, which guarantees - // that all carries are at most 111 - 51 = 60 bits, which fits in a uint64. - // - // r0 = a0×b0 + 19×(a1×b4 + a2×b3 + a3×b2 + a4×b1) - // r0 < 2⁵²×2⁵² + 19×(2⁵²×2⁵² + 2⁵²×2⁵² + 2⁵²×2⁵² + 2⁵²×2⁵²) - // r0 < (1 + 19 × 4) × 2⁵² × 2⁵² - // r0 < 2⁷ × 2⁵² × 2⁵² - // r0 < 2¹¹¹ - // - // Moreover, the top coefficient (r4) is at most 107 bits, so c4 is at most - // 56 bits, and c4 * 19 is at most 61 bits, which again fits in a uint64 and - // allows us to easily apply the reduction identity. - // - // r4 = a0×b4 + a1×b3 + a2×b2 + a3×b1 + a4×b0 - // r4 < 5 × 2⁵² × 2⁵² - // r4 < 2¹⁰⁷ - // - - c0 := shiftRightBy51(r0) - c1 := shiftRightBy51(r1) - c2 := shiftRightBy51(r2) - c3 := shiftRightBy51(r3) - c4 := shiftRightBy51(r4) - - rr0 := r0.lo&maskLow51Bits + c4*19 - rr1 := r1.lo&maskLow51Bits + c0 - rr2 := r2.lo&maskLow51Bits + c1 - rr3 := r3.lo&maskLow51Bits + c2 - rr4 := r4.lo&maskLow51Bits + c3 - - // Now all coefficients fit into 64-bit registers but are still too large to - // be passed around as a Element. We therefore do one last carry chain, - // where the carries will be small enough to fit in the wiggle room above 2⁵¹. - *v = Element{rr0, rr1, rr2, rr3, rr4} - v.carryPropagate() -} - -func feSquareGeneric(v, a *Element) { - l0 := a.l0 - l1 := a.l1 - l2 := a.l2 - l3 := a.l3 - l4 := a.l4 - - // Squaring works precisely like multiplication above, but thanks to its - // symmetry we get to group a few terms together. - // - // l4 l3 l2 l1 l0 x - // l4 l3 l2 l1 l0 = - // ------------------------ - // l4l0 l3l0 l2l0 l1l0 l0l0 + - // l4l1 l3l1 l2l1 l1l1 l0l1 + - // l4l2 l3l2 l2l2 l1l2 l0l2 + - // l4l3 l3l3 l2l3 l1l3 l0l3 + - // l4l4 l3l4 l2l4 l1l4 l0l4 = - // ---------------------------------------------- - // r8 r7 r6 r5 r4 r3 r2 r1 r0 - // - // l4l0 l3l0 l2l0 l1l0 l0l0 + - // l3l1 l2l1 l1l1 l0l1 19×l4l1 + - // l2l2 l1l2 l0l2 19×l4l2 19×l3l2 + - // l1l3 l0l3 19×l4l3 19×l3l3 19×l2l3 + - // l0l4 19×l4l4 19×l3l4 19×l2l4 19×l1l4 = - // -------------------------------------- - // r4 r3 r2 r1 r0 - // - // With precomputed 2×, 19×, and 2×19× terms, we can compute each limb with - // only three Mul64 and four Add64, instead of five and eight. - - l0_2 := l0 * 2 - l1_2 := l1 * 2 - - l1_38 := l1 * 38 - l2_38 := l2 * 38 - l3_38 := l3 * 38 - - l3_19 := l3 * 19 - l4_19 := l4 * 19 - - // r0 = l0×l0 + 19×(l1×l4 + l2×l3 + l3×l2 + l4×l1) = l0×l0 + 19×2×(l1×l4 + l2×l3) - r0 := mul64(l0, l0) - r0 = addMul64(r0, l1_38, l4) - r0 = addMul64(r0, l2_38, l3) - - // r1 = l0×l1 + l1×l0 + 19×(l2×l4 + l3×l3 + l4×l2) = 2×l0×l1 + 19×2×l2×l4 + 19×l3×l3 - r1 := mul64(l0_2, l1) - r1 = addMul64(r1, l2_38, l4) - r1 = addMul64(r1, l3_19, l3) - - // r2 = l0×l2 + l1×l1 + l2×l0 + 19×(l3×l4 + l4×l3) = 2×l0×l2 + l1×l1 + 19×2×l3×l4 - r2 := mul64(l0_2, l2) - r2 = addMul64(r2, l1, l1) - r2 = addMul64(r2, l3_38, l4) - - // r3 = l0×l3 + l1×l2 + l2×l1 + l3×l0 + 19×l4×l4 = 2×l0×l3 + 2×l1×l2 + 19×l4×l4 - r3 := mul64(l0_2, l3) - r3 = addMul64(r3, l1_2, l2) - r3 = addMul64(r3, l4_19, l4) - - // r4 = l0×l4 + l1×l3 + l2×l2 + l3×l1 + l4×l0 = 2×l0×l4 + 2×l1×l3 + l2×l2 - r4 := mul64(l0_2, l4) - r4 = addMul64(r4, l1_2, l3) - r4 = addMul64(r4, l2, l2) - - c0 := shiftRightBy51(r0) - c1 := shiftRightBy51(r1) - c2 := shiftRightBy51(r2) - c3 := shiftRightBy51(r3) - c4 := shiftRightBy51(r4) - - rr0 := r0.lo&maskLow51Bits + c4*19 - rr1 := r1.lo&maskLow51Bits + c0 - rr2 := r2.lo&maskLow51Bits + c1 - rr3 := r3.lo&maskLow51Bits + c2 - rr4 := r4.lo&maskLow51Bits + c3 - - *v = Element{rr0, rr1, rr2, rr3, rr4} - v.carryPropagate() -} - -// carryPropagateGeneric brings the limbs below 52 bits by applying the reduction -// identity (a * 2²⁵⁵ + b = a * 19 + b) to the l4 carry. TODO inline -func (v *Element) carryPropagateGeneric() *Element { - c0 := v.l0 >> 51 - c1 := v.l1 >> 51 - c2 := v.l2 >> 51 - c3 := v.l3 >> 51 - c4 := v.l4 >> 51 - - v.l0 = v.l0&maskLow51Bits + c4*19 - v.l1 = v.l1&maskLow51Bits + c0 - v.l2 = v.l2&maskLow51Bits + c1 - v.l3 = v.l3&maskLow51Bits + c2 - v.l4 = v.l4&maskLow51Bits + c3 - - return v -} diff --git a/vendor/golang.org/x/crypto/curve25519/internal/field/sync.checkpoint b/vendor/golang.org/x/crypto/curve25519/internal/field/sync.checkpoint deleted file mode 100644 index e3685f95c..000000000 --- a/vendor/golang.org/x/crypto/curve25519/internal/field/sync.checkpoint +++ /dev/null @@ -1 +0,0 @@ -b0c49ae9f59d233526f8934262c5bbbe14d4358d diff --git a/vendor/golang.org/x/crypto/curve25519/internal/field/sync.sh b/vendor/golang.org/x/crypto/curve25519/internal/field/sync.sh deleted file mode 100644 index 1ba22a8b4..000000000 --- a/vendor/golang.org/x/crypto/curve25519/internal/field/sync.sh +++ /dev/null @@ -1,19 +0,0 @@ -#! /bin/bash -set -euo pipefail - -cd "$(git rev-parse --show-toplevel)" - -STD_PATH=src/crypto/ed25519/internal/edwards25519/field -LOCAL_PATH=curve25519/internal/field -LAST_SYNC_REF=$(cat $LOCAL_PATH/sync.checkpoint) - -git fetch https://go.googlesource.com/go master - -if git diff --quiet $LAST_SYNC_REF:$STD_PATH FETCH_HEAD:$STD_PATH; then - echo "No changes." -else - NEW_REF=$(git rev-parse FETCH_HEAD | tee $LOCAL_PATH/sync.checkpoint) - echo "Applying changes from $LAST_SYNC_REF to $NEW_REF..." - git diff $LAST_SYNC_REF:$STD_PATH FETCH_HEAD:$STD_PATH | \ - git apply -3 --directory=$LOCAL_PATH -fi diff --git a/vendor/golang.org/x/crypto/ed25519/ed25519.go b/vendor/golang.org/x/crypto/ed25519/ed25519.go deleted file mode 100644 index a7828345f..000000000 --- a/vendor/golang.org/x/crypto/ed25519/ed25519.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package ed25519 implements the Ed25519 signature algorithm. See -// https://ed25519.cr.yp.to/. -// -// These functions are also compatible with the “Ed25519” function defined in -// RFC 8032. However, unlike RFC 8032's formulation, this package's private key -// representation includes a public key suffix to make multiple signing -// operations with the same key more efficient. This package refers to the RFC -// 8032 private key as the “seed”. -// -// Beginning with Go 1.13, the functionality of this package was moved to the -// standard library as crypto/ed25519. This package only acts as a compatibility -// wrapper. -package ed25519 - -import ( - "crypto/ed25519" - "io" -) - -const ( - // PublicKeySize is the size, in bytes, of public keys as used in this package. - PublicKeySize = 32 - // PrivateKeySize is the size, in bytes, of private keys as used in this package. - PrivateKeySize = 64 - // SignatureSize is the size, in bytes, of signatures generated and verified by this package. - SignatureSize = 64 - // SeedSize is the size, in bytes, of private key seeds. These are the private key representations used by RFC 8032. - SeedSize = 32 -) - -// PublicKey is the type of Ed25519 public keys. -// -// This type is an alias for crypto/ed25519's PublicKey type. -// See the crypto/ed25519 package for the methods on this type. -type PublicKey = ed25519.PublicKey - -// PrivateKey is the type of Ed25519 private keys. It implements crypto.Signer. -// -// This type is an alias for crypto/ed25519's PrivateKey type. -// See the crypto/ed25519 package for the methods on this type. -type PrivateKey = ed25519.PrivateKey - -// GenerateKey generates a public/private key pair using entropy from rand. -// If rand is nil, crypto/rand.Reader will be used. -func GenerateKey(rand io.Reader) (PublicKey, PrivateKey, error) { - return ed25519.GenerateKey(rand) -} - -// NewKeyFromSeed calculates a private key from a seed. It will panic if -// len(seed) is not SeedSize. This function is provided for interoperability -// with RFC 8032. RFC 8032's private keys correspond to seeds in this -// package. -func NewKeyFromSeed(seed []byte) PrivateKey { - return ed25519.NewKeyFromSeed(seed) -} - -// Sign signs the message with privateKey and returns a signature. It will -// panic if len(privateKey) is not PrivateKeySize. -func Sign(privateKey PrivateKey, message []byte) []byte { - return ed25519.Sign(privateKey, message) -} - -// Verify reports whether sig is a valid signature of message by publicKey. It -// will panic if len(publicKey) is not PublicKeySize. -func Verify(publicKey PublicKey, message, sig []byte) bool { - return ed25519.Verify(publicKey, message, sig) -} diff --git a/vendor/golang.org/x/crypto/nacl/box/box.go b/vendor/golang.org/x/crypto/nacl/box/box.go deleted file mode 100644 index 7f3b830ee..000000000 --- a/vendor/golang.org/x/crypto/nacl/box/box.go +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* -Package box authenticates and encrypts small messages using public-key cryptography. - -Box uses Curve25519, XSalsa20 and Poly1305 to encrypt and authenticate -messages. The length of messages is not hidden. - -It is the caller's responsibility to ensure the uniqueness of nonces—for -example, by using nonce 1 for the first message, nonce 2 for the second -message, etc. Nonces are long enough that randomly generated nonces have -negligible risk of collision. - -Messages should be small because: - -1. The whole message needs to be held in memory to be processed. - -2. Using large messages pressures implementations on small machines to decrypt -and process plaintext before authenticating it. This is very dangerous, and -this API does not allow it, but a protocol that uses excessive message sizes -might present some implementations with no other choice. - -3. Fixed overheads will be sufficiently amortised by messages as small as 8KB. - -4. Performance may be improved by working with messages that fit into data caches. - -Thus large amounts of data should be chunked so that each message is small. -(Each message still needs a unique nonce.) If in doubt, 16KB is a reasonable -chunk size. - -This package is interoperable with NaCl: https://nacl.cr.yp.to/box.html. -Anonymous sealing/opening is an extension of NaCl defined by and interoperable -with libsodium: -https://libsodium.gitbook.io/doc/public-key_cryptography/sealed_boxes. -*/ -package box // import "golang.org/x/crypto/nacl/box" - -import ( - cryptorand "crypto/rand" - "io" - - "golang.org/x/crypto/blake2b" - "golang.org/x/crypto/curve25519" - "golang.org/x/crypto/nacl/secretbox" - "golang.org/x/crypto/salsa20/salsa" -) - -const ( - // Overhead is the number of bytes of overhead when boxing a message. - Overhead = secretbox.Overhead - - // AnonymousOverhead is the number of bytes of overhead when using anonymous - // sealed boxes. - AnonymousOverhead = Overhead + 32 -) - -// GenerateKey generates a new public/private key pair suitable for use with -// Seal and Open. -func GenerateKey(rand io.Reader) (publicKey, privateKey *[32]byte, err error) { - publicKey = new([32]byte) - privateKey = new([32]byte) - _, err = io.ReadFull(rand, privateKey[:]) - if err != nil { - publicKey = nil - privateKey = nil - return - } - - curve25519.ScalarBaseMult(publicKey, privateKey) - return -} - -var zeros [16]byte - -// Precompute calculates the shared key between peersPublicKey and privateKey -// and writes it to sharedKey. The shared key can be used with -// OpenAfterPrecomputation and SealAfterPrecomputation to speed up processing -// when using the same pair of keys repeatedly. -func Precompute(sharedKey, peersPublicKey, privateKey *[32]byte) { - curve25519.ScalarMult(sharedKey, privateKey, peersPublicKey) - salsa.HSalsa20(sharedKey, &zeros, sharedKey, &salsa.Sigma) -} - -// Seal appends an encrypted and authenticated copy of message to out, which -// will be Overhead bytes longer than the original and must not overlap it. The -// nonce must be unique for each distinct message for a given pair of keys. -func Seal(out, message []byte, nonce *[24]byte, peersPublicKey, privateKey *[32]byte) []byte { - var sharedKey [32]byte - Precompute(&sharedKey, peersPublicKey, privateKey) - return secretbox.Seal(out, message, nonce, &sharedKey) -} - -// SealAfterPrecomputation performs the same actions as Seal, but takes a -// shared key as generated by Precompute. -func SealAfterPrecomputation(out, message []byte, nonce *[24]byte, sharedKey *[32]byte) []byte { - return secretbox.Seal(out, message, nonce, sharedKey) -} - -// Open authenticates and decrypts a box produced by Seal and appends the -// message to out, which must not overlap box. The output will be Overhead -// bytes smaller than box. -func Open(out, box []byte, nonce *[24]byte, peersPublicKey, privateKey *[32]byte) ([]byte, bool) { - var sharedKey [32]byte - Precompute(&sharedKey, peersPublicKey, privateKey) - return secretbox.Open(out, box, nonce, &sharedKey) -} - -// OpenAfterPrecomputation performs the same actions as Open, but takes a -// shared key as generated by Precompute. -func OpenAfterPrecomputation(out, box []byte, nonce *[24]byte, sharedKey *[32]byte) ([]byte, bool) { - return secretbox.Open(out, box, nonce, sharedKey) -} - -// SealAnonymous appends an encrypted and authenticated copy of message to out, -// which will be AnonymousOverhead bytes longer than the original and must not -// overlap it. This differs from Seal in that the sender is not required to -// provide a private key. -func SealAnonymous(out, message []byte, recipient *[32]byte, rand io.Reader) ([]byte, error) { - if rand == nil { - rand = cryptorand.Reader - } - ephemeralPub, ephemeralPriv, err := GenerateKey(rand) - if err != nil { - return nil, err - } - - var nonce [24]byte - if err := sealNonce(ephemeralPub, recipient, &nonce); err != nil { - return nil, err - } - - if total := len(out) + AnonymousOverhead + len(message); cap(out) < total { - original := out - out = make([]byte, 0, total) - out = append(out, original...) - } - out = append(out, ephemeralPub[:]...) - - return Seal(out, message, &nonce, recipient, ephemeralPriv), nil -} - -// OpenAnonymous authenticates and decrypts a box produced by SealAnonymous and -// appends the message to out, which must not overlap box. The output will be -// AnonymousOverhead bytes smaller than box. -func OpenAnonymous(out, box []byte, publicKey, privateKey *[32]byte) (message []byte, ok bool) { - if len(box) < AnonymousOverhead { - return nil, false - } - - var ephemeralPub [32]byte - copy(ephemeralPub[:], box[:32]) - - var nonce [24]byte - if err := sealNonce(&ephemeralPub, publicKey, &nonce); err != nil { - return nil, false - } - - return Open(out, box[32:], &nonce, &ephemeralPub, privateKey) -} - -// sealNonce generates a 24 byte nonce that is a blake2b digest of the -// ephemeral public key and the receiver's public key. -func sealNonce(ephemeralPub, peersPublicKey *[32]byte, nonce *[24]byte) error { - h, err := blake2b.New(24, nil) - if err != nil { - return err - } - - if _, err = h.Write(ephemeralPub[:]); err != nil { - return err - } - - if _, err = h.Write(peersPublicKey[:]); err != nil { - return err - } - - h.Sum(nonce[:0]) - - return nil -} diff --git a/vendor/golang.org/x/sys/execabs/execabs.go b/vendor/golang.org/x/sys/execabs/execabs.go deleted file mode 100644 index 3bf40fdfe..000000000 --- a/vendor/golang.org/x/sys/execabs/execabs.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2020 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package execabs is a drop-in replacement for os/exec -// that requires PATH lookups to find absolute paths. -// That is, execabs.Command("cmd") runs the same PATH lookup -// as exec.Command("cmd"), but if the result is a path -// which is relative, the Run and Start methods will report -// an error instead of running the executable. -// -// See https://blog.golang.org/path-security for more information -// about when it may be necessary or appropriate to use this package. -package execabs - -import ( - "context" - "fmt" - "os/exec" - "path/filepath" - "reflect" - "unsafe" -) - -// ErrNotFound is the error resulting if a path search failed to find an executable file. -// It is an alias for exec.ErrNotFound. -var ErrNotFound = exec.ErrNotFound - -// Cmd represents an external command being prepared or run. -// It is an alias for exec.Cmd. -type Cmd = exec.Cmd - -// Error is returned by LookPath when it fails to classify a file as an executable. -// It is an alias for exec.Error. -type Error = exec.Error - -// An ExitError reports an unsuccessful exit by a command. -// It is an alias for exec.ExitError. -type ExitError = exec.ExitError - -func relError(file, path string) error { - return fmt.Errorf("%s resolves to executable in current directory (.%c%s)", file, filepath.Separator, path) -} - -// LookPath searches for an executable named file in the directories -// named by the PATH environment variable. If file contains a slash, -// it is tried directly and the PATH is not consulted. The result will be -// an absolute path. -// -// LookPath differs from exec.LookPath in its handling of PATH lookups, -// which are used for file names without slashes. If exec.LookPath's -// PATH lookup would have returned an executable from the current directory, -// LookPath instead returns an error. -func LookPath(file string) (string, error) { - path, err := exec.LookPath(file) - if err != nil && !isGo119ErrDot(err) { - return "", err - } - if filepath.Base(file) == file && !filepath.IsAbs(path) { - return "", relError(file, path) - } - return path, nil -} - -func fixCmd(name string, cmd *exec.Cmd) { - if filepath.Base(name) == name && !filepath.IsAbs(cmd.Path) && !isGo119ErrFieldSet(cmd) { - // exec.Command was called with a bare binary name and - // exec.LookPath returned a path which is not absolute. - // Set cmd.lookPathErr and clear cmd.Path so that it - // cannot be run. - lookPathErr := (*error)(unsafe.Pointer(reflect.ValueOf(cmd).Elem().FieldByName("lookPathErr").Addr().Pointer())) - if *lookPathErr == nil { - *lookPathErr = relError(name, cmd.Path) - } - cmd.Path = "" - } -} - -// CommandContext is like Command but includes a context. -// -// The provided context is used to kill the process (by calling os.Process.Kill) -// if the context becomes done before the command completes on its own. -func CommandContext(ctx context.Context, name string, arg ...string) *exec.Cmd { - cmd := exec.CommandContext(ctx, name, arg...) - fixCmd(name, cmd) - return cmd - -} - -// Command returns the Cmd struct to execute the named program with the given arguments. -// See exec.Command for most details. -// -// Command differs from exec.Command in its handling of PATH lookups, -// which are used when the program name contains no slashes. -// If exec.Command would have returned an exec.Cmd configured to run an -// executable from the current directory, Command instead -// returns an exec.Cmd that will return an error from Start or Run. -func Command(name string, arg ...string) *exec.Cmd { - cmd := exec.Command(name, arg...) - fixCmd(name, cmd) - return cmd -} diff --git a/vendor/golang.org/x/sys/execabs/execabs_go118.go b/vendor/golang.org/x/sys/execabs/execabs_go118.go deleted file mode 100644 index 5627d70e3..000000000 --- a/vendor/golang.org/x/sys/execabs/execabs_go118.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2022 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !go1.19 - -package execabs - -import "os/exec" - -func isGo119ErrDot(err error) bool { - return false -} - -func isGo119ErrFieldSet(cmd *exec.Cmd) bool { - return false -} diff --git a/vendor/golang.org/x/sys/execabs/execabs_go119.go b/vendor/golang.org/x/sys/execabs/execabs_go119.go deleted file mode 100644 index d60ab1b41..000000000 --- a/vendor/golang.org/x/sys/execabs/execabs_go119.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2022 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build go1.19 - -package execabs - -import ( - "errors" - "os/exec" -) - -func isGo119ErrDot(err error) bool { - return errors.Is(err, exec.ErrDot) -} - -func isGo119ErrFieldSet(cmd *exec.Cmd) bool { - return cmd.Err != nil -} diff --git a/vendor/gomodules.xyz/counter/LICENSE b/vendor/gomodules.xyz/counter/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/vendor/gomodules.xyz/counter/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - 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 "[]" - 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 - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/gomodules.xyz/counter/hourly/int.go b/vendor/gomodules.xyz/counter/hourly/int.go deleted file mode 100644 index f786afeed..000000000 --- a/vendor/gomodules.xyz/counter/hourly/int.go +++ /dev/null @@ -1,20 +0,0 @@ -package hourly - -import "sync" - -type Int struct { - c int - m sync.RWMutex -} - -func (i *Int) Inc() int { - i.m.Lock() - defer i.m.Unlock() - return Inc(&i.c) -} - -func (i *Int) Get() int { - i.m.RLock() - defer i.m.RUnlock() - return Get(&i.c) -} diff --git a/vendor/gomodules.xyz/counter/hourly/int32.go b/vendor/gomodules.xyz/counter/hourly/int32.go deleted file mode 100644 index 225fd1b3d..000000000 --- a/vendor/gomodules.xyz/counter/hourly/int32.go +++ /dev/null @@ -1,20 +0,0 @@ -package hourly - -import "sync" - -type Int32 struct { - c int32 - m sync.RWMutex -} - -func (i *Int32) Inc() int32 { - i.m.Lock() - defer i.m.Unlock() - return Inc32(&i.c) -} - -func (i *Int32) Get() int32 { - i.m.RLock() - defer i.m.RUnlock() - return Get32(&i.c) -} diff --git a/vendor/gomodules.xyz/counter/hourly/int64.go b/vendor/gomodules.xyz/counter/hourly/int64.go deleted file mode 100644 index ee59dfa52..000000000 --- a/vendor/gomodules.xyz/counter/hourly/int64.go +++ /dev/null @@ -1,20 +0,0 @@ -package hourly - -import "sync" - -type Int64 struct { - c int64 - m sync.RWMutex -} - -func (i *Int64) Inc() int64 { - i.m.Lock() - defer i.m.Unlock() - return Inc64(&i.c) -} - -func (i *Int64) Get() int64 { - i.m.RLock() - defer i.m.RUnlock() - return Get64(&i.c) -} diff --git a/vendor/gomodules.xyz/counter/hourly/lib.go b/vendor/gomodules.xyz/counter/hourly/lib.go deleted file mode 100644 index a16d3f4c1..000000000 --- a/vendor/gomodules.xyz/counter/hourly/lib.go +++ /dev/null @@ -1,78 +0,0 @@ -package hourly - -import ( - "github.com/jonboulle/clockwork" -) - -var Clock = clockwork.NewRealClock() - -const ( - SuffixLen = 6 // bits.Len(23) + 1 - Suffix = 0b0111111 -) - -func Inc(addr *int) int { - stored := *addr - storedTime := int(stored & Suffix) - curTime := Clock.Now().Hour() - if storedTime == curTime { - *addr = ((stored>>SuffixLen)+1)<> SuffixLen - } - return 0 -} - -func Inc64(addr *int64) int64 { - stored := *addr - storedTime := int(stored & Suffix) - curTime := Clock.Now().Hour() - if storedTime == curTime { - *addr = ((stored>>SuffixLen)+1)<> SuffixLen - } - return 0 -} - -func Inc32(addr *int32) int32 { - stored := *addr - storedTime := int(stored & Suffix) - curTime := Clock.Now().Hour() - if storedTime == curTime { - *addr = ((stored>>SuffixLen)+1)<> SuffixLen - } - return 0 -} diff --git a/vendor/kmodules.xyz/client-go/tools/clusterid/lib.go b/vendor/kmodules.xyz/client-go/tools/clusterid/lib.go deleted file mode 100644 index 0e29fe4db..000000000 --- a/vendor/kmodules.xyz/client-go/tools/clusterid/lib.go +++ /dev/null @@ -1,77 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 clusterid - -import ( - "context" - "flag" - "fmt" - - kmapi "kmodules.xyz/client-go/api/v1" - - "github.com/spf13/pflag" - core "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - corev1 "k8s.io/client-go/kubernetes/typed/core/v1" -) - -var clusterName = "" - -func AddFlags(fs *pflag.FlagSet) { - fs.StringVar(&clusterName, "cluster-name", clusterName, "Name of cluster used in a multi-cluster setup") -} - -func AddGoFlags(fs *flag.FlagSet) { - fs.StringVar(&clusterName, "cluster-name", clusterName, "Name of cluster used in a multi-cluster setup") -} - -func ClusterName() string { - return clusterName -} - -func ClusterUID(client corev1.NamespaceInterface) (string, error) { - ns, err := client.Get(context.TODO(), metav1.NamespaceSystem, metav1.GetOptions{}) - if err != nil { - return "", err - } - return string(ns.UID), nil -} - -func ClusterMetadataForNamespace(ns *core.Namespace) (*kmapi.ClusterMetadata, error) { - if ns.Name != metav1.NamespaceSystem { - return nil, fmt.Errorf("expected namespace %s, found namespace %s", metav1.NamespaceSystem, ns.Name) - } - name := ns.Annotations[kmapi.ClusterNameKey] - if name == "" { - name = ClusterName() - } - obj := &kmapi.ClusterMetadata{ - UID: string(ns.UID), - Name: name, - DisplayName: ns.Annotations[kmapi.ClusterDisplayNameKey], - Provider: kmapi.HostingProvider(ns.Annotations[kmapi.ClusterProviderNameKey]), - } - return obj, nil -} - -func ClusterMetadata(client corev1.NamespaceInterface) (*kmapi.ClusterMetadata, error) { - ns, err := client.Get(context.TODO(), metav1.NamespaceSystem, metav1.GetOptions{}) - if err != nil { - return nil, err - } - return ClusterMetadataForNamespace(ns) -} diff --git a/vendor/kmodules.xyz/custom-resources/util/siteinfo/lib.go b/vendor/kmodules.xyz/custom-resources/util/siteinfo/lib.go deleted file mode 100644 index d71e66493..000000000 --- a/vendor/kmodules.xyz/custom-resources/util/siteinfo/lib.go +++ /dev/null @@ -1,166 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 siteinfo - -import ( - "context" - "net" - "strings" - - meta_util "kmodules.xyz/client-go/meta" - "kmodules.xyz/client-go/tools/clusterid" - auditorapi "kmodules.xyz/custom-resources/apis/auditor/v1alpha1" - "kmodules.xyz/resource-metrics/api" - - "go.bytebuilders.dev/license-verifier/info" - v "gomodules.xyz/x/version" - core "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/rest" -) - -func GetSiteInfo(cfg *rest.Config, kc kubernetes.Interface, nodes []*core.Node, licenseID string) (*auditorapi.SiteInfo, error) { - si := auditorapi.SiteInfo{ - TypeMeta: metav1.TypeMeta{ - APIVersion: auditorapi.SchemeGroupVersion.String(), - Kind: "SiteInfo", - }, - Kubernetes: &auditorapi.KubernetesInfo{}, - } - - if info.ProductName != "" || v.Version.Version != "" || licenseID != "" { - si.Product = &auditorapi.ProductInfo{} - si.Product.LicenseID = licenseID - si.Product.ProductOwnerName = info.ProductOwnerName - si.Product.ProductOwnerUID = info.ProductOwnerUID - si.Product.ProductName = info.ProductName - si.Product.ProductUID = info.ProductUID - si.Product.Version = auditorapi.Version{ - Version: v.Version.Version, - VersionStrategy: v.Version.VersionStrategy, - CommitHash: v.Version.CommitHash, - GitBranch: v.Version.GitBranch, - GitTag: v.Version.GitTag, - CommitTimestamp: v.Version.CommitTimestamp, - GoVersion: v.Version.GoVersion, - Compiler: v.Version.Compiler, - Platform: v.Version.Platform, - } - } - - cmeta, err := clusterid.ClusterMetadata(kc.CoreV1().Namespaces()) - if err != nil { - return nil, err - } - si.Kubernetes.Cluster = cmeta - si.Kubernetes.Version, err = kc.Discovery().ServerVersion() - if err != nil { - return nil, err - } - - cert, err := meta_util.APIServerCertificate(cfg) - if err != nil { - return nil, err - } else { - si.Kubernetes.ControlPlane = &auditorapi.ControlPlaneInfo{ - NotBefore: metav1.NewTime(cert.NotBefore), - NotAfter: metav1.NewTime(cert.NotAfter), - // DNSNames: cert.DNSNames, - EmailAddresses: cert.EmailAddresses, - // IPAddresses: cert.IPAddresses, - // URIs: cert.URIs, - } - - dnsNames := sets.NewString(cert.DNSNames...) - ips := sets.NewString() - if len(cert.Subject.CommonName) > 0 { - if ip := net.ParseIP(cert.Subject.CommonName); ip != nil { - if !skipIP(ip) { - ips.Insert(ip.String()) - } - } else { - dnsNames.Insert(cert.Subject.CommonName) - } - } - - for _, host := range dnsNames.UnsortedList() { - if host == "kubernetes" || - host == "kubernetes.default" || - host == "kubernetes.default.svc" || - strings.HasSuffix(host, ".svc.cluster.local") || - host == "localhost" || - !strings.ContainsRune(host, '.') { - dnsNames.Delete(host) - } - } - si.Kubernetes.ControlPlane.DNSNames = dnsNames.List() - - for _, ip := range cert.IPAddresses { - if !skipIP(ip) { - ips.Insert(ip.String()) - } - } - si.Kubernetes.ControlPlane.IPAddresses = ips.List() - - uris := make([]string, 0, len(cert.URIs)) - for _, u := range cert.URIs { - uris = append(uris, u.String()) - } - si.Kubernetes.ControlPlane.URIs = uris - } - - if len(nodes) == 0 { - result, err := kc.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{}) - if err != nil { - return nil, err - } - nodes = make([]*core.Node, len(result.Items)) - for i := range result.Items { - nodes[i] = &result.Items[i] - } - } - RefreshNodeStats(&si, nodes) - - return &si, nil -} - -func RefreshNodeStats(si *auditorapi.SiteInfo, nodes []*core.Node) { - if len(nodes) == 0 { - return - } - si.Kubernetes.NodeStats.Count = len(nodes) - - var capacity core.ResourceList - var allocatable core.ResourceList - for _, node := range nodes { - capacity = api.AddResourceList(capacity, node.Status.Capacity) - allocatable = api.AddResourceList(allocatable, node.Status.Allocatable) - } - si.Kubernetes.NodeStats.Capacity = capacity - si.Kubernetes.NodeStats.Allocatable = allocatable -} - -func skipIP(ip net.IP) bool { - return ip.IsLoopback() || - ip.IsMulticast() || - ip.IsGlobalUnicast() || - ip.IsInterfaceLocalMulticast() || - ip.IsLinkLocalMulticast() || - ip.IsLinkLocalUnicast() -} diff --git a/vendor/kmodules.xyz/go-containerregistry/LICENSE b/vendor/kmodules.xyz/go-containerregistry/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/vendor/kmodules.xyz/go-containerregistry/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - 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 "[]" - 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 - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/kmodules.xyz/go-containerregistry/name/lib.go b/vendor/kmodules.xyz/go-containerregistry/name/lib.go deleted file mode 100644 index 334b51736..000000000 --- a/vendor/kmodules.xyz/go-containerregistry/name/lib.go +++ /dev/null @@ -1,104 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 name - -import ( - "fmt" - "strings" - - "github.com/google/go-containerregistry/pkg/authn" - "github.com/google/go-containerregistry/pkg/crane" - "github.com/google/go-containerregistry/pkg/name" - "github.com/google/go-containerregistry/pkg/v1/remote" -) - -type Image struct { - Original string - Name string - Registry string - Repository string - Tag string - Digest string -} - -func parseReference(s string, extractTag bool, opts ...name.Option) (*Image, error) { - ref, err := name.ParseReference(s, opts...) - if err != nil { - return nil, err - } - - var img Image - switch u := ref.(type) { - case name.Tag: - img.Registry = u.RegistryStr() - img.Repository = u.RepositoryStr() - img.Tag = u.TagStr() - if extractTag { - img.Digest, err = crane.Digest(s, crane.WithAuthFromKeychain(authn.DefaultKeychain)) - if err != nil { - return nil, err - } - } else { - img.Digest = "" - } - img.Name = u.Name() - img.Original = u.String() - case name.Digest: - img.Registry = u.RegistryStr() - img.Repository = u.RepositoryStr() - if tag, err := name.NewTag( - strings.Split(s, "@")[0], // skip the digest - append(opts, name.WithDefaultTag(""))..., // don't use defaultTag "latest" - ); err == nil { - img.Tag = tag.TagStr() - } - img.Digest = u.DigestStr() - img.Name = u.Name() - img.Original = u.String() - default: - return nil, fmt.Errorf("unknown image %T", ref) - } - return &img, nil -} - -func ParseReference(s string, opts ...name.Option) (*Image, error) { - return parseReference(s, false, opts...) -} - -func ParseOrExtractDigest(s string, opts ...name.Option) (*Image, error) { - return parseReference(s, true, opts...) -} - -func IsPrivateImage(img string) (bool, error) { - reference, err := name.ParseReference(img) - if err != nil { - return false, err - } - - _, err = remote.Get(reference, remote.WithAuthFromKeychain(authn.DefaultKeychain)) - if err == nil { - return false, nil - } - if strings.Contains(err.Error(), "UNAUTHORIZED") { - return true, nil - } - if strings.Contains(err.Error(), "MANIFEST_UNKNOWN") { // If the image is kind loaded (not available online) - return true, nil - } - - return true, err -} diff --git a/vendor/kmodules.xyz/offshoot-api/api/v2/doc.go b/vendor/kmodules.xyz/offshoot-api/api/v2/doc.go deleted file mode 100644 index ee23698bf..000000000 --- a/vendor/kmodules.xyz/offshoot-api/api/v2/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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. -*/ - -// +k8s:deepcopy-gen=package -// +k8s:openapi-gen=true -// +gencrdrefdocs:force=true -package v2 // import "kmodules.xyz/offshoot-api/api/v2" diff --git a/vendor/kmodules.xyz/offshoot-api/api/v2/openapi_generated.go b/vendor/kmodules.xyz/offshoot-api/api/v2/openapi_generated.go deleted file mode 100644 index a3343cfb3..000000000 --- a/vendor/kmodules.xyz/offshoot-api/api/v2/openapi_generated.go +++ /dev/null @@ -1,452 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright AppsCode Inc. and Contributors - -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. -*/ - -// Code generated by openapi-gen. DO NOT EDIT. - -// This file was autogenerated by openapi-gen. Do not edit it manually! - -package v2 - -import ( - common "k8s.io/kube-openapi/pkg/common" - spec "k8s.io/kube-openapi/pkg/validation/spec" -) - -func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenAPIDefinition { - return map[string]common.OpenAPIDefinition{ - "kmodules.xyz/offshoot-api/api/v2.PodSpec": schema_kmodulesxyz_offshoot_api_api_v2_PodSpec(ref), - "kmodules.xyz/offshoot-api/api/v2.PodTemplateSpec": schema_kmodulesxyz_offshoot_api_api_v2_PodTemplateSpec(ref), - } -} - -func schema_kmodulesxyz_offshoot_api_api_v2_PodSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodSpec is a description of a pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "volumes": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge,retainKeys", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/offshoot-api/api/v1.Volume"), - }, - }, - }, - }, - }, - "initContainers": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of initialization containers belonging to the pod. Init containers are executed in order prior to containers being started. If any init container fails, the pod is considered to have failed and is handled according to its restartPolicy. The name for an init container or normal container must be unique among all containers. Init containers may not have Lifecycle actions, Readiness probes, Liveness probes, or Startup probes. The resourceRequirements of an init container are taken into account during scheduling by finding the highest request/limit for each resource type, and then using the max of of that value or the sum of the normal containers. Limits are applied to init containers in a similar fashion. Init containers cannot currently be added or removed. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Container"), - }, - }, - }, - }, - }, - "containers": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of sidecar containers belonging to the pod. Containers cannot currently be added or removed.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Container"), - }, - }, - }, - }, - }, - "ephemeralContainers": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of ephemeral containers run in this pod. Ephemeral containers may be run in an existing pod to perform user-initiated actions such as debugging. This list cannot be specified when creating a pod, and it cannot be modified by updating the pod spec. In order to add an ephemeral container to an existing pod, use the pod's ephemeralcontainers subresource.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EphemeralContainer"), - }, - }, - }, - }, - }, - "restartPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Restart policy for all containers within the pod. One of Always, OnFailure, Never. In some contexts, only a subset of those values may be permitted. Default to Always. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy", - Type: []string{"string"}, - Format: "", - }, - }, - "terminationGracePeriodSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Optional duration in seconds the pod needs to terminate gracefully. May be decreased in delete request. Value must be non-negative integer. The value zero indicates stop immediately via the kill signal (no opportunity to shut down). If this value is nil, the default grace period will be used instead. The grace period is the duration in seconds after the processes running in the pod are sent a termination signal and the time when the processes are forcibly halted with a kill signal. Set this value longer than the expected cleanup time for your process. Defaults to 30 seconds.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "activeDeadlineSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Optional duration in seconds the pod may be active on the node relative to StartTime before the system will actively try to mark it failed and kill associated containers. Value must be a positive integer.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "dnsPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Set DNS policy for the pod. Defaults to \"ClusterFirst\". Valid values are 'ClusterFirstWithHostNet', 'ClusterFirst', 'Default' or 'None'. DNS parameters given in DNSConfig will be merged with the policy selected with DNSPolicy. To have DNS options set along with hostNetwork, you have to specify DNS policy explicitly to 'ClusterFirstWithHostNet'.", - Type: []string{"string"}, - Format: "", - }, - }, - "nodeSelector": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "NodeSelector is a selector which must be true for the pod to fit on a node. Selector which must match a node's labels for the pod to be scheduled on that node. More info: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "serviceAccountName": { - SchemaProps: spec.SchemaProps{ - Description: "ServiceAccountName is the name of the ServiceAccount to use to run this pod. More info: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/", - Type: []string{"string"}, - Format: "", - }, - }, - "automountServiceAccountToken": { - SchemaProps: spec.SchemaProps{ - Description: "AutomountServiceAccountToken indicates whether a service account token should be automatically mounted.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "nodeName": { - SchemaProps: spec.SchemaProps{ - Description: "NodeName is a request to schedule this pod onto a specific node. If it is non-empty, the scheduler simply schedules this pod onto that node, assuming that it fits resource requirements.", - Type: []string{"string"}, - Format: "", - }, - }, - "hostNetwork": { - SchemaProps: spec.SchemaProps{ - Description: "Host networking requested for this pod. Use the host's network namespace. If this option is set, the ports that will be used must be specified. Default to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "hostPID": { - SchemaProps: spec.SchemaProps{ - Description: "Use the host's pid namespace. Optional: Default to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "hostIPC": { - SchemaProps: spec.SchemaProps{ - Description: "Use the host's ipc namespace. Optional: Default to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "shareProcessNamespace": { - SchemaProps: spec.SchemaProps{ - Description: "Share a single process namespace between all of the containers in a pod. When this is set containers will be able to view and signal processes from other containers in the same pod, and the first process in each container will not be assigned PID 1. HostPID and ShareProcessNamespace cannot both be set. Optional: Default to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "securityContext": { - SchemaProps: spec.SchemaProps{ - Description: "SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field.", - Ref: ref("k8s.io/api/core/v1.PodSecurityContext"), - }, - }, - "imagePullSecrets": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. If specified, these secrets will be passed to individual puller implementations for them to use. More info: https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - }, - }, - }, - "affinity": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, the pod's scheduling constraints", - Ref: ref("k8s.io/api/core/v1.Affinity"), - }, - }, - "schedulerName": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, the pod will be dispatched by specified scheduler. If not specified, the pod will be dispatched by default scheduler.", - Type: []string{"string"}, - Format: "", - }, - }, - "tolerations": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, the pod's tolerations.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Toleration"), - }, - }, - }, - }, - }, - "hostAliases": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "ip", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "HostAliases is an optional list of hosts and IPs that will be injected into the pod's hosts file if specified. This is only valid for non-hostNetwork pods.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.HostAlias"), - }, - }, - }, - }, - }, - "priorityClassName": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, indicates the pod's priority. \"system-node-critical\" and \"system-cluster-critical\" are two special keywords which indicate the highest priorities with the former being the highest priority. Any other name must be defined by creating a PriorityClass object with that name. If not specified, the pod priority will be default or zero if there is no default.", - Type: []string{"string"}, - Format: "", - }, - }, - "priority": { - SchemaProps: spec.SchemaProps{ - Description: "The priority value. Various system components use this field to find the priority of the pod. When Priority Admission Controller is enabled, it prevents users from setting this field. The admission controller populates this field from PriorityClassName. The higher the value, the higher the priority.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "dnsConfig": { - SchemaProps: spec.SchemaProps{ - Description: "Specifies the DNS parameters of a pod. Parameters specified here will be merged to the generated DNS configuration based on DNSPolicy.", - Ref: ref("k8s.io/api/core/v1.PodDNSConfig"), - }, - }, - "readinessGates": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, all readiness gates will be evaluated for pod readiness. A pod is ready when all its containers are ready AND all conditions specified in the readiness gates have status equal to \"True\" More info: https://git.k8s.io/enhancements/keps/sig-network/580-pod-readiness-gates", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodReadinessGate"), - }, - }, - }, - }, - }, - "runtimeClassName": { - SchemaProps: spec.SchemaProps{ - Description: "RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group, which should be used to run this pod. If no RuntimeClass resource matches the named class, the pod will not be run. If unset or empty, the \"legacy\" RuntimeClass will be used, which is an implicit class with an empty definition that uses the default runtime handler. More info: https://git.k8s.io/enhancements/keps/sig-node/585-runtime-class", - Type: []string{"string"}, - Format: "", - }, - }, - "enableServiceLinks": { - SchemaProps: spec.SchemaProps{ - Description: "EnableServiceLinks indicates whether information about services should be injected into pod's environment variables, matching the syntax of Docker links. Optional: Defaults to true.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "preemptionPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "PreemptionPolicy is the Policy for preempting pods with lower priority. One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset.", - Type: []string{"string"}, - Format: "", - }, - }, - "overhead": { - SchemaProps: spec.SchemaProps{ - Description: "Overhead represents the resource overhead associated with running a pod for a given RuntimeClass. This field will be autopopulated at admission time by the RuntimeClass admission controller. If the RuntimeClass admission controller is enabled, overhead must not be set in Pod create requests. The RuntimeClass admission controller will reject Pod create requests which have the overhead already set. If RuntimeClass is configured and selected in the PodSpec, Overhead will be set to the value defined in the corresponding RuntimeClass, otherwise it will remain unset and treated as zero. More info: https://git.k8s.io/enhancements/keps/sig-node/688-pod-overhead/README.md", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "topologySpreadConstraints": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "topologyKey", - "whenUnsatisfiable", - }, - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "topologyKey", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "TopologySpreadConstraints describes how a group of pods ought to spread across topology domains. Scheduler will schedule pods in a way which abides by the constraints. All topologySpreadConstraints are ANDed.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.TopologySpreadConstraint"), - }, - }, - }, - }, - }, - "setHostnameAsFQDN": { - SchemaProps: spec.SchemaProps{ - Description: "If true the pod's hostname will be configured as the pod's FQDN, rather than the leaf name (the default). In Linux containers, this means setting the FQDN in the hostname field of the kernel (the nodename field of struct utsname). In Windows containers, this means setting the registry value of hostname for the registry key HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters to FQDN. If a pod does not have FQDN, this has no effect. Default to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "os": { - SchemaProps: spec.SchemaProps{ - Description: "Specifies the OS of the containers in the pod. Some pod and container fields are restricted if this is set.\n\nIf the OS field is set to linux, the following fields must be unset: -securityContext.windowsOptions\n\nIf the OS field is set to windows, following fields must be unset: - spec.hostPID - spec.hostIPC - spec.hostUsers - spec.securityContext.seLinuxOptions - spec.securityContext.seccompProfile - spec.securityContext.fsGroup - spec.securityContext.fsGroupChangePolicy - spec.securityContext.sysctls - spec.shareProcessNamespace - spec.securityContext.runAsUser - spec.securityContext.runAsGroup - spec.securityContext.supplementalGroups - spec.containers[*].securityContext.seLinuxOptions - spec.containers[*].securityContext.seccompProfile - spec.containers[*].securityContext.capabilities - spec.containers[*].securityContext.readOnlyRootFilesystem - spec.containers[*].securityContext.privileged - spec.containers[*].securityContext.allowPrivilegeEscalation - spec.containers[*].securityContext.procMount - spec.containers[*].securityContext.runAsUser - spec.containers[*].securityContext.runAsGroup", - Ref: ref("k8s.io/api/core/v1.PodOS"), - }, - }, - "hostUsers": { - SchemaProps: spec.SchemaProps{ - Description: "Use the host's user namespace. Optional: Default to true. If set to true or not present, the pod will be run in the host user namespace, useful for when the pod needs a feature only available to the host user namespace, such as loading a kernel module with CAP_SYS_MODULE. When set to false, a new userns is created for the pod. Setting false is useful for mitigating container breakout vulnerabilities even allowing users to run their containers as root without actually having root privileges on the host. This field is alpha-level and is only honored by servers that enable the UserNamespacesSupport feature.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.Affinity", "k8s.io/api/core/v1.Container", "k8s.io/api/core/v1.EphemeralContainer", "k8s.io/api/core/v1.HostAlias", "k8s.io/api/core/v1.LocalObjectReference", "k8s.io/api/core/v1.PodDNSConfig", "k8s.io/api/core/v1.PodOS", "k8s.io/api/core/v1.PodReadinessGate", "k8s.io/api/core/v1.PodSecurityContext", "k8s.io/api/core/v1.Toleration", "k8s.io/api/core/v1.TopologySpreadConstraint", "k8s.io/apimachinery/pkg/api/resource.Quantity", "kmodules.xyz/offshoot-api/api/v1.Volume"}, - } -} - -func schema_kmodulesxyz_offshoot_api_api_v2_PodTemplateSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodTemplateSpec describes the data a pod should have when created from a template", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/offshoot-api/api/v1.ObjectMeta"), - }, - }, - "controller": { - SchemaProps: spec.SchemaProps{ - Description: "Workload controller's metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/offshoot-api/api/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Specification of the desired behavior of the pod. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/offshoot-api/api/v2.PodSpec"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "kmodules.xyz/offshoot-api/api/v1.ObjectMeta", "kmodules.xyz/offshoot-api/api/v2.PodSpec"}, - } -} diff --git a/vendor/kmodules.xyz/offshoot-api/api/v2/types.go b/vendor/kmodules.xyz/offshoot-api/api/v2/types.go deleted file mode 100644 index 843ec57aa..000000000 --- a/vendor/kmodules.xyz/offshoot-api/api/v2/types.go +++ /dev/null @@ -1,292 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v2 - -import ( - v1 "kmodules.xyz/offshoot-api/api/v1" - - core "k8s.io/api/core/v1" -) - -// PodTemplateSpec describes the data a pod should have when created from a template -type PodTemplateSpec struct { - // Standard object's metadata. - // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata - // +optional - v1.ObjectMeta `json:"metadata,omitempty"` - - // Workload controller's metadata. - // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata - // +optional - Controller v1.ObjectMeta `json:"controller,omitempty"` - - // Specification of the desired behavior of the pod. - // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status - // +optional - Spec PodSpec `json:"spec,omitempty"` -} - -// PodSpec is a description of a pod. -type PodSpec struct { - // List of volumes that can be mounted by containers belonging to the pod. - // More info: https://kubernetes.io/docs/concepts/storage/volumes - // +optional - // +patchMergeKey=name - // +patchStrategy=merge,retainKeys - Volumes []v1.Volume `json:"volumes,omitempty" patchStrategy:"merge,retainKeys" patchMergeKey:"name"` - // List of initialization containers belonging to the pod. - // Init containers are executed in order prior to containers being started. If any - // init container fails, the pod is considered to have failed and is handled according - // to its restartPolicy. The name for an init container or normal container must be - // unique among all containers. - // Init containers may not have Lifecycle actions, Readiness probes, Liveness probes, or Startup probes. - // The resourceRequirements of an init container are taken into account during scheduling - // by finding the highest request/limit for each resource type, and then using the max of - // of that value or the sum of the normal containers. Limits are applied to init containers - // in a similar fashion. - // Init containers cannot currently be added or removed. - // Cannot be updated. - // More info: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/ - // +patchMergeKey=name - // +patchStrategy=merge - InitContainers []core.Container `json:"initContainers,omitempty" patchStrategy:"merge" patchMergeKey:"name"` - // List of sidecar containers belonging to the pod. - // Containers cannot currently be added or removed. - // +patchMergeKey=name - // +patchStrategy=merge - Containers []core.Container `json:"containers,omitempty" patchStrategy:"merge" patchMergeKey:"name"` - // List of ephemeral containers run in this pod. Ephemeral containers may be run in an existing - // pod to perform user-initiated actions such as debugging. This list cannot be specified when - // creating a pod, and it cannot be modified by updating the pod spec. In order to add an - // ephemeral container to an existing pod, use the pod's ephemeralcontainers subresource. - // +optional - // +patchMergeKey=name - // +patchStrategy=merge - EphemeralContainers []core.EphemeralContainer `json:"ephemeralContainers,omitempty" patchStrategy:"merge" patchMergeKey:"name"` - // Restart policy for all containers within the pod. - // One of Always, OnFailure, Never. In some contexts, only a subset of those values may be permitted. - // Default to Always. - // More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy - // +optional - RestartPolicy core.RestartPolicy `json:"restartPolicy,omitempty"` - // Optional duration in seconds the pod needs to terminate gracefully. May be decreased in delete request. - // Value must be non-negative integer. The value zero indicates stop immediately via - // the kill signal (no opportunity to shut down). - // If this value is nil, the default grace period will be used instead. - // The grace period is the duration in seconds after the processes running in the pod are sent - // a termination signal and the time when the processes are forcibly halted with a kill signal. - // Set this value longer than the expected cleanup time for your process. - // Defaults to 30 seconds. - // +optional - TerminationGracePeriodSeconds *int64 `json:"terminationGracePeriodSeconds,omitempty"` - // Optional duration in seconds the pod may be active on the node relative to - // StartTime before the system will actively try to mark it failed and kill associated containers. - // Value must be a positive integer. - // +optional - ActiveDeadlineSeconds *int64 `json:"activeDeadlineSeconds,omitempty"` - // Set DNS policy for the pod. - // Defaults to "ClusterFirst". - // Valid values are 'ClusterFirstWithHostNet', 'ClusterFirst', 'Default' or 'None'. - // DNS parameters given in DNSConfig will be merged with the policy selected with DNSPolicy. - // To have DNS options set along with hostNetwork, you have to specify DNS policy - // explicitly to 'ClusterFirstWithHostNet'. - // +optional - DNSPolicy core.DNSPolicy `json:"dnsPolicy,omitempty"` - // NodeSelector is a selector which must be true for the pod to fit on a node. - // Selector which must match a node's labels for the pod to be scheduled on that node. - // More info: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/ - // +optional - // +mapType=atomic - NodeSelector map[string]string `json:"nodeSelector,omitempty"` - - // ServiceAccountName is the name of the ServiceAccount to use to run this pod. - // More info: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/ - // +optional - ServiceAccountName string `json:"serviceAccountName,omitempty"` - // AutomountServiceAccountToken indicates whether a service account token should be automatically mounted. - // +optional - AutomountServiceAccountToken *bool `json:"automountServiceAccountToken,omitempty"` - - // NodeName is a request to schedule this pod onto a specific node. If it is non-empty, - // the scheduler simply schedules this pod onto that node, assuming that it fits resource - // requirements. - // +optional - NodeName string `json:"nodeName,omitempty"` - // Host networking requested for this pod. Use the host's network namespace. - // If this option is set, the ports that will be used must be specified. - // Default to false. - // +k8s:conversion-gen=false - // +optional - HostNetwork bool `json:"hostNetwork,omitempty"` - // Use the host's pid namespace. - // Optional: Default to false. - // +k8s:conversion-gen=false - // +optional - HostPID bool `json:"hostPID,omitempty"` - // Use the host's ipc namespace. - // Optional: Default to false. - // +k8s:conversion-gen=false - // +optional - HostIPC bool `json:"hostIPC,omitempty"` - // Share a single process namespace between all of the containers in a pod. - // When this is set containers will be able to view and signal processes from other containers - // in the same pod, and the first process in each container will not be assigned PID 1. - // HostPID and ShareProcessNamespace cannot both be set. - // Optional: Default to false. - // +k8s:conversion-gen=false - // +optional - ShareProcessNamespace *bool `json:"shareProcessNamespace,omitempty"` - // SecurityContext holds pod-level security attributes and common container settings. - // Optional: Defaults to empty. See type description for default values of each field. - // +optional - SecurityContext *core.PodSecurityContext `json:"securityContext,omitempty"` - // ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. - // If specified, these secrets will be passed to individual puller implementations for them to use. - // More info: https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod - // +optional - // +patchMergeKey=name - // +patchStrategy=merge - ImagePullSecrets []core.LocalObjectReference `json:"imagePullSecrets,omitempty" patchStrategy:"merge" patchMergeKey:"name"` - // If specified, the pod's scheduling constraints - // +optional - Affinity *core.Affinity `json:"affinity,omitempty"` - // If specified, the pod will be dispatched by specified scheduler. - // If not specified, the pod will be dispatched by default scheduler. - // +optional - SchedulerName string `json:"schedulerName,omitempty"` - // If specified, the pod's tolerations. - // +optional - Tolerations []core.Toleration `json:"tolerations,omitempty"` - // HostAliases is an optional list of hosts and IPs that will be injected into the pod's hosts - // file if specified. This is only valid for non-hostNetwork pods. - // +optional - // +patchMergeKey=ip - // +patchStrategy=merge - HostAliases []core.HostAlias `json:"hostAliases,omitempty" patchStrategy:"merge" patchMergeKey:"ip"` - // If specified, indicates the pod's priority. "system-node-critical" and - // "system-cluster-critical" are two special keywords which indicate the - // highest priorities with the former being the highest priority. Any other - // name must be defined by creating a PriorityClass object with that name. - // If not specified, the pod priority will be default or zero if there is no - // default. - // +optional - PriorityClassName string `json:"priorityClassName,omitempty"` - // The priority value. Various system components use this field to find the - // priority of the pod. When Priority Admission Controller is enabled, it - // prevents users from setting this field. The admission controller populates - // this field from PriorityClassName. - // The higher the value, the higher the priority. - // +optional - Priority *int32 `json:"priority,omitempty"` - // Specifies the DNS parameters of a pod. - // Parameters specified here will be merged to the generated DNS - // configuration based on DNSPolicy. - // +optional - DNSConfig *core.PodDNSConfig `json:"dnsConfig,omitempty"` - // If specified, all readiness gates will be evaluated for pod readiness. - // A pod is ready when all its containers are ready AND - // all conditions specified in the readiness gates have status equal to "True" - // More info: https://git.k8s.io/enhancements/keps/sig-network/580-pod-readiness-gates - // +optional - ReadinessGates []core.PodReadinessGate `json:"readinessGates,omitempty"` - // RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group, which should be used - // to run this pod. If no RuntimeClass resource matches the named class, the pod will not be run. - // If unset or empty, the "legacy" RuntimeClass will be used, which is an implicit class with an - // empty definition that uses the default runtime handler. - // More info: https://git.k8s.io/enhancements/keps/sig-node/585-runtime-class - // +optional - RuntimeClassName *string `json:"runtimeClassName,omitempty"` - // EnableServiceLinks indicates whether information about services should be injected into pod's - // environment variables, matching the syntax of Docker links. - // Optional: Defaults to true. - // +optional - EnableServiceLinks *bool `json:"enableServiceLinks,omitempty"` - // PreemptionPolicy is the Policy for preempting pods with lower priority. - // One of Never, PreemptLowerPriority. - // Defaults to PreemptLowerPriority if unset. - // +optional - PreemptionPolicy *core.PreemptionPolicy `json:"preemptionPolicy,omitempty"` - // Overhead represents the resource overhead associated with running a pod for a given RuntimeClass. - // This field will be autopopulated at admission time by the RuntimeClass admission controller. If - // the RuntimeClass admission controller is enabled, overhead must not be set in Pod create requests. - // The RuntimeClass admission controller will reject Pod create requests which have the overhead already - // set. If RuntimeClass is configured and selected in the PodSpec, Overhead will be set to the value - // defined in the corresponding RuntimeClass, otherwise it will remain unset and treated as zero. - // More info: https://git.k8s.io/enhancements/keps/sig-node/688-pod-overhead/README.md - // +optional - Overhead core.ResourceList `json:"overhead,omitempty"` - // TopologySpreadConstraints describes how a group of pods ought to spread across topology - // domains. Scheduler will schedule pods in a way which abides by the constraints. - // All topologySpreadConstraints are ANDed. - // +optional - // +patchMergeKey=topologyKey - // +patchStrategy=merge - // +listType=map - // +listMapKey=topologyKey - // +listMapKey=whenUnsatisfiable - TopologySpreadConstraints []core.TopologySpreadConstraint `json:"topologySpreadConstraints,omitempty" patchStrategy:"merge" patchMergeKey:"topologyKey"` - // If true the pod's hostname will be configured as the pod's FQDN, rather than the leaf name (the default). - // In Linux containers, this means setting the FQDN in the hostname field of the kernel (the nodename field of struct utsname). - // In Windows containers, this means setting the registry value of hostname for the registry key HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters to FQDN. - // If a pod does not have FQDN, this has no effect. - // Default to false. - // +optional - SetHostnameAsFQDN *bool `json:"setHostnameAsFQDN,omitempty"` - // Specifies the OS of the containers in the pod. - // Some pod and container fields are restricted if this is set. - // - // If the OS field is set to linux, the following fields must be unset: - // -securityContext.windowsOptions - // - // If the OS field is set to windows, following fields must be unset: - // - spec.hostPID - // - spec.hostIPC - // - spec.hostUsers - // - spec.securityContext.seLinuxOptions - // - spec.securityContext.seccompProfile - // - spec.securityContext.fsGroup - // - spec.securityContext.fsGroupChangePolicy - // - spec.securityContext.sysctls - // - spec.shareProcessNamespace - // - spec.securityContext.runAsUser - // - spec.securityContext.runAsGroup - // - spec.securityContext.supplementalGroups - // - spec.containers[*].securityContext.seLinuxOptions - // - spec.containers[*].securityContext.seccompProfile - // - spec.containers[*].securityContext.capabilities - // - spec.containers[*].securityContext.readOnlyRootFilesystem - // - spec.containers[*].securityContext.privileged - // - spec.containers[*].securityContext.allowPrivilegeEscalation - // - spec.containers[*].securityContext.procMount - // - spec.containers[*].securityContext.runAsUser - // - spec.containers[*].securityContext.runAsGroup - // +optional - OS *core.PodOS `json:"os,omitempty"` - - // Use the host's user namespace. - // Optional: Default to true. - // If set to true or not present, the pod will be run in the host user namespace, useful - // for when the pod needs a feature only available to the host user namespace, such as - // loading a kernel module with CAP_SYS_MODULE. - // When set to false, a new userns is created for the pod. Setting false is useful for - // mitigating container breakout vulnerabilities even allowing users to run their - // containers as root without actually having root privileges on the host. - // This field is alpha-level and is only honored by servers that enable the UserNamespacesSupport feature. - // +k8s:conversion-gen=false - // +optional - HostUsers *bool `json:"hostUsers,omitempty"` -} diff --git a/vendor/kmodules.xyz/offshoot-api/api/v2/zz_generated.deepcopy.go b/vendor/kmodules.xyz/offshoot-api/api/v2/zz_generated.deepcopy.go deleted file mode 100644 index d907cdee3..000000000 --- a/vendor/kmodules.xyz/offshoot-api/api/v2/zz_generated.deepcopy.go +++ /dev/null @@ -1,206 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright AppsCode Inc. and Contributors - -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. -*/ - -// Code generated by deepcopy-gen. DO NOT EDIT. - -package v2 - -import ( - v1 "kmodules.xyz/offshoot-api/api/v1" - - corev1 "k8s.io/api/core/v1" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PodSpec) DeepCopyInto(out *PodSpec) { - *out = *in - if in.Volumes != nil { - in, out := &in.Volumes, &out.Volumes - *out = make([]v1.Volume, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.InitContainers != nil { - in, out := &in.InitContainers, &out.InitContainers - *out = make([]corev1.Container, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Containers != nil { - in, out := &in.Containers, &out.Containers - *out = make([]corev1.Container, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.EphemeralContainers != nil { - in, out := &in.EphemeralContainers, &out.EphemeralContainers - *out = make([]corev1.EphemeralContainer, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.TerminationGracePeriodSeconds != nil { - in, out := &in.TerminationGracePeriodSeconds, &out.TerminationGracePeriodSeconds - *out = new(int64) - **out = **in - } - if in.ActiveDeadlineSeconds != nil { - in, out := &in.ActiveDeadlineSeconds, &out.ActiveDeadlineSeconds - *out = new(int64) - **out = **in - } - if in.NodeSelector != nil { - in, out := &in.NodeSelector, &out.NodeSelector - *out = make(map[string]string, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - if in.AutomountServiceAccountToken != nil { - in, out := &in.AutomountServiceAccountToken, &out.AutomountServiceAccountToken - *out = new(bool) - **out = **in - } - if in.ShareProcessNamespace != nil { - in, out := &in.ShareProcessNamespace, &out.ShareProcessNamespace - *out = new(bool) - **out = **in - } - if in.SecurityContext != nil { - in, out := &in.SecurityContext, &out.SecurityContext - *out = new(corev1.PodSecurityContext) - (*in).DeepCopyInto(*out) - } - if in.ImagePullSecrets != nil { - in, out := &in.ImagePullSecrets, &out.ImagePullSecrets - *out = make([]corev1.LocalObjectReference, len(*in)) - copy(*out, *in) - } - if in.Affinity != nil { - in, out := &in.Affinity, &out.Affinity - *out = new(corev1.Affinity) - (*in).DeepCopyInto(*out) - } - if in.Tolerations != nil { - in, out := &in.Tolerations, &out.Tolerations - *out = make([]corev1.Toleration, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.HostAliases != nil { - in, out := &in.HostAliases, &out.HostAliases - *out = make([]corev1.HostAlias, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Priority != nil { - in, out := &in.Priority, &out.Priority - *out = new(int32) - **out = **in - } - if in.DNSConfig != nil { - in, out := &in.DNSConfig, &out.DNSConfig - *out = new(corev1.PodDNSConfig) - (*in).DeepCopyInto(*out) - } - if in.ReadinessGates != nil { - in, out := &in.ReadinessGates, &out.ReadinessGates - *out = make([]corev1.PodReadinessGate, len(*in)) - copy(*out, *in) - } - if in.RuntimeClassName != nil { - in, out := &in.RuntimeClassName, &out.RuntimeClassName - *out = new(string) - **out = **in - } - if in.EnableServiceLinks != nil { - in, out := &in.EnableServiceLinks, &out.EnableServiceLinks - *out = new(bool) - **out = **in - } - if in.PreemptionPolicy != nil { - in, out := &in.PreemptionPolicy, &out.PreemptionPolicy - *out = new(corev1.PreemptionPolicy) - **out = **in - } - if in.Overhead != nil { - in, out := &in.Overhead, &out.Overhead - *out = make(corev1.ResourceList, len(*in)) - for key, val := range *in { - (*out)[key] = val.DeepCopy() - } - } - if in.TopologySpreadConstraints != nil { - in, out := &in.TopologySpreadConstraints, &out.TopologySpreadConstraints - *out = make([]corev1.TopologySpreadConstraint, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.SetHostnameAsFQDN != nil { - in, out := &in.SetHostnameAsFQDN, &out.SetHostnameAsFQDN - *out = new(bool) - **out = **in - } - if in.OS != nil { - in, out := &in.OS, &out.OS - *out = new(corev1.PodOS) - **out = **in - } - if in.HostUsers != nil { - in, out := &in.HostUsers, &out.HostUsers - *out = new(bool) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodSpec. -func (in *PodSpec) DeepCopy() *PodSpec { - if in == nil { - return nil - } - out := new(PodSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PodTemplateSpec) DeepCopyInto(out *PodTemplateSpec) { - *out = *in - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Controller.DeepCopyInto(&out.Controller) - in.Spec.DeepCopyInto(&out.Spec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodTemplateSpec. -func (in *PodTemplateSpec) DeepCopy() *PodTemplateSpec { - if in == nil { - return nil - } - out := new(PodTemplateSpec) - in.DeepCopyInto(out) - return out -} diff --git a/vendor/kmodules.xyz/resource-metadata/LICENSE b/vendor/kmodules.xyz/resource-metadata/LICENSE deleted file mode 100644 index 8dada3eda..000000000 --- a/vendor/kmodules.xyz/resource-metadata/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - 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 "{}" - 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 - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - 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. diff --git a/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/doc.go b/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/doc.go deleted file mode 100644 index 305555413..000000000 --- a/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/doc.go +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors. - -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 v1alpha1 contains API Schema definitions for the ui v1alpha1 API group - -// +k8s:openapi-gen=true -// +k8s:deepcopy-gen=package -// +k8s:defaulter-gen=TypeMeta -// +groupName=core.k8s.appscode.com -package v1alpha1 // import "kmodules.xyz/resource-metadata/apis/core/v1alpha1" diff --git a/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/generic_resource_helpers.go b/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/generic_resource_helpers.go deleted file mode 100644 index 62908a911..000000000 --- a/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/generic_resource_helpers.go +++ /dev/null @@ -1,193 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors. - -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 v1alpha1 - -import ( - "encoding/json" - "fmt" - "strings" - - kmapi "kmodules.xyz/client-go/api/v1" - mu "kmodules.xyz/client-go/meta" - resourcemetrics "kmodules.xyz/resource-metrics" - "kmodules.xyz/resource-metrics/api" - - core "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "sigs.k8s.io/cli-utils/pkg/kstatus/status" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -func GetGenericResourceName(item client.Object) string { - return fmt.Sprintf("%s~%s", item.GetName(), item.GetObjectKind().GroupVersionKind().GroupKind()) -} - -func ParseGenericResourceName(name string) (string, schema.GroupKind, error) { - parts := strings.SplitN(name, "~", 2) - if len(parts) != 2 { - return "", schema.GroupKind{}, fmt.Errorf("expected resource name %s in format {.metadata.name}~Kind.Group", name) - } - return parts[0], schema.ParseGroupKind(parts[1]), nil -} - -func ToGenericResource(item client.Object, apiType *kmapi.ResourceID, cmeta *kmapi.ClusterMetadata) (*GenericResource, error) { - content, err := runtime.DefaultUnstructuredConverter.ToUnstructured(item) - if err != nil { - return nil, err - } - - s, err := status.Compute(&unstructured.Unstructured{ - Object: content, - }) - if err != nil { - return nil, err - } - - // api.RegisteredTypes() - - var resstatus *runtime.RawExtension - if v, ok, _ := unstructured.NestedFieldNoCopy(content, "status"); ok { - data, err := json.Marshal(v) - if err != nil { - return nil, fmt.Errorf("failed to convert status to json, reason: %v", err) - } - resstatus = &runtime.RawExtension{Raw: data} - } - - genres := GenericResource{ - TypeMeta: metav1.TypeMeta{ - APIVersion: SchemeGroupVersion.String(), - Kind: ResourceKindGenericResource, - }, - ObjectMeta: metav1.ObjectMeta{ - Name: GetGenericResourceName(item), - GenerateName: item.GetGenerateName(), - Namespace: item.GetNamespace(), - SelfLink: "", - UID: "gres-" + item.GetUID(), - ResourceVersion: item.GetResourceVersion(), - Generation: item.GetGeneration(), - CreationTimestamp: item.GetCreationTimestamp(), - DeletionTimestamp: item.GetDeletionTimestamp(), - DeletionGracePeriodSeconds: item.GetDeletionGracePeriodSeconds(), - Labels: item.GetLabels(), - Annotations: map[string]string{}, - // OwnerReferences: item.GetOwnerReferences(), - // Finalizers: item.GetFinalizers(), - // ClusterName: item.GetClusterName(), - // ManagedFields: nil, - }, - Spec: GenericResourceSpec{ - Cluster: *cmeta, - APIType: *apiType, - Name: item.GetName(), - UID: item.GetUID(), - Replicas: 0, - RoleReplicas: nil, - Mode: "", - TotalResource: core.ResourceRequirements{}, - AppResource: core.ResourceRequirements{}, - RoleResourceLimits: nil, - RoleResourceRequests: nil, - - Status: GenericResourceStatus{ - Status: s.Status.String(), - Message: s.Message, - }, - }, - Status: resstatus, - } - for k, v := range item.GetAnnotations() { - if k != mu.LastAppliedConfigAnnotation { - genres.Annotations[k] = v - } - } - { - if v, ok, _ := unstructured.NestedString(content, "spec", "version"); ok { - genres.Spec.Version = v - } - } - if api.IsRegistered(apiType.GroupVersionKind()) { - { - rv, err := resourcemetrics.Replicas(content) - if err != nil { - return nil, err - } - genres.Spec.Replicas = rv - } - { - rv, err := resourcemetrics.RoleReplicas(content) - if err != nil { - return nil, err - } - genres.Spec.RoleReplicas = rv - } - { - rv, err := resourcemetrics.Mode(content) - if err != nil { - return nil, err - } - genres.Spec.Mode = rv - } - { - rv, err := resourcemetrics.TotalResourceRequests(content) - if err != nil { - return nil, err - } - genres.Spec.TotalResource.Requests = rv - } - { - rv, err := resourcemetrics.TotalResourceLimits(content) - if err != nil { - return nil, err - } - genres.Spec.TotalResource.Limits = rv - } - { - rv, err := resourcemetrics.AppResourceRequests(content) - if err != nil { - return nil, err - } - genres.Spec.AppResource.Requests = rv - } - { - rv, err := resourcemetrics.AppResourceLimits(content) - if err != nil { - return nil, err - } - genres.Spec.AppResource.Limits = rv - } - { - rv, err := resourcemetrics.RoleResourceRequests(content) - if err != nil { - return nil, err - } - genres.Spec.RoleResourceRequests = rv - } - { - rv, err := resourcemetrics.RoleResourceLimits(content) - if err != nil { - return nil, err - } - genres.Spec.RoleResourceLimits = rv - } - } - return &genres, nil -} diff --git a/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/generic_resource_service_types.go b/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/generic_resource_service_types.go deleted file mode 100644 index 20435663a..000000000 --- a/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/generic_resource_service_types.go +++ /dev/null @@ -1,113 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors. - -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 v1alpha1 - -import ( - kmapi "kmodules.xyz/client-go/api/v1" - "kmodules.xyz/resource-metadata/apis/shared" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" -) - -const ( - ResourceKindGenericResourceService = "GenericResourceService" - ResourceGenericResourceService = "genericresourceservice" - ResourceGenericResourceServices = "genericresourceservices" -) - -// GenericResourceService reports any ops services used by any resource - -// +genclient -// +genclient:onlyVerbs=get,list -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type GenericResourceService struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec GenericResourceServiceSpec `json:"spec,omitempty"` - Status *runtime.RawExtension `json:"status,omitempty"` -} - -type GenericResourceServiceSpec struct { - Cluster kmapi.ClusterMetadata `json:"cluster,omitempty"` - APIType kmapi.ResourceID `json:"apiType"` - Name string `json:"name,omitempty"` - Facilities GenericResourceServiceFacilities `json:"facilities,omitempty"` - Status GenericResourceServiceStatus `json:"status"` -} - -type GenericResourceServiceFacilities struct { - Exposed GenericResourceServiceFacilitator `json:"exposed,omitempty"` - TLS GenericResourceServiceFacilitator `json:"tls,omitempty"` - Backup GenericResourceServiceFacilitator `json:"backup,omitempty"` - Monitoring GenericResourceServiceFacilitator `json:"monitoring,omitempty"` - Exec []ExecServiceFacilitator `json:"exec,omitempty"` -} - -type GenericResourceServiceFacilitator struct { - Usage FacilityUsage `json:"usage"` - // +optional - Resource *kmapi.ResourceID `json:"resource,omitempty"` - // +optional - Refs []kmapi.ObjectReference `json:"refs,omitempty"` -} - -type ExecServiceFacilitator struct { - Alias string `json:"alias"` - Resource string `json:"resource"` - Ref kmapi.ObjectReference `json:"ref"` - Container string `json:"container"` - Command []string `json:"command"` - // +optional - KubectlCommand string `json:"kubectlCommand,omitempty"` - // +optional - Help string `json:"help,omitempty"` -} - -type Service struct { - Name string `json:"name"` - shared.ResourceLocator `json:",inline"` -} - -type FacilityUsage string - -const ( - FacilityUsed FacilityUsage = "Used" - FacilityUnused FacilityUsage = "Unused" - FacilityUnknown FacilityUsage = "Unknown" -) - -type GenericResourceServiceStatus struct { - // Status - Status string `json:"status,omitempty"` - // Message - Message string `json:"message,omitempty"` -} - -// GenericResourceServiceList contains a list of GenericResourceService - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type GenericResourceServiceList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []GenericResourceService `json:"items"` -} - -func init() { - SchemeBuilder.Register(&GenericResourceService{}, &GenericResourceServiceList{}) -} diff --git a/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/generic_resource_summary_types.go b/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/generic_resource_summary_types.go deleted file mode 100644 index d4085f536..000000000 --- a/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/generic_resource_summary_types.go +++ /dev/null @@ -1,82 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors. - -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 v1alpha1 - -import ( - kmapi "kmodules.xyz/client-go/api/v1" - - core "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/version" -) - -const ( - ResourceKindResourceSummary = "ResourceSummary" - ResourceResourceSummary = "resourcesummary" - ResourceResourceSummaries = "resourcesummaries" -) - -type ResourceSummarySpec struct { - Cluster kmapi.ClusterMetadata `json:"cluster,omitempty"` - APIType kmapi.ResourceID `json:"apiType"` - TotalResource core.ResourceRequirements `json:"totalResource,omitempty"` - AppResource core.ResourceRequirements `json:"appResource,omitempty"` - Count int `json:"count,omitempty"` -} - -type KubernetesInfo struct { - // https://github.com/kmodules/client-go/blob/master/tools/clusterid/lib.go - ClusterName string `json:"clusterName,omitempty"` - ClusterUID string `json:"clusterUID,omitempty"` - Version *version.Info `json:"version,omitempty"` - ControlPlane *ControlPlaneInfo `json:"controlPlane,omitempty"` -} - -// https://github.com/kmodules/client-go/blob/kubernetes-1.16.3/tools/analytics/analytics.go#L66 -type ControlPlaneInfo struct { - DNSNames []string `json:"dnsNames,omitempty"` - EmailAddresses []string `json:"emailAddresses,omitempty"` - IPAddresses []string `json:"ipAddresses,omitempty"` - URIs []string `json:"uris,omitempty"` - NotBefore metav1.Time `json:"notBefore"` - NotAfter metav1.Time `json:"notAfter"` -} - -// ResourceSummary is the Schema for the ResourceSummary API - -// +genclient -// +genclient:onlyVerbs=get,list -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type ResourceSummary struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec ResourceSummarySpec `json:"spec,omitempty"` -} - -// ResourceSummaryList contains a list of ResourceSummary - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type ResourceSummaryList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []ResourceSummary `json:"items"` -} - -func init() { - SchemeBuilder.Register(&ResourceSummary{}, &ResourceSummaryList{}) -} diff --git a/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/generic_resource_types.go b/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/generic_resource_types.go deleted file mode 100644 index 65d53a196..000000000 --- a/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/generic_resource_types.go +++ /dev/null @@ -1,92 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors. - -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 v1alpha1 - -import ( - kmapi "kmodules.xyz/client-go/api/v1" - "kmodules.xyz/resource-metrics/api" - - core "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" -) - -const ( - ResourceKindGenericResource = "GenericResource" - ResourceGenericResource = "genericresource" - ResourceGenericResources = "genericresources" -) - -// GenericResource is the Schema for any resource supported by resource-metrics library - -// +genclient -// +genclient:onlyVerbs=get,list -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type GenericResource struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec GenericResourceSpec `json:"spec,omitempty"` - Status *runtime.RawExtension `json:"status,omitempty"` -} - -type GenericResourceSpec struct { - // +optional - Cluster kmapi.ClusterMetadata `json:"cluster,omitempty"` - APIType kmapi.ResourceID `json:"apiType"` - Name string `json:"name"` - // +optional - UID types.UID `json:"uid,omitempty"` - // +optional - Version string `json:"version,omitempty"` - // +optional - Replicas int64 `json:"replicas,omitempty"` - // +optional - RoleReplicas api.ReplicaList `json:"roleReplicas,omitempty"` - // +optional - Mode string `json:"mode,omitempty"` - // +optional - TotalResource core.ResourceRequirements `json:"totalResource,omitempty"` - // +optional - AppResource core.ResourceRequirements `json:"appResource,omitempty"` - // +optional - RoleResourceLimits map[api.PodRole]core.ResourceList `json:"roleResourceLimits,omitempty"` - // +optional - RoleResourceRequests map[api.PodRole]core.ResourceList `json:"roleResourceRequests,omitempty"` - Status GenericResourceStatus `json:"status"` -} - -type GenericResourceStatus struct { - // Status - Status string `json:"status,omitempty"` - // Message - Message string `json:"message,omitempty"` -} - -// GenericResourceList contains a list of GenericResource - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type GenericResourceList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []GenericResource `json:"items"` -} - -func init() { - SchemeBuilder.Register(&GenericResource{}, &GenericResourceList{}) -} diff --git a/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/groupversion_info.go b/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/groupversion_info.go deleted file mode 100644 index d49984634..000000000 --- a/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/groupversion_info.go +++ /dev/null @@ -1,35 +0,0 @@ -/* -Copyright 2021. - -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 v1alpha1 - -import ( - "k8s.io/apimachinery/pkg/runtime/schema" - "sigs.k8s.io/controller-runtime/pkg/scheme" -) - -const GroupName = "core.k8s.appscode.com" - -var ( - // SchemeGroupVersion is group version used to register these objects - SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha1"} - - // SchemeBuilder is used to add go types to the GroupVersionKind scheme - SchemeBuilder = &scheme.Builder{GroupVersion: SchemeGroupVersion} - - // AddToScheme adds the types in this group-version to the given scheme. - AddToScheme = SchemeBuilder.AddToScheme -) diff --git a/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/openapi_generated.go b/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/openapi_generated.go deleted file mode 100644 index 9dec2f5b1..000000000 --- a/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/openapi_generated.go +++ /dev/null @@ -1,17656 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright AppsCode Inc. and Contributors - -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. -*/ - -// Code generated by openapi-gen. DO NOT EDIT. - -// This file was autogenerated by openapi-gen. Do not edit it manually! - -package v1alpha1 - -import ( - resource "k8s.io/apimachinery/pkg/api/resource" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - intstr "k8s.io/apimachinery/pkg/util/intstr" - common "k8s.io/kube-openapi/pkg/common" - spec "k8s.io/kube-openapi/pkg/validation/spec" -) - -func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenAPIDefinition { - return map[string]common.OpenAPIDefinition{ - "k8s.io/api/core/v1.AWSElasticBlockStoreVolumeSource": schema_k8sio_api_core_v1_AWSElasticBlockStoreVolumeSource(ref), - "k8s.io/api/core/v1.Affinity": schema_k8sio_api_core_v1_Affinity(ref), - "k8s.io/api/core/v1.AttachedVolume": schema_k8sio_api_core_v1_AttachedVolume(ref), - "k8s.io/api/core/v1.AvoidPods": schema_k8sio_api_core_v1_AvoidPods(ref), - "k8s.io/api/core/v1.AzureDiskVolumeSource": schema_k8sio_api_core_v1_AzureDiskVolumeSource(ref), - "k8s.io/api/core/v1.AzureFilePersistentVolumeSource": schema_k8sio_api_core_v1_AzureFilePersistentVolumeSource(ref), - "k8s.io/api/core/v1.AzureFileVolumeSource": schema_k8sio_api_core_v1_AzureFileVolumeSource(ref), - "k8s.io/api/core/v1.Binding": schema_k8sio_api_core_v1_Binding(ref), - "k8s.io/api/core/v1.CSIPersistentVolumeSource": schema_k8sio_api_core_v1_CSIPersistentVolumeSource(ref), - "k8s.io/api/core/v1.CSIVolumeSource": schema_k8sio_api_core_v1_CSIVolumeSource(ref), - "k8s.io/api/core/v1.Capabilities": schema_k8sio_api_core_v1_Capabilities(ref), - "k8s.io/api/core/v1.CephFSPersistentVolumeSource": schema_k8sio_api_core_v1_CephFSPersistentVolumeSource(ref), - "k8s.io/api/core/v1.CephFSVolumeSource": schema_k8sio_api_core_v1_CephFSVolumeSource(ref), - "k8s.io/api/core/v1.CinderPersistentVolumeSource": schema_k8sio_api_core_v1_CinderPersistentVolumeSource(ref), - "k8s.io/api/core/v1.CinderVolumeSource": schema_k8sio_api_core_v1_CinderVolumeSource(ref), - "k8s.io/api/core/v1.ClaimSource": schema_k8sio_api_core_v1_ClaimSource(ref), - "k8s.io/api/core/v1.ClientIPConfig": schema_k8sio_api_core_v1_ClientIPConfig(ref), - "k8s.io/api/core/v1.ClusterTrustBundleProjection": schema_k8sio_api_core_v1_ClusterTrustBundleProjection(ref), - "k8s.io/api/core/v1.ComponentCondition": schema_k8sio_api_core_v1_ComponentCondition(ref), - "k8s.io/api/core/v1.ComponentStatus": schema_k8sio_api_core_v1_ComponentStatus(ref), - "k8s.io/api/core/v1.ComponentStatusList": schema_k8sio_api_core_v1_ComponentStatusList(ref), - "k8s.io/api/core/v1.ConfigMap": schema_k8sio_api_core_v1_ConfigMap(ref), - "k8s.io/api/core/v1.ConfigMapEnvSource": schema_k8sio_api_core_v1_ConfigMapEnvSource(ref), - "k8s.io/api/core/v1.ConfigMapKeySelector": schema_k8sio_api_core_v1_ConfigMapKeySelector(ref), - "k8s.io/api/core/v1.ConfigMapList": schema_k8sio_api_core_v1_ConfigMapList(ref), - "k8s.io/api/core/v1.ConfigMapNodeConfigSource": schema_k8sio_api_core_v1_ConfigMapNodeConfigSource(ref), - "k8s.io/api/core/v1.ConfigMapProjection": schema_k8sio_api_core_v1_ConfigMapProjection(ref), - "k8s.io/api/core/v1.ConfigMapVolumeSource": schema_k8sio_api_core_v1_ConfigMapVolumeSource(ref), - "k8s.io/api/core/v1.Container": schema_k8sio_api_core_v1_Container(ref), - "k8s.io/api/core/v1.ContainerImage": schema_k8sio_api_core_v1_ContainerImage(ref), - "k8s.io/api/core/v1.ContainerPort": schema_k8sio_api_core_v1_ContainerPort(ref), - "k8s.io/api/core/v1.ContainerResizePolicy": schema_k8sio_api_core_v1_ContainerResizePolicy(ref), - "k8s.io/api/core/v1.ContainerState": schema_k8sio_api_core_v1_ContainerState(ref), - "k8s.io/api/core/v1.ContainerStateRunning": schema_k8sio_api_core_v1_ContainerStateRunning(ref), - "k8s.io/api/core/v1.ContainerStateTerminated": schema_k8sio_api_core_v1_ContainerStateTerminated(ref), - "k8s.io/api/core/v1.ContainerStateWaiting": schema_k8sio_api_core_v1_ContainerStateWaiting(ref), - "k8s.io/api/core/v1.ContainerStatus": schema_k8sio_api_core_v1_ContainerStatus(ref), - "k8s.io/api/core/v1.DaemonEndpoint": schema_k8sio_api_core_v1_DaemonEndpoint(ref), - "k8s.io/api/core/v1.DownwardAPIProjection": schema_k8sio_api_core_v1_DownwardAPIProjection(ref), - "k8s.io/api/core/v1.DownwardAPIVolumeFile": schema_k8sio_api_core_v1_DownwardAPIVolumeFile(ref), - "k8s.io/api/core/v1.DownwardAPIVolumeSource": schema_k8sio_api_core_v1_DownwardAPIVolumeSource(ref), - "k8s.io/api/core/v1.EmptyDirVolumeSource": schema_k8sio_api_core_v1_EmptyDirVolumeSource(ref), - "k8s.io/api/core/v1.EndpointAddress": schema_k8sio_api_core_v1_EndpointAddress(ref), - "k8s.io/api/core/v1.EndpointPort": schema_k8sio_api_core_v1_EndpointPort(ref), - "k8s.io/api/core/v1.EndpointSubset": schema_k8sio_api_core_v1_EndpointSubset(ref), - "k8s.io/api/core/v1.Endpoints": schema_k8sio_api_core_v1_Endpoints(ref), - "k8s.io/api/core/v1.EndpointsList": schema_k8sio_api_core_v1_EndpointsList(ref), - "k8s.io/api/core/v1.EnvFromSource": schema_k8sio_api_core_v1_EnvFromSource(ref), - "k8s.io/api/core/v1.EnvVar": schema_k8sio_api_core_v1_EnvVar(ref), - "k8s.io/api/core/v1.EnvVarSource": schema_k8sio_api_core_v1_EnvVarSource(ref), - "k8s.io/api/core/v1.EphemeralContainer": schema_k8sio_api_core_v1_EphemeralContainer(ref), - "k8s.io/api/core/v1.EphemeralContainerCommon": schema_k8sio_api_core_v1_EphemeralContainerCommon(ref), - "k8s.io/api/core/v1.EphemeralVolumeSource": schema_k8sio_api_core_v1_EphemeralVolumeSource(ref), - "k8s.io/api/core/v1.Event": schema_k8sio_api_core_v1_Event(ref), - "k8s.io/api/core/v1.EventList": schema_k8sio_api_core_v1_EventList(ref), - "k8s.io/api/core/v1.EventSeries": schema_k8sio_api_core_v1_EventSeries(ref), - "k8s.io/api/core/v1.EventSource": schema_k8sio_api_core_v1_EventSource(ref), - "k8s.io/api/core/v1.ExecAction": schema_k8sio_api_core_v1_ExecAction(ref), - "k8s.io/api/core/v1.FCVolumeSource": schema_k8sio_api_core_v1_FCVolumeSource(ref), - "k8s.io/api/core/v1.FlexPersistentVolumeSource": schema_k8sio_api_core_v1_FlexPersistentVolumeSource(ref), - "k8s.io/api/core/v1.FlexVolumeSource": schema_k8sio_api_core_v1_FlexVolumeSource(ref), - "k8s.io/api/core/v1.FlockerVolumeSource": schema_k8sio_api_core_v1_FlockerVolumeSource(ref), - "k8s.io/api/core/v1.GCEPersistentDiskVolumeSource": schema_k8sio_api_core_v1_GCEPersistentDiskVolumeSource(ref), - "k8s.io/api/core/v1.GRPCAction": schema_k8sio_api_core_v1_GRPCAction(ref), - "k8s.io/api/core/v1.GitRepoVolumeSource": schema_k8sio_api_core_v1_GitRepoVolumeSource(ref), - "k8s.io/api/core/v1.GlusterfsPersistentVolumeSource": schema_k8sio_api_core_v1_GlusterfsPersistentVolumeSource(ref), - "k8s.io/api/core/v1.GlusterfsVolumeSource": schema_k8sio_api_core_v1_GlusterfsVolumeSource(ref), - "k8s.io/api/core/v1.HTTPGetAction": schema_k8sio_api_core_v1_HTTPGetAction(ref), - "k8s.io/api/core/v1.HTTPHeader": schema_k8sio_api_core_v1_HTTPHeader(ref), - "k8s.io/api/core/v1.HostAlias": schema_k8sio_api_core_v1_HostAlias(ref), - "k8s.io/api/core/v1.HostIP": schema_k8sio_api_core_v1_HostIP(ref), - "k8s.io/api/core/v1.HostPathVolumeSource": schema_k8sio_api_core_v1_HostPathVolumeSource(ref), - "k8s.io/api/core/v1.ISCSIPersistentVolumeSource": schema_k8sio_api_core_v1_ISCSIPersistentVolumeSource(ref), - "k8s.io/api/core/v1.ISCSIVolumeSource": schema_k8sio_api_core_v1_ISCSIVolumeSource(ref), - "k8s.io/api/core/v1.KeyToPath": schema_k8sio_api_core_v1_KeyToPath(ref), - "k8s.io/api/core/v1.Lifecycle": schema_k8sio_api_core_v1_Lifecycle(ref), - "k8s.io/api/core/v1.LifecycleHandler": schema_k8sio_api_core_v1_LifecycleHandler(ref), - "k8s.io/api/core/v1.LimitRange": schema_k8sio_api_core_v1_LimitRange(ref), - "k8s.io/api/core/v1.LimitRangeItem": schema_k8sio_api_core_v1_LimitRangeItem(ref), - "k8s.io/api/core/v1.LimitRangeList": schema_k8sio_api_core_v1_LimitRangeList(ref), - "k8s.io/api/core/v1.LimitRangeSpec": schema_k8sio_api_core_v1_LimitRangeSpec(ref), - "k8s.io/api/core/v1.List": schema_k8sio_api_core_v1_List(ref), - "k8s.io/api/core/v1.LoadBalancerIngress": schema_k8sio_api_core_v1_LoadBalancerIngress(ref), - "k8s.io/api/core/v1.LoadBalancerStatus": schema_k8sio_api_core_v1_LoadBalancerStatus(ref), - "k8s.io/api/core/v1.LocalObjectReference": schema_k8sio_api_core_v1_LocalObjectReference(ref), - "k8s.io/api/core/v1.LocalVolumeSource": schema_k8sio_api_core_v1_LocalVolumeSource(ref), - "k8s.io/api/core/v1.ModifyVolumeStatus": schema_k8sio_api_core_v1_ModifyVolumeStatus(ref), - "k8s.io/api/core/v1.NFSVolumeSource": schema_k8sio_api_core_v1_NFSVolumeSource(ref), - "k8s.io/api/core/v1.Namespace": schema_k8sio_api_core_v1_Namespace(ref), - "k8s.io/api/core/v1.NamespaceCondition": schema_k8sio_api_core_v1_NamespaceCondition(ref), - "k8s.io/api/core/v1.NamespaceList": schema_k8sio_api_core_v1_NamespaceList(ref), - "k8s.io/api/core/v1.NamespaceSpec": schema_k8sio_api_core_v1_NamespaceSpec(ref), - "k8s.io/api/core/v1.NamespaceStatus": schema_k8sio_api_core_v1_NamespaceStatus(ref), - "k8s.io/api/core/v1.Node": schema_k8sio_api_core_v1_Node(ref), - "k8s.io/api/core/v1.NodeAddress": schema_k8sio_api_core_v1_NodeAddress(ref), - "k8s.io/api/core/v1.NodeAffinity": schema_k8sio_api_core_v1_NodeAffinity(ref), - "k8s.io/api/core/v1.NodeCondition": schema_k8sio_api_core_v1_NodeCondition(ref), - "k8s.io/api/core/v1.NodeConfigSource": schema_k8sio_api_core_v1_NodeConfigSource(ref), - "k8s.io/api/core/v1.NodeConfigStatus": schema_k8sio_api_core_v1_NodeConfigStatus(ref), - "k8s.io/api/core/v1.NodeDaemonEndpoints": schema_k8sio_api_core_v1_NodeDaemonEndpoints(ref), - "k8s.io/api/core/v1.NodeList": schema_k8sio_api_core_v1_NodeList(ref), - "k8s.io/api/core/v1.NodeProxyOptions": schema_k8sio_api_core_v1_NodeProxyOptions(ref), - "k8s.io/api/core/v1.NodeResources": schema_k8sio_api_core_v1_NodeResources(ref), - "k8s.io/api/core/v1.NodeSelector": schema_k8sio_api_core_v1_NodeSelector(ref), - "k8s.io/api/core/v1.NodeSelectorRequirement": schema_k8sio_api_core_v1_NodeSelectorRequirement(ref), - "k8s.io/api/core/v1.NodeSelectorTerm": schema_k8sio_api_core_v1_NodeSelectorTerm(ref), - "k8s.io/api/core/v1.NodeSpec": schema_k8sio_api_core_v1_NodeSpec(ref), - "k8s.io/api/core/v1.NodeStatus": schema_k8sio_api_core_v1_NodeStatus(ref), - "k8s.io/api/core/v1.NodeSystemInfo": schema_k8sio_api_core_v1_NodeSystemInfo(ref), - "k8s.io/api/core/v1.ObjectFieldSelector": schema_k8sio_api_core_v1_ObjectFieldSelector(ref), - "k8s.io/api/core/v1.ObjectReference": schema_k8sio_api_core_v1_ObjectReference(ref), - "k8s.io/api/core/v1.PersistentVolume": schema_k8sio_api_core_v1_PersistentVolume(ref), - "k8s.io/api/core/v1.PersistentVolumeClaim": schema_k8sio_api_core_v1_PersistentVolumeClaim(ref), - "k8s.io/api/core/v1.PersistentVolumeClaimCondition": schema_k8sio_api_core_v1_PersistentVolumeClaimCondition(ref), - "k8s.io/api/core/v1.PersistentVolumeClaimList": schema_k8sio_api_core_v1_PersistentVolumeClaimList(ref), - "k8s.io/api/core/v1.PersistentVolumeClaimSpec": schema_k8sio_api_core_v1_PersistentVolumeClaimSpec(ref), - "k8s.io/api/core/v1.PersistentVolumeClaimStatus": schema_k8sio_api_core_v1_PersistentVolumeClaimStatus(ref), - "k8s.io/api/core/v1.PersistentVolumeClaimTemplate": schema_k8sio_api_core_v1_PersistentVolumeClaimTemplate(ref), - "k8s.io/api/core/v1.PersistentVolumeClaimVolumeSource": schema_k8sio_api_core_v1_PersistentVolumeClaimVolumeSource(ref), - "k8s.io/api/core/v1.PersistentVolumeList": schema_k8sio_api_core_v1_PersistentVolumeList(ref), - "k8s.io/api/core/v1.PersistentVolumeSource": schema_k8sio_api_core_v1_PersistentVolumeSource(ref), - "k8s.io/api/core/v1.PersistentVolumeSpec": schema_k8sio_api_core_v1_PersistentVolumeSpec(ref), - "k8s.io/api/core/v1.PersistentVolumeStatus": schema_k8sio_api_core_v1_PersistentVolumeStatus(ref), - "k8s.io/api/core/v1.PhotonPersistentDiskVolumeSource": schema_k8sio_api_core_v1_PhotonPersistentDiskVolumeSource(ref), - "k8s.io/api/core/v1.Pod": schema_k8sio_api_core_v1_Pod(ref), - "k8s.io/api/core/v1.PodAffinity": schema_k8sio_api_core_v1_PodAffinity(ref), - "k8s.io/api/core/v1.PodAffinityTerm": schema_k8sio_api_core_v1_PodAffinityTerm(ref), - "k8s.io/api/core/v1.PodAntiAffinity": schema_k8sio_api_core_v1_PodAntiAffinity(ref), - "k8s.io/api/core/v1.PodAttachOptions": schema_k8sio_api_core_v1_PodAttachOptions(ref), - "k8s.io/api/core/v1.PodCondition": schema_k8sio_api_core_v1_PodCondition(ref), - "k8s.io/api/core/v1.PodDNSConfig": schema_k8sio_api_core_v1_PodDNSConfig(ref), - "k8s.io/api/core/v1.PodDNSConfigOption": schema_k8sio_api_core_v1_PodDNSConfigOption(ref), - "k8s.io/api/core/v1.PodExecOptions": schema_k8sio_api_core_v1_PodExecOptions(ref), - "k8s.io/api/core/v1.PodIP": schema_k8sio_api_core_v1_PodIP(ref), - "k8s.io/api/core/v1.PodList": schema_k8sio_api_core_v1_PodList(ref), - "k8s.io/api/core/v1.PodLogOptions": schema_k8sio_api_core_v1_PodLogOptions(ref), - "k8s.io/api/core/v1.PodOS": schema_k8sio_api_core_v1_PodOS(ref), - "k8s.io/api/core/v1.PodPortForwardOptions": schema_k8sio_api_core_v1_PodPortForwardOptions(ref), - "k8s.io/api/core/v1.PodProxyOptions": schema_k8sio_api_core_v1_PodProxyOptions(ref), - "k8s.io/api/core/v1.PodReadinessGate": schema_k8sio_api_core_v1_PodReadinessGate(ref), - "k8s.io/api/core/v1.PodResourceClaim": schema_k8sio_api_core_v1_PodResourceClaim(ref), - "k8s.io/api/core/v1.PodResourceClaimStatus": schema_k8sio_api_core_v1_PodResourceClaimStatus(ref), - "k8s.io/api/core/v1.PodSchedulingGate": schema_k8sio_api_core_v1_PodSchedulingGate(ref), - "k8s.io/api/core/v1.PodSecurityContext": schema_k8sio_api_core_v1_PodSecurityContext(ref), - "k8s.io/api/core/v1.PodSignature": schema_k8sio_api_core_v1_PodSignature(ref), - "k8s.io/api/core/v1.PodSpec": schema_k8sio_api_core_v1_PodSpec(ref), - "k8s.io/api/core/v1.PodStatus": schema_k8sio_api_core_v1_PodStatus(ref), - "k8s.io/api/core/v1.PodStatusResult": schema_k8sio_api_core_v1_PodStatusResult(ref), - "k8s.io/api/core/v1.PodTemplate": schema_k8sio_api_core_v1_PodTemplate(ref), - "k8s.io/api/core/v1.PodTemplateList": schema_k8sio_api_core_v1_PodTemplateList(ref), - "k8s.io/api/core/v1.PodTemplateSpec": schema_k8sio_api_core_v1_PodTemplateSpec(ref), - "k8s.io/api/core/v1.PortStatus": schema_k8sio_api_core_v1_PortStatus(ref), - "k8s.io/api/core/v1.PortworxVolumeSource": schema_k8sio_api_core_v1_PortworxVolumeSource(ref), - "k8s.io/api/core/v1.PreferAvoidPodsEntry": schema_k8sio_api_core_v1_PreferAvoidPodsEntry(ref), - "k8s.io/api/core/v1.PreferredSchedulingTerm": schema_k8sio_api_core_v1_PreferredSchedulingTerm(ref), - "k8s.io/api/core/v1.Probe": schema_k8sio_api_core_v1_Probe(ref), - "k8s.io/api/core/v1.ProbeHandler": schema_k8sio_api_core_v1_ProbeHandler(ref), - "k8s.io/api/core/v1.ProjectedVolumeSource": schema_k8sio_api_core_v1_ProjectedVolumeSource(ref), - "k8s.io/api/core/v1.QuobyteVolumeSource": schema_k8sio_api_core_v1_QuobyteVolumeSource(ref), - "k8s.io/api/core/v1.RBDPersistentVolumeSource": schema_k8sio_api_core_v1_RBDPersistentVolumeSource(ref), - "k8s.io/api/core/v1.RBDVolumeSource": schema_k8sio_api_core_v1_RBDVolumeSource(ref), - "k8s.io/api/core/v1.RangeAllocation": schema_k8sio_api_core_v1_RangeAllocation(ref), - "k8s.io/api/core/v1.ReplicationController": schema_k8sio_api_core_v1_ReplicationController(ref), - "k8s.io/api/core/v1.ReplicationControllerCondition": schema_k8sio_api_core_v1_ReplicationControllerCondition(ref), - "k8s.io/api/core/v1.ReplicationControllerList": schema_k8sio_api_core_v1_ReplicationControllerList(ref), - "k8s.io/api/core/v1.ReplicationControllerSpec": schema_k8sio_api_core_v1_ReplicationControllerSpec(ref), - "k8s.io/api/core/v1.ReplicationControllerStatus": schema_k8sio_api_core_v1_ReplicationControllerStatus(ref), - "k8s.io/api/core/v1.ResourceClaim": schema_k8sio_api_core_v1_ResourceClaim(ref), - "k8s.io/api/core/v1.ResourceFieldSelector": schema_k8sio_api_core_v1_ResourceFieldSelector(ref), - "k8s.io/api/core/v1.ResourceQuota": schema_k8sio_api_core_v1_ResourceQuota(ref), - "k8s.io/api/core/v1.ResourceQuotaList": schema_k8sio_api_core_v1_ResourceQuotaList(ref), - "k8s.io/api/core/v1.ResourceQuotaSpec": schema_k8sio_api_core_v1_ResourceQuotaSpec(ref), - "k8s.io/api/core/v1.ResourceQuotaStatus": schema_k8sio_api_core_v1_ResourceQuotaStatus(ref), - "k8s.io/api/core/v1.ResourceRequirements": schema_k8sio_api_core_v1_ResourceRequirements(ref), - "k8s.io/api/core/v1.SELinuxOptions": schema_k8sio_api_core_v1_SELinuxOptions(ref), - "k8s.io/api/core/v1.ScaleIOPersistentVolumeSource": schema_k8sio_api_core_v1_ScaleIOPersistentVolumeSource(ref), - "k8s.io/api/core/v1.ScaleIOVolumeSource": schema_k8sio_api_core_v1_ScaleIOVolumeSource(ref), - "k8s.io/api/core/v1.ScopeSelector": schema_k8sio_api_core_v1_ScopeSelector(ref), - "k8s.io/api/core/v1.ScopedResourceSelectorRequirement": schema_k8sio_api_core_v1_ScopedResourceSelectorRequirement(ref), - "k8s.io/api/core/v1.SeccompProfile": schema_k8sio_api_core_v1_SeccompProfile(ref), - "k8s.io/api/core/v1.Secret": schema_k8sio_api_core_v1_Secret(ref), - "k8s.io/api/core/v1.SecretEnvSource": schema_k8sio_api_core_v1_SecretEnvSource(ref), - "k8s.io/api/core/v1.SecretKeySelector": schema_k8sio_api_core_v1_SecretKeySelector(ref), - "k8s.io/api/core/v1.SecretList": schema_k8sio_api_core_v1_SecretList(ref), - "k8s.io/api/core/v1.SecretProjection": schema_k8sio_api_core_v1_SecretProjection(ref), - "k8s.io/api/core/v1.SecretReference": schema_k8sio_api_core_v1_SecretReference(ref), - "k8s.io/api/core/v1.SecretVolumeSource": schema_k8sio_api_core_v1_SecretVolumeSource(ref), - "k8s.io/api/core/v1.SecurityContext": schema_k8sio_api_core_v1_SecurityContext(ref), - "k8s.io/api/core/v1.SerializedReference": schema_k8sio_api_core_v1_SerializedReference(ref), - "k8s.io/api/core/v1.Service": schema_k8sio_api_core_v1_Service(ref), - "k8s.io/api/core/v1.ServiceAccount": schema_k8sio_api_core_v1_ServiceAccount(ref), - "k8s.io/api/core/v1.ServiceAccountList": schema_k8sio_api_core_v1_ServiceAccountList(ref), - "k8s.io/api/core/v1.ServiceAccountTokenProjection": schema_k8sio_api_core_v1_ServiceAccountTokenProjection(ref), - "k8s.io/api/core/v1.ServiceList": schema_k8sio_api_core_v1_ServiceList(ref), - "k8s.io/api/core/v1.ServicePort": schema_k8sio_api_core_v1_ServicePort(ref), - "k8s.io/api/core/v1.ServiceProxyOptions": schema_k8sio_api_core_v1_ServiceProxyOptions(ref), - "k8s.io/api/core/v1.ServiceSpec": schema_k8sio_api_core_v1_ServiceSpec(ref), - "k8s.io/api/core/v1.ServiceStatus": schema_k8sio_api_core_v1_ServiceStatus(ref), - "k8s.io/api/core/v1.SessionAffinityConfig": schema_k8sio_api_core_v1_SessionAffinityConfig(ref), - "k8s.io/api/core/v1.SleepAction": schema_k8sio_api_core_v1_SleepAction(ref), - "k8s.io/api/core/v1.StorageOSPersistentVolumeSource": schema_k8sio_api_core_v1_StorageOSPersistentVolumeSource(ref), - "k8s.io/api/core/v1.StorageOSVolumeSource": schema_k8sio_api_core_v1_StorageOSVolumeSource(ref), - "k8s.io/api/core/v1.Sysctl": schema_k8sio_api_core_v1_Sysctl(ref), - "k8s.io/api/core/v1.TCPSocketAction": schema_k8sio_api_core_v1_TCPSocketAction(ref), - "k8s.io/api/core/v1.Taint": schema_k8sio_api_core_v1_Taint(ref), - "k8s.io/api/core/v1.Toleration": schema_k8sio_api_core_v1_Toleration(ref), - "k8s.io/api/core/v1.TopologySelectorLabelRequirement": schema_k8sio_api_core_v1_TopologySelectorLabelRequirement(ref), - "k8s.io/api/core/v1.TopologySelectorTerm": schema_k8sio_api_core_v1_TopologySelectorTerm(ref), - "k8s.io/api/core/v1.TopologySpreadConstraint": schema_k8sio_api_core_v1_TopologySpreadConstraint(ref), - "k8s.io/api/core/v1.TypedLocalObjectReference": schema_k8sio_api_core_v1_TypedLocalObjectReference(ref), - "k8s.io/api/core/v1.TypedObjectReference": schema_k8sio_api_core_v1_TypedObjectReference(ref), - "k8s.io/api/core/v1.Volume": schema_k8sio_api_core_v1_Volume(ref), - "k8s.io/api/core/v1.VolumeDevice": schema_k8sio_api_core_v1_VolumeDevice(ref), - "k8s.io/api/core/v1.VolumeMount": schema_k8sio_api_core_v1_VolumeMount(ref), - "k8s.io/api/core/v1.VolumeNodeAffinity": schema_k8sio_api_core_v1_VolumeNodeAffinity(ref), - "k8s.io/api/core/v1.VolumeProjection": schema_k8sio_api_core_v1_VolumeProjection(ref), - "k8s.io/api/core/v1.VolumeResourceRequirements": schema_k8sio_api_core_v1_VolumeResourceRequirements(ref), - "k8s.io/api/core/v1.VolumeSource": schema_k8sio_api_core_v1_VolumeSource(ref), - "k8s.io/api/core/v1.VsphereVirtualDiskVolumeSource": schema_k8sio_api_core_v1_VsphereVirtualDiskVolumeSource(ref), - "k8s.io/api/core/v1.WeightedPodAffinityTerm": schema_k8sio_api_core_v1_WeightedPodAffinityTerm(ref), - "k8s.io/api/core/v1.WindowsSecurityContextOptions": schema_k8sio_api_core_v1_WindowsSecurityContextOptions(ref), - "k8s.io/apimachinery/pkg/api/resource.Quantity": schema_apimachinery_pkg_api_resource_Quantity(ref), - "k8s.io/apimachinery/pkg/api/resource.int64Amount": schema_apimachinery_pkg_api_resource_int64Amount(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.APIGroup": schema_pkg_apis_meta_v1_APIGroup(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.APIGroupList": schema_pkg_apis_meta_v1_APIGroupList(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.APIResource": schema_pkg_apis_meta_v1_APIResource(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.APIResourceList": schema_pkg_apis_meta_v1_APIResourceList(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.APIVersions": schema_pkg_apis_meta_v1_APIVersions(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.ApplyOptions": schema_pkg_apis_meta_v1_ApplyOptions(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.Condition": schema_pkg_apis_meta_v1_Condition(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.CreateOptions": schema_pkg_apis_meta_v1_CreateOptions(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.DeleteOptions": schema_pkg_apis_meta_v1_DeleteOptions(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.Duration": schema_pkg_apis_meta_v1_Duration(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.FieldsV1": schema_pkg_apis_meta_v1_FieldsV1(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.GetOptions": schema_pkg_apis_meta_v1_GetOptions(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.GroupKind": schema_pkg_apis_meta_v1_GroupKind(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.GroupResource": schema_pkg_apis_meta_v1_GroupResource(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.GroupVersion": schema_pkg_apis_meta_v1_GroupVersion(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.GroupVersionForDiscovery": schema_pkg_apis_meta_v1_GroupVersionForDiscovery(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.GroupVersionKind": schema_pkg_apis_meta_v1_GroupVersionKind(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.GroupVersionResource": schema_pkg_apis_meta_v1_GroupVersionResource(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.InternalEvent": schema_pkg_apis_meta_v1_InternalEvent(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector": schema_pkg_apis_meta_v1_LabelSelector(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelectorRequirement": schema_pkg_apis_meta_v1_LabelSelectorRequirement(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.List": schema_pkg_apis_meta_v1_List(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta": schema_pkg_apis_meta_v1_ListMeta(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.ListOptions": schema_pkg_apis_meta_v1_ListOptions(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.ManagedFieldsEntry": schema_pkg_apis_meta_v1_ManagedFieldsEntry(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.MicroTime": schema_pkg_apis_meta_v1_MicroTime(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta": schema_pkg_apis_meta_v1_ObjectMeta(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.OwnerReference": schema_pkg_apis_meta_v1_OwnerReference(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.PartialObjectMetadata": schema_pkg_apis_meta_v1_PartialObjectMetadata(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.PartialObjectMetadataList": schema_pkg_apis_meta_v1_PartialObjectMetadataList(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.Patch": schema_pkg_apis_meta_v1_Patch(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.PatchOptions": schema_pkg_apis_meta_v1_PatchOptions(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.Preconditions": schema_pkg_apis_meta_v1_Preconditions(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.RootPaths": schema_pkg_apis_meta_v1_RootPaths(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.ServerAddressByClientCIDR": schema_pkg_apis_meta_v1_ServerAddressByClientCIDR(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.Status": schema_pkg_apis_meta_v1_Status(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.StatusCause": schema_pkg_apis_meta_v1_StatusCause(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.StatusDetails": schema_pkg_apis_meta_v1_StatusDetails(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.Table": schema_pkg_apis_meta_v1_Table(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.TableColumnDefinition": schema_pkg_apis_meta_v1_TableColumnDefinition(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.TableOptions": schema_pkg_apis_meta_v1_TableOptions(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.TableRow": schema_pkg_apis_meta_v1_TableRow(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.TableRowCondition": schema_pkg_apis_meta_v1_TableRowCondition(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.Time": schema_pkg_apis_meta_v1_Time(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.Timestamp": schema_pkg_apis_meta_v1_Timestamp(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.TypeMeta": schema_pkg_apis_meta_v1_TypeMeta(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.UpdateOptions": schema_pkg_apis_meta_v1_UpdateOptions(ref), - "k8s.io/apimachinery/pkg/apis/meta/v1.WatchEvent": schema_pkg_apis_meta_v1_WatchEvent(ref), - "k8s.io/apimachinery/pkg/runtime.RawExtension": schema_k8sio_apimachinery_pkg_runtime_RawExtension(ref), - "k8s.io/apimachinery/pkg/runtime.TypeMeta": schema_k8sio_apimachinery_pkg_runtime_TypeMeta(ref), - "k8s.io/apimachinery/pkg/runtime.Unknown": schema_k8sio_apimachinery_pkg_runtime_Unknown(ref), - "k8s.io/apimachinery/pkg/util/intstr.IntOrString": schema_apimachinery_pkg_util_intstr_IntOrString(ref), - "k8s.io/apimachinery/pkg/version.Info": schema_k8sio_apimachinery_pkg_version_Info(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.ContainerView": schema_resource_metadata_apis_core_v1alpha1_ContainerView(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.ControlPlaneInfo": schema_resource_metadata_apis_core_v1alpha1_ControlPlaneInfo(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.ExecServiceFacilitator": schema_resource_metadata_apis_core_v1alpha1_ExecServiceFacilitator(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResource": schema_resource_metadata_apis_core_v1alpha1_GenericResource(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceList": schema_resource_metadata_apis_core_v1alpha1_GenericResourceList(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceService": schema_resource_metadata_apis_core_v1alpha1_GenericResourceService(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceServiceFacilitator": schema_resource_metadata_apis_core_v1alpha1_GenericResourceServiceFacilitator(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceServiceFacilities": schema_resource_metadata_apis_core_v1alpha1_GenericResourceServiceFacilities(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceServiceList": schema_resource_metadata_apis_core_v1alpha1_GenericResourceServiceList(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceServiceSpec": schema_resource_metadata_apis_core_v1alpha1_GenericResourceServiceSpec(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceServiceStatus": schema_resource_metadata_apis_core_v1alpha1_GenericResourceServiceStatus(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceSpec": schema_resource_metadata_apis_core_v1alpha1_GenericResourceSpec(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceStatus": schema_resource_metadata_apis_core_v1alpha1_GenericResourceStatus(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.KubernetesInfo": schema_resource_metadata_apis_core_v1alpha1_KubernetesInfo(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.PodView": schema_resource_metadata_apis_core_v1alpha1_PodView(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.PodViewList": schema_resource_metadata_apis_core_v1alpha1_PodViewList(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.PodViewSpec": schema_resource_metadata_apis_core_v1alpha1_PodViewSpec(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.Project": schema_resource_metadata_apis_core_v1alpha1_Project(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.ProjectList": schema_resource_metadata_apis_core_v1alpha1_ProjectList(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.ProjectMonitoring": schema_resource_metadata_apis_core_v1alpha1_ProjectMonitoring(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.ProjectSpec": schema_resource_metadata_apis_core_v1alpha1_ProjectSpec(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.ResourceSummary": schema_resource_metadata_apis_core_v1alpha1_ResourceSummary(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.ResourceSummaryList": schema_resource_metadata_apis_core_v1alpha1_ResourceSummaryList(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.ResourceSummarySpec": schema_resource_metadata_apis_core_v1alpha1_ResourceSummarySpec(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.ResourceView": schema_resource_metadata_apis_core_v1alpha1_ResourceView(ref), - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.Service": schema_resource_metadata_apis_core_v1alpha1_Service(ref), - "kmodules.xyz/resource-metadata/apis/shared.Action": schema_kmodulesxyz_resource_metadata_apis_shared_Action(ref), - "kmodules.xyz/resource-metadata/apis/shared.ActionGroup": schema_kmodulesxyz_resource_metadata_apis_shared_ActionGroup(ref), - "kmodules.xyz/resource-metadata/apis/shared.ActionInfo": schema_kmodulesxyz_resource_metadata_apis_shared_ActionInfo(ref), - "kmodules.xyz/resource-metadata/apis/shared.ActionTemplate": schema_kmodulesxyz_resource_metadata_apis_shared_ActionTemplate(ref), - "kmodules.xyz/resource-metadata/apis/shared.ActionTemplateGroup": schema_kmodulesxyz_resource_metadata_apis_shared_ActionTemplateGroup(ref), - "kmodules.xyz/resource-metadata/apis/shared.BootstrapPresets": schema_kmodulesxyz_resource_metadata_apis_shared_BootstrapPresets(ref), - "kmodules.xyz/resource-metadata/apis/shared.Dashboard": schema_kmodulesxyz_resource_metadata_apis_shared_Dashboard(ref), - "kmodules.xyz/resource-metadata/apis/shared.DashboardVar": schema_kmodulesxyz_resource_metadata_apis_shared_DashboardVar(ref), - "kmodules.xyz/resource-metadata/apis/shared.DeploymentParameters": schema_kmodulesxyz_resource_metadata_apis_shared_DeploymentParameters(ref), - "kmodules.xyz/resource-metadata/apis/shared.HelmInfo": schema_kmodulesxyz_resource_metadata_apis_shared_HelmInfo(ref), - "kmodules.xyz/resource-metadata/apis/shared.HelmRelease": schema_kmodulesxyz_resource_metadata_apis_shared_HelmRelease(ref), - "kmodules.xyz/resource-metadata/apis/shared.HelmRepository": schema_kmodulesxyz_resource_metadata_apis_shared_HelmRepository(ref), - "kmodules.xyz/resource-metadata/apis/shared.If": schema_kmodulesxyz_resource_metadata_apis_shared_If(ref), - "kmodules.xyz/resource-metadata/apis/shared.ImageRegistrySpec": schema_kmodulesxyz_resource_metadata_apis_shared_ImageRegistrySpec(ref), - "kmodules.xyz/resource-metadata/apis/shared.RegistryInfo": schema_kmodulesxyz_resource_metadata_apis_shared_RegistryInfo(ref), - "kmodules.xyz/resource-metadata/apis/shared.RegistryProxies": schema_kmodulesxyz_resource_metadata_apis_shared_RegistryProxies(ref), - "kmodules.xyz/resource-metadata/apis/shared.ResourceLocator": schema_kmodulesxyz_resource_metadata_apis_shared_ResourceLocator(ref), - "kmodules.xyz/resource-metadata/apis/shared.ResourceQuery": schema_kmodulesxyz_resource_metadata_apis_shared_ResourceQuery(ref), - "kmodules.xyz/resource-metadata/apis/shared.SourceLocator": schema_kmodulesxyz_resource_metadata_apis_shared_SourceLocator(ref), - "kmodules.xyz/resource-metadata/apis/shared.UIParameterTemplate": schema_kmodulesxyz_resource_metadata_apis_shared_UIParameterTemplate(ref), - "kmodules.xyz/resource-metadata/apis/shared.UIParameters": schema_kmodulesxyz_resource_metadata_apis_shared_UIParameters(ref), - } -} - -func schema_k8sio_api_core_v1_AWSElasticBlockStoreVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Persistent Disk resource in AWS.\n\nAn AWS EBS disk must exist before mounting to a container. The disk must also be in the same AWS zone as the kubelet. An AWS EBS disk can only be mounted as read/write once. AWS EBS volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "volumeID": { - SchemaProps: spec.SchemaProps{ - Description: "volumeID is unique ID of the persistent disk resource in AWS (Amazon EBS volume). More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore", - Type: []string{"string"}, - Format: "", - }, - }, - "partition": { - SchemaProps: spec.SchemaProps{ - Description: "partition is the partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as \"1\". Similarly, the volume partition for /dev/sda is \"0\" (or you can leave the property empty).", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly value true will force the readOnly setting in VolumeMounts. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"volumeID"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_Affinity(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Affinity is a group of affinity scheduling rules.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "nodeAffinity": { - SchemaProps: spec.SchemaProps{ - Description: "Describes node affinity scheduling rules for the pod.", - Ref: ref("k8s.io/api/core/v1.NodeAffinity"), - }, - }, - "podAffinity": { - SchemaProps: spec.SchemaProps{ - Description: "Describes pod affinity scheduling rules (e.g. co-locate this pod in the same node, zone, etc. as some other pod(s)).", - Ref: ref("k8s.io/api/core/v1.PodAffinity"), - }, - }, - "podAntiAffinity": { - SchemaProps: spec.SchemaProps{ - Description: "Describes pod anti-affinity scheduling rules (e.g. avoid putting this pod in the same node, zone, etc. as some other pod(s)).", - Ref: ref("k8s.io/api/core/v1.PodAntiAffinity"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NodeAffinity", "k8s.io/api/core/v1.PodAffinity", "k8s.io/api/core/v1.PodAntiAffinity"}, - } -} - -func schema_k8sio_api_core_v1_AttachedVolume(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "AttachedVolume describes a volume attached to a node", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the attached volume", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "devicePath": { - SchemaProps: spec.SchemaProps{ - Description: "DevicePath represents the device path where the volume should be available", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name", "devicePath"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_AvoidPods(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "AvoidPods describes pods that should avoid this node. This is the value for a Node annotation with key scheduler.alpha.kubernetes.io/preferAvoidPods and will eventually become a field of NodeStatus.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "preferAvoidPods": { - SchemaProps: spec.SchemaProps{ - Description: "Bounded-sized list of signatures of pods that should avoid this node, sorted in timestamp order from oldest to newest. Size of the slice is unspecified.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PreferAvoidPodsEntry"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PreferAvoidPodsEntry"}, - } -} - -func schema_k8sio_api_core_v1_AzureDiskVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "AzureDisk represents an Azure Data Disk mount on the host and bind mount to the pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "diskName": { - SchemaProps: spec.SchemaProps{ - Description: "diskName is the Name of the data disk in the blob storage", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "diskURI": { - SchemaProps: spec.SchemaProps{ - Description: "diskURI is the URI of data disk in the blob storage", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "cachingMode": { - SchemaProps: spec.SchemaProps{ - Description: "cachingMode is the Host Caching mode: None, Read Only, Read Write.\n\nPossible enum values:\n - `\"None\"`\n - `\"ReadOnly\"`\n - `\"ReadWrite\"`", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"None", "ReadOnly", "ReadWrite"}, - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "kind expected values are Shared: multiple blob disks per storage account Dedicated: single blob disk per storage account Managed: azure managed data disk (only in managed availability set). defaults to shared\n\nPossible enum values:\n - `\"Dedicated\"`\n - `\"Managed\"`\n - `\"Shared\"`", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Dedicated", "Managed", "Shared"}, - }, - }, - }, - Required: []string{"diskName", "diskURI"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_AzureFilePersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "AzureFile represents an Azure File Service mount on the host and bind mount to the pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "secretName": { - SchemaProps: spec.SchemaProps{ - Description: "secretName is the name of secret that contains Azure Storage Account Name and Key", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "shareName": { - SchemaProps: spec.SchemaProps{ - Description: "shareName is the azure Share Name", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "secretNamespace": { - SchemaProps: spec.SchemaProps{ - Description: "secretNamespace is the namespace of the secret that contains Azure Storage Account Name and Key default is the same as the Pod", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"secretName", "shareName"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_AzureFileVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "AzureFile represents an Azure File Service mount on the host and bind mount to the pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "secretName": { - SchemaProps: spec.SchemaProps{ - Description: "secretName is the name of secret that contains Azure Storage Account Name and Key", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "shareName": { - SchemaProps: spec.SchemaProps{ - Description: "shareName is the azure share Name", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"secretName", "shareName"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_Binding(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Binding ties one object to another; for example, a pod is bound to a node by a scheduler. Deprecated in 1.7, please use the bindings subresource of pods instead.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "target": { - SchemaProps: spec.SchemaProps{ - Description: "The target object that you want to bind to the standard object.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ObjectReference"), - }, - }, - }, - Required: []string{"target"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ObjectReference", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_CSIPersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents storage that is managed by an external CSI volume driver (Beta feature)", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "driver": { - SchemaProps: spec.SchemaProps{ - Description: "driver is the name of the driver to use for this volume. Required.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeHandle": { - SchemaProps: spec.SchemaProps{ - Description: "volumeHandle is the unique volume name returned by the CSI volume plugin’s CreateVolume to refer to the volume on all subsequent calls. Required.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly value to pass to ControllerPublishVolumeRequest. Defaults to false (read/write).", - Type: []string{"boolean"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\".", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeAttributes": { - SchemaProps: spec.SchemaProps{ - Description: "volumeAttributes of the volume to publish.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "controllerPublishSecretRef": { - SchemaProps: spec.SchemaProps{ - Description: "controllerPublishSecretRef is a reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI ControllerPublishVolume and ControllerUnpublishVolume calls. This field is optional, and may be empty if no secret is required. If the secret object contains more than one secret, all secrets are passed.", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - "nodeStageSecretRef": { - SchemaProps: spec.SchemaProps{ - Description: "nodeStageSecretRef is a reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI NodeStageVolume and NodeStageVolume and NodeUnstageVolume calls. This field is optional, and may be empty if no secret is required. If the secret object contains more than one secret, all secrets are passed.", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - "nodePublishSecretRef": { - SchemaProps: spec.SchemaProps{ - Description: "nodePublishSecretRef is a reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI NodePublishVolume and NodeUnpublishVolume calls. This field is optional, and may be empty if no secret is required. If the secret object contains more than one secret, all secrets are passed.", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - "controllerExpandSecretRef": { - SchemaProps: spec.SchemaProps{ - Description: "controllerExpandSecretRef is a reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI ControllerExpandVolume call. This field is optional, and may be empty if no secret is required. If the secret object contains more than one secret, all secrets are passed.", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - "nodeExpandSecretRef": { - SchemaProps: spec.SchemaProps{ - Description: "nodeExpandSecretRef is a reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI NodeExpandVolume call. This field is optional, may be omitted if no secret is required. If the secret object contains more than one secret, all secrets are passed.", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - }, - Required: []string{"driver", "volumeHandle"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.SecretReference"}, - } -} - -func schema_k8sio_api_core_v1_CSIVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a source location of a volume to mount, managed by an external CSI driver", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "driver": { - SchemaProps: spec.SchemaProps{ - Description: "driver is the name of the CSI driver that handles this volume. Consult with your admin for the correct name as registered in the cluster.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly specifies a read-only configuration for the volume. Defaults to false (read/write).", - Type: []string{"boolean"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType to mount. Ex. \"ext4\", \"xfs\", \"ntfs\". If not provided, the empty value is passed to the associated CSI driver which will determine the default filesystem to apply.", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeAttributes": { - SchemaProps: spec.SchemaProps{ - Description: "volumeAttributes stores driver-specific properties that are passed to the CSI driver. Consult your driver's documentation for supported values.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "nodePublishSecretRef": { - SchemaProps: spec.SchemaProps{ - Description: "nodePublishSecretRef is a reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI NodePublishVolume and NodeUnpublishVolume calls. This field is optional, and may be empty if no secret is required. If the secret object contains more than one secret, all secret references are passed.", - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - }, - Required: []string{"driver"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LocalObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_Capabilities(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Adds and removes POSIX capabilities from running containers.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "add": { - SchemaProps: spec.SchemaProps{ - Description: "Added capabilities", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "drop": { - SchemaProps: spec.SchemaProps{ - Description: "Removed capabilities", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_CephFSPersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Ceph Filesystem mount that lasts the lifetime of a pod Cephfs volumes do not support ownership management or SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "monitors": { - SchemaProps: spec.SchemaProps{ - Description: "monitors is Required: Monitors is a collection of Ceph monitors More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "path is Optional: Used as the mounted root, rather than the full Ceph tree, default is /", - Type: []string{"string"}, - Format: "", - }, - }, - "user": { - SchemaProps: spec.SchemaProps{ - Description: "user is Optional: User is the rados user name, default is admin More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - Type: []string{"string"}, - Format: "", - }, - }, - "secretFile": { - SchemaProps: spec.SchemaProps{ - Description: "secretFile is Optional: SecretFile is the path to key ring for User, default is /etc/ceph/user.secret More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - Type: []string{"string"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef is Optional: SecretRef is reference to the authentication secret for User, default is empty. More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly is Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"monitors"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.SecretReference"}, - } -} - -func schema_k8sio_api_core_v1_CephFSVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Ceph Filesystem mount that lasts the lifetime of a pod Cephfs volumes do not support ownership management or SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "monitors": { - SchemaProps: spec.SchemaProps{ - Description: "monitors is Required: Monitors is a collection of Ceph monitors More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "path is Optional: Used as the mounted root, rather than the full Ceph tree, default is /", - Type: []string{"string"}, - Format: "", - }, - }, - "user": { - SchemaProps: spec.SchemaProps{ - Description: "user is optional: User is the rados user name, default is admin More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - Type: []string{"string"}, - Format: "", - }, - }, - "secretFile": { - SchemaProps: spec.SchemaProps{ - Description: "secretFile is Optional: SecretFile is the path to key ring for User, default is /etc/ceph/user.secret More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - Type: []string{"string"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef is Optional: SecretRef is reference to the authentication secret for User, default is empty. More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly is Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"monitors"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LocalObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_CinderPersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a cinder volume resource in Openstack. A Cinder volume must exist before mounting to a container. The volume must also be in the same region as the kubelet. Cinder volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "volumeID": { - SchemaProps: spec.SchemaProps{ - Description: "volumeID used to identify the volume in cinder. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType Filesystem type to mount. Must be a filesystem type supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly is Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - Type: []string{"boolean"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef is Optional: points to a secret object containing parameters used to connect to OpenStack.", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - }, - Required: []string{"volumeID"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.SecretReference"}, - } -} - -func schema_k8sio_api_core_v1_CinderVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a cinder volume resource in Openstack. A Cinder volume must exist before mounting to a container. The volume must also be in the same region as the kubelet. Cinder volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "volumeID": { - SchemaProps: spec.SchemaProps{ - Description: "volumeID used to identify the volume in cinder. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - Type: []string{"boolean"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef is optional: points to a secret object containing parameters used to connect to OpenStack.", - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - }, - Required: []string{"volumeID"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LocalObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_ClaimSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ClaimSource describes a reference to a ResourceClaim.\n\nExactly one of these fields should be set. Consumers of this type must treat an empty object as if it has an unknown value.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "resourceClaimName": { - SchemaProps: spec.SchemaProps{ - Description: "ResourceClaimName is the name of a ResourceClaim object in the same namespace as this pod.", - Type: []string{"string"}, - Format: "", - }, - }, - "resourceClaimTemplateName": { - SchemaProps: spec.SchemaProps{ - Description: "ResourceClaimTemplateName is the name of a ResourceClaimTemplate object in the same namespace as this pod.\n\nThe template will be used to create a new ResourceClaim, which will be bound to this pod. When this pod is deleted, the ResourceClaim will also be deleted. The pod name and resource name, along with a generated component, will be used to form a unique name for the ResourceClaim, which will be recorded in pod.status.resourceClaimStatuses.\n\nThis field is immutable and no changes will be made to the corresponding ResourceClaim by the control plane after creating the ResourceClaim.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ClientIPConfig(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ClientIPConfig represents the configurations of Client IP based session affinity.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "timeoutSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "timeoutSeconds specifies the seconds of ClientIP type session sticky time. The value must be >0 && <=86400(for 1 day) if ServiceAffinity == \"ClientIP\". Default value is 10800(for 3 hours).", - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ClusterTrustBundleProjection(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ClusterTrustBundleProjection describes how to select a set of ClusterTrustBundle objects and project their contents into the pod filesystem.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Select a single ClusterTrustBundle by object name. Mutually-exclusive with signerName and labelSelector.", - Type: []string{"string"}, - Format: "", - }, - }, - "signerName": { - SchemaProps: spec.SchemaProps{ - Description: "Select all ClusterTrustBundles that match this signer name. Mutually-exclusive with name. The contents of all selected ClusterTrustBundles will be unified and deduplicated.", - Type: []string{"string"}, - Format: "", - }, - }, - "labelSelector": { - SchemaProps: spec.SchemaProps{ - Description: "Select all ClusterTrustBundles that match this label selector. Only has effect if signerName is set. Mutually-exclusive with name. If unset, interpreted as \"match nothing\". If set but empty, interpreted as \"match everything\".", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), - }, - }, - "optional": { - SchemaProps: spec.SchemaProps{ - Description: "If true, don't block pod startup if the referenced ClusterTrustBundle(s) aren't available. If using name, then the named ClusterTrustBundle is allowed not to exist. If using signerName, then the combination of signerName and labelSelector is allowed to match zero ClusterTrustBundles.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "Relative path from the volume root to write the bundle.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"path"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"}, - } -} - -func schema_k8sio_api_core_v1_ComponentCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Information about the condition of a component.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of condition for a component. Valid value: \"Healthy\"", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status of the condition for a component. Valid values for \"Healthy\": \"True\", \"False\", or \"Unknown\".", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "Message about the condition for a component. For example, information about a health check.", - Type: []string{"string"}, - Format: "", - }, - }, - "error": { - SchemaProps: spec.SchemaProps{ - Description: "Condition error code for a component. For example, a health check error code.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ComponentStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ComponentStatus (and ComponentStatusList) holds the cluster validation info. Deprecated: This API is deprecated in v1.19+", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "conditions": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of component conditions observed", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ComponentCondition"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ComponentCondition", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_ComponentStatusList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Status of all the conditions for the component as a list of ComponentStatus objects. Deprecated: This API is deprecated in v1.19+", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of ComponentStatus objects.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ComponentStatus"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ComponentStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_ConfigMap(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ConfigMap holds configuration data for pods to consume.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "immutable": { - SchemaProps: spec.SchemaProps{ - Description: "Immutable, if set to true, ensures that data stored in the ConfigMap cannot be updated (only object metadata can be modified). If not set to true, the field can be modified at any time. Defaulted to nil.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "data": { - SchemaProps: spec.SchemaProps{ - Description: "Data contains the configuration data. Each key must consist of alphanumeric characters, '-', '_' or '.'. Values with non-UTF-8 byte sequences must use the BinaryData field. The keys stored in Data must not overlap with the keys in the BinaryData field, this is enforced during validation process.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "binaryData": { - SchemaProps: spec.SchemaProps{ - Description: "BinaryData contains the binary data. Each key must consist of alphanumeric characters, '-', '_' or '.'. BinaryData can contain byte sequences that are not in the UTF-8 range. The keys stored in BinaryData must not overlap with the ones in the Data field, this is enforced during validation process. Using this field will require 1.10+ apiserver and kubelet.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "byte", - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_ConfigMapEnvSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ConfigMapEnvSource selects a ConfigMap to populate the environment variables with.\n\nThe contents of the target ConfigMap's Data field will represent the key-value pairs as environment variables.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Type: []string{"string"}, - Format: "", - }, - }, - "optional": { - SchemaProps: spec.SchemaProps{ - Description: "Specify whether the ConfigMap must be defined", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ConfigMapKeySelector(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Selects a key from a ConfigMap.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Type: []string{"string"}, - Format: "", - }, - }, - "key": { - SchemaProps: spec.SchemaProps{ - Description: "The key to select.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "optional": { - SchemaProps: spec.SchemaProps{ - Description: "Specify whether the ConfigMap or its key must be defined", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"key"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ConfigMapList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ConfigMapList is a resource containing a list of ConfigMap objects.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is the list of ConfigMaps.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ConfigMap"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ConfigMap", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_ConfigMapNodeConfigSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ConfigMapNodeConfigSource contains the information to reference a ConfigMap as a config source for the Node. This API is deprecated since 1.22: https://git.k8s.io/enhancements/keps/sig-node/281-dynamic-kubelet-configuration", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "namespace": { - SchemaProps: spec.SchemaProps{ - Description: "Namespace is the metadata.namespace of the referenced ConfigMap. This field is required in all cases.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name is the metadata.name of the referenced ConfigMap. This field is required in all cases.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "uid": { - SchemaProps: spec.SchemaProps{ - Description: "UID is the metadata.UID of the referenced ConfigMap. This field is forbidden in Node.Spec, and required in Node.Status.", - Type: []string{"string"}, - Format: "", - }, - }, - "resourceVersion": { - SchemaProps: spec.SchemaProps{ - Description: "ResourceVersion is the metadata.ResourceVersion of the referenced ConfigMap. This field is forbidden in Node.Spec, and required in Node.Status.", - Type: []string{"string"}, - Format: "", - }, - }, - "kubeletConfigKey": { - SchemaProps: spec.SchemaProps{ - Description: "KubeletConfigKey declares which key of the referenced ConfigMap corresponds to the KubeletConfiguration structure This field is required in all cases.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"namespace", "name", "kubeletConfigKey"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ConfigMapProjection(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Adapts a ConfigMap into a projected volume.\n\nThe contents of the target ConfigMap's Data field will be presented in a projected volume as files using the keys in the Data field as the file names, unless the items element is populated with specific mappings of keys to paths. Note that this is identical to a configmap volume source without the default mode.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Type: []string{"string"}, - Format: "", - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "items if unspecified, each key-value pair in the Data field of the referenced ConfigMap will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the ConfigMap, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.KeyToPath"), - }, - }, - }, - }, - }, - "optional": { - SchemaProps: spec.SchemaProps{ - Description: "optional specify whether the ConfigMap or its keys must be defined", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.KeyToPath"}, - } -} - -func schema_k8sio_api_core_v1_ConfigMapVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Adapts a ConfigMap into a volume.\n\nThe contents of the target ConfigMap's Data field will be presented in a volume as files using the keys in the Data field as the file names, unless the items element is populated with specific mappings of keys to paths. ConfigMap volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Type: []string{"string"}, - Format: "", - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "items if unspecified, each key-value pair in the Data field of the referenced ConfigMap will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the ConfigMap, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.KeyToPath"), - }, - }, - }, - }, - }, - "defaultMode": { - SchemaProps: spec.SchemaProps{ - Description: "defaultMode is optional: mode bits used to set permissions on created files by default. Must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "optional": { - SchemaProps: spec.SchemaProps{ - Description: "optional specify whether the ConfigMap or its keys must be defined", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.KeyToPath"}, - } -} - -func schema_k8sio_api_core_v1_Container(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A single application container that you want to run within a pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the container specified as a DNS_LABEL. Each container in a pod must have a unique name (DNS_LABEL). Cannot be updated.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "image": { - SchemaProps: spec.SchemaProps{ - Description: "Container image name. More info: https://kubernetes.io/docs/concepts/containers/images This field is optional to allow higher level config management to default or override container images in workload controllers like Deployments and StatefulSets.", - Type: []string{"string"}, - Format: "", - }, - }, - "command": { - SchemaProps: spec.SchemaProps{ - Description: "Entrypoint array. Not executed within a shell. The container image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "args": { - SchemaProps: spec.SchemaProps{ - Description: "Arguments to the entrypoint. The container image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "workingDir": { - SchemaProps: spec.SchemaProps{ - Description: "Container's working directory. If not specified, the container runtime's default will be used, which might be configured in the container image. Cannot be updated.", - Type: []string{"string"}, - Format: "", - }, - }, - "ports": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "containerPort", - "protocol", - }, - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "containerPort", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of ports to expose from the container. Not specifying a port here DOES NOT prevent that port from being exposed. Any port which is listening on the default \"0.0.0.0\" address inside a container will be accessible from the network. Modifying this array with strategic merge patch may corrupt the data. For more information See https://github.com/kubernetes/kubernetes/issues/108255. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerPort"), - }, - }, - }, - }, - }, - "envFrom": { - SchemaProps: spec.SchemaProps{ - Description: "List of sources to populate environment variables in the container. The keys defined within a source must be a C_IDENTIFIER. All invalid keys will be reported as an event when the container is starting. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EnvFromSource"), - }, - }, - }, - }, - }, - "env": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of environment variables to set in the container. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EnvVar"), - }, - }, - }, - }, - }, - "resources": { - SchemaProps: spec.SchemaProps{ - Description: "Compute Resources required by this container. Cannot be updated. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ResourceRequirements"), - }, - }, - "resizePolicy": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Resources resize policy for the container.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerResizePolicy"), - }, - }, - }, - }, - }, - "restartPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "RestartPolicy defines the restart behavior of individual containers in a pod. This field may only be set for init containers, and the only allowed value is \"Always\". For non-init containers or when this field is not specified, the restart behavior is defined by the Pod's restart policy and the container type. Setting the RestartPolicy as \"Always\" for the init container will have the following effect: this init container will be continually restarted on exit until all regular containers have terminated. Once all regular containers have completed, all init containers with restartPolicy \"Always\" will be shut down. This lifecycle differs from normal init containers and is often referred to as a \"sidecar\" container. Although this init container still starts in the init container sequence, it does not wait for the container to complete before proceeding to the next init container. Instead, the next init container starts immediately after this init container is started, or after any startupProbe has successfully completed.", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeMounts": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "mountPath", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Pod volumes to mount into the container's filesystem. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.VolumeMount"), - }, - }, - }, - }, - }, - "volumeDevices": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "devicePath", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "volumeDevices is the list of block devices to be used by the container.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.VolumeDevice"), - }, - }, - }, - }, - }, - "livenessProbe": { - SchemaProps: spec.SchemaProps{ - Description: "Periodic probe of container liveness. Container will be restarted if the probe fails. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "readinessProbe": { - SchemaProps: spec.SchemaProps{ - Description: "Periodic probe of container service readiness. Container will be removed from service endpoints if the probe fails. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "startupProbe": { - SchemaProps: spec.SchemaProps{ - Description: "StartupProbe indicates that the Pod has successfully initialized. If specified, no other probes are executed until this completes successfully. If this probe fails, the Pod will be restarted, just as if the livenessProbe failed. This can be used to provide different probe parameters at the beginning of a Pod's lifecycle, when it might take a long time to load data or warm a cache, than during steady-state operation. This cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "lifecycle": { - SchemaProps: spec.SchemaProps{ - Description: "Actions that the management system should take in response to container lifecycle events. Cannot be updated.", - Ref: ref("k8s.io/api/core/v1.Lifecycle"), - }, - }, - "terminationMessagePath": { - SchemaProps: spec.SchemaProps{ - Description: "Optional: Path at which the file to which the container's termination message will be written is mounted into the container's filesystem. Message written is intended to be brief final status, such as an assertion failure message. Will be truncated by the node if greater than 4096 bytes. The total message length across all containers will be limited to 12kb. Defaults to /dev/termination-log. Cannot be updated.", - Type: []string{"string"}, - Format: "", - }, - }, - "terminationMessagePolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Indicate how the termination message should be populated. File will use the contents of terminationMessagePath to populate the container status message on both success and failure. FallbackToLogsOnError will use the last chunk of container log output if the termination message file is empty and the container exited with an error. The log output is limited to 2048 bytes or 80 lines, whichever is smaller. Defaults to File. Cannot be updated.\n\nPossible enum values:\n - `\"FallbackToLogsOnError\"` will read the most recent contents of the container logs for the container status message when the container exits with an error and the terminationMessagePath has no contents.\n - `\"File\"` is the default behavior and will set the container status message to the contents of the container's terminationMessagePath when the container exits.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"FallbackToLogsOnError", "File"}, - }, - }, - "imagePullPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More info: https://kubernetes.io/docs/concepts/containers/images#updating-images\n\nPossible enum values:\n - `\"Always\"` means that kubelet always attempts to pull the latest image. Container will fail If the pull fails.\n - `\"IfNotPresent\"` means that kubelet pulls if the image isn't present on disk. Container will fail if the image isn't present and the pull fails.\n - `\"Never\"` means that kubelet never pulls an image, but only uses a local image. Container will fail if the image isn't present", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Always", "IfNotPresent", "Never"}, - }, - }, - "securityContext": { - SchemaProps: spec.SchemaProps{ - Description: "SecurityContext defines the security options the container should be run with. If set, the fields of SecurityContext override the equivalent fields of PodSecurityContext. More info: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/", - Ref: ref("k8s.io/api/core/v1.SecurityContext"), - }, - }, - "stdin": { - SchemaProps: spec.SchemaProps{ - Description: "Whether this container should allocate a buffer for stdin in the container runtime. If this is not set, reads from stdin in the container will always result in EOF. Default is false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "stdinOnce": { - SchemaProps: spec.SchemaProps{ - Description: "Whether the container runtime should close the stdin channel after it has been opened by a single attach. When stdin is true the stdin stream will remain open across multiple attach sessions. If stdinOnce is set to true, stdin is opened on container start, is empty until the first client attaches to stdin, and then remains open and accepts data until the client disconnects, at which time stdin is closed and remains closed until the container is restarted. If this flag is false, a container processes that reads from stdin will never receive an EOF. Default is false", - Type: []string{"boolean"}, - Format: "", - }, - }, - "tty": { - SchemaProps: spec.SchemaProps{ - Description: "Whether this container should allocate a TTY for itself, also requires 'stdin' to be true. Default is false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"name"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ContainerPort", "k8s.io/api/core/v1.ContainerResizePolicy", "k8s.io/api/core/v1.EnvFromSource", "k8s.io/api/core/v1.EnvVar", "k8s.io/api/core/v1.Lifecycle", "k8s.io/api/core/v1.Probe", "k8s.io/api/core/v1.ResourceRequirements", "k8s.io/api/core/v1.SecurityContext", "k8s.io/api/core/v1.VolumeDevice", "k8s.io/api/core/v1.VolumeMount"}, - } -} - -func schema_k8sio_api_core_v1_ContainerImage(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Describe a container image", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "names": { - SchemaProps: spec.SchemaProps{ - Description: "Names by which this image is known. e.g. [\"kubernetes.example/hyperkube:v1.0.7\", \"cloud-vendor.registry.example/cloud-vendor/hyperkube:v1.0.7\"]", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "sizeBytes": { - SchemaProps: spec.SchemaProps{ - Description: "The size of the image in bytes.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ContainerPort(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ContainerPort represents a network port in a single container.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, this must be an IANA_SVC_NAME and unique within the pod. Each named port in a pod must have a unique name. Name for the port that can be referred to by services.", - Type: []string{"string"}, - Format: "", - }, - }, - "hostPort": { - SchemaProps: spec.SchemaProps{ - Description: "Number of port to expose on the host. If specified, this must be a valid port number, 0 < x < 65536. If HostNetwork is specified, this must match ContainerPort. Most containers do not need this.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "containerPort": { - SchemaProps: spec.SchemaProps{ - Description: "Number of port to expose on the pod's IP address. This must be a valid port number, 0 < x < 65536.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "protocol": { - SchemaProps: spec.SchemaProps{ - Description: "Protocol for port. Must be UDP, TCP, or SCTP. Defaults to \"TCP\".\n\nPossible enum values:\n - `\"SCTP\"` is the SCTP protocol.\n - `\"TCP\"` is the TCP protocol.\n - `\"UDP\"` is the UDP protocol.", - Default: "TCP", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"SCTP", "TCP", "UDP"}, - }, - }, - "hostIP": { - SchemaProps: spec.SchemaProps{ - Description: "What host IP to bind the external port to.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"containerPort"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ContainerResizePolicy(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ContainerResizePolicy represents resource resize policy for the container.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "resourceName": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the resource to which this resource resize policy applies. Supported values: cpu, memory.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "restartPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Restart policy to apply when specified resource is resized. If not specified, it defaults to NotRequired.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"resourceName", "restartPolicy"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ContainerState(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ContainerState holds a possible state of container. Only one of its members may be specified. If none of them is specified, the default one is ContainerStateWaiting.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "waiting": { - SchemaProps: spec.SchemaProps{ - Description: "Details about a waiting container", - Ref: ref("k8s.io/api/core/v1.ContainerStateWaiting"), - }, - }, - "running": { - SchemaProps: spec.SchemaProps{ - Description: "Details about a running container", - Ref: ref("k8s.io/api/core/v1.ContainerStateRunning"), - }, - }, - "terminated": { - SchemaProps: spec.SchemaProps{ - Description: "Details about a terminated container", - Ref: ref("k8s.io/api/core/v1.ContainerStateTerminated"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ContainerStateRunning", "k8s.io/api/core/v1.ContainerStateTerminated", "k8s.io/api/core/v1.ContainerStateWaiting"}, - } -} - -func schema_k8sio_api_core_v1_ContainerStateRunning(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ContainerStateRunning is a running state of a container.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "startedAt": { - SchemaProps: spec.SchemaProps{ - Description: "Time at which the container was last (re-)started", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_ContainerStateTerminated(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ContainerStateTerminated is a terminated state of a container.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "exitCode": { - SchemaProps: spec.SchemaProps{ - Description: "Exit status from the last termination of the container", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "signal": { - SchemaProps: spec.SchemaProps{ - Description: "Signal from the last termination of the container", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "(brief) reason from the last termination of the container", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "Message regarding the last termination of the container", - Type: []string{"string"}, - Format: "", - }, - }, - "startedAt": { - SchemaProps: spec.SchemaProps{ - Description: "Time at which previous execution of the container started", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "finishedAt": { - SchemaProps: spec.SchemaProps{ - Description: "Time at which the container last terminated", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "containerID": { - SchemaProps: spec.SchemaProps{ - Description: "Container's ID in the format '://'", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"exitCode"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_ContainerStateWaiting(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ContainerStateWaiting is a waiting state of a container.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "(brief) reason the container is not yet running.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "Message regarding why the container is not yet running.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ContainerStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ContainerStatus contains details for the current status of this container.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name is a DNS_LABEL representing the unique name of the container. Each container in a pod must have a unique name across all container types. Cannot be updated.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "state": { - SchemaProps: spec.SchemaProps{ - Description: "State holds details about the container's current condition.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerState"), - }, - }, - "lastState": { - SchemaProps: spec.SchemaProps{ - Description: "LastTerminationState holds the last termination state of the container to help debug container crashes and restarts. This field is not populated if the container is still running and RestartCount is 0.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerState"), - }, - }, - "ready": { - SchemaProps: spec.SchemaProps{ - Description: "Ready specifies whether the container is currently passing its readiness check. The value will change as readiness probes keep executing. If no readiness probes are specified, this field defaults to true once the container is fully started (see Started field).\n\nThe value is typically used to determine whether a container is ready to accept traffic.", - Default: false, - Type: []string{"boolean"}, - Format: "", - }, - }, - "restartCount": { - SchemaProps: spec.SchemaProps{ - Description: "RestartCount holds the number of times the container has been restarted. Kubelet makes an effort to always increment the value, but there are cases when the state may be lost due to node restarts and then the value may be reset to 0. The value is never negative.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "image": { - SchemaProps: spec.SchemaProps{ - Description: "Image is the name of container image that the container is running. The container image may not match the image used in the PodSpec, as it may have been resolved by the runtime. More info: https://kubernetes.io/docs/concepts/containers/images.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "imageID": { - SchemaProps: spec.SchemaProps{ - Description: "ImageID is the image ID of the container's image. The image ID may not match the image ID of the image used in the PodSpec, as it may have been resolved by the runtime.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "containerID": { - SchemaProps: spec.SchemaProps{ - Description: "ContainerID is the ID of the container in the format '://'. Where type is a container runtime identifier, returned from Version call of CRI API (for example \"containerd\").", - Type: []string{"string"}, - Format: "", - }, - }, - "started": { - SchemaProps: spec.SchemaProps{ - Description: "Started indicates whether the container has finished its postStart lifecycle hook and passed its startup probe. Initialized as false, becomes true after startupProbe is considered successful. Resets to false when the container is restarted, or if kubelet loses state temporarily. In both cases, startup probes will run again. Is always true when no startupProbe is defined and container is running and has passed the postStart lifecycle hook. The null value must be treated the same as false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "allocatedResources": { - SchemaProps: spec.SchemaProps{ - Description: "AllocatedResources represents the compute resources allocated for this container by the node. Kubelet sets this value to Container.Resources.Requests upon successful pod admission and after successfully admitting desired pod resize.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "resources": { - SchemaProps: spec.SchemaProps{ - Description: "Resources represents the compute resource requests and limits that have been successfully enacted on the running container after it has been started or has been successfully resized.", - Ref: ref("k8s.io/api/core/v1.ResourceRequirements"), - }, - }, - }, - Required: []string{"name", "ready", "restartCount", "image", "imageID"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ContainerState", "k8s.io/api/core/v1.ResourceRequirements", "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_DaemonEndpoint(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "DaemonEndpoint contains information about a single Daemon endpoint.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "Port": { - SchemaProps: spec.SchemaProps{ - Description: "Port number of the given endpoint.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - Required: []string{"Port"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_DownwardAPIProjection(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents downward API info for projecting into a projected volume. Note that this is identical to a downwardAPI volume source without the default mode.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is a list of DownwardAPIVolume file", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.DownwardAPIVolumeFile"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.DownwardAPIVolumeFile"}, - } -} - -func schema_k8sio_api_core_v1_DownwardAPIVolumeFile(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "DownwardAPIVolumeFile represents information to create the file containing the pod field", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "path": { - SchemaProps: spec.SchemaProps{ - Description: "Required: Path is the relative path name of the file to be created. Must not be absolute or contain the '..' path. Must be utf-8 encoded. The first item of the relative path must not start with '..'", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fieldRef": { - SchemaProps: spec.SchemaProps{ - Description: "Required: Selects a field of the pod: only annotations, labels, name and namespace are supported.", - Ref: ref("k8s.io/api/core/v1.ObjectFieldSelector"), - }, - }, - "resourceFieldRef": { - SchemaProps: spec.SchemaProps{ - Description: "Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, requests.cpu and requests.memory) are currently supported.", - Ref: ref("k8s.io/api/core/v1.ResourceFieldSelector"), - }, - }, - "mode": { - SchemaProps: spec.SchemaProps{ - Description: "Optional: mode bits used to set permissions on this file, must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - Required: []string{"path"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ObjectFieldSelector", "k8s.io/api/core/v1.ResourceFieldSelector"}, - } -} - -func schema_k8sio_api_core_v1_DownwardAPIVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "DownwardAPIVolumeSource represents a volume containing downward API info. Downward API volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is a list of downward API volume file", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.DownwardAPIVolumeFile"), - }, - }, - }, - }, - }, - "defaultMode": { - SchemaProps: spec.SchemaProps{ - Description: "Optional: mode bits to use on created files by default. Must be a Optional: mode bits used to set permissions on created files by default. Must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.DownwardAPIVolumeFile"}, - } -} - -func schema_k8sio_api_core_v1_EmptyDirVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents an empty directory for a pod. Empty directory volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "medium": { - SchemaProps: spec.SchemaProps{ - Description: "medium represents what type of storage medium should back this directory. The default is \"\" which means to use the node's default medium. Must be an empty string (default) or Memory. More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir", - Type: []string{"string"}, - Format: "", - }, - }, - "sizeLimit": { - SchemaProps: spec.SchemaProps{ - Description: "sizeLimit is the total amount of local storage required for this EmptyDir volume. The size limit is also applicable for memory medium. The maximum usage on memory medium EmptyDir would be the minimum value between the SizeLimit specified here and the sum of memory limits of all containers in a pod. The default is nil which means that the limit is undefined. More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir", - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_EndpointAddress(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EndpointAddress is a tuple that describes single IP address.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "ip": { - SchemaProps: spec.SchemaProps{ - Description: "The IP of this endpoint. May not be loopback (127.0.0.0/8 or ::1), link-local (169.254.0.0/16 or fe80::/10), or link-local multicast (224.0.0.0/24 or ff02::/16).", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "hostname": { - SchemaProps: spec.SchemaProps{ - Description: "The Hostname of this endpoint", - Type: []string{"string"}, - Format: "", - }, - }, - "nodeName": { - SchemaProps: spec.SchemaProps{ - Description: "Optional: Node hosting this endpoint. This can be used to determine endpoints local to a node.", - Type: []string{"string"}, - Format: "", - }, - }, - "targetRef": { - SchemaProps: spec.SchemaProps{ - Description: "Reference to object providing the endpoint.", - Ref: ref("k8s.io/api/core/v1.ObjectReference"), - }, - }, - }, - Required: []string{"ip"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_EndpointPort(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EndpointPort is a tuple that describes a single port.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "The name of this port. This must match the 'name' field in the corresponding ServicePort. Must be a DNS_LABEL. Optional only if one port is defined.", - Type: []string{"string"}, - Format: "", - }, - }, - "port": { - SchemaProps: spec.SchemaProps{ - Description: "The port number of the endpoint.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "protocol": { - SchemaProps: spec.SchemaProps{ - Description: "The IP protocol for this port. Must be UDP, TCP, or SCTP. Default is TCP.\n\nPossible enum values:\n - `\"SCTP\"` is the SCTP protocol.\n - `\"TCP\"` is the TCP protocol.\n - `\"UDP\"` is the UDP protocol.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"SCTP", "TCP", "UDP"}, - }, - }, - "appProtocol": { - SchemaProps: spec.SchemaProps{ - Description: "The application protocol for this port. This is used as a hint for implementations to offer richer behavior for protocols that they understand. This field follows standard Kubernetes label syntax. Valid values are either:\n\n* Un-prefixed protocol names - reserved for IANA standard service names (as per RFC-6335 and https://www.iana.org/assignments/service-names).\n\n* Kubernetes-defined prefixed names:\n * 'kubernetes.io/h2c' - HTTP/2 prior knowledge over cleartext as described in https://www.rfc-editor.org/rfc/rfc9113.html#name-starting-http-2-with-prior-\n * 'kubernetes.io/ws' - WebSocket over cleartext as described in https://www.rfc-editor.org/rfc/rfc6455\n * 'kubernetes.io/wss' - WebSocket over TLS as described in https://www.rfc-editor.org/rfc/rfc6455\n\n* Other protocols should use implementation-defined prefixed names such as mycompany.com/my-custom-protocol.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"port"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_EndpointSubset(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EndpointSubset is a group of addresses with a common set of ports. The expanded set of endpoints is the Cartesian product of Addresses x Ports. For example, given:\n\n\t{\n\t Addresses: [{\"ip\": \"10.10.1.1\"}, {\"ip\": \"10.10.2.2\"}],\n\t Ports: [{\"name\": \"a\", \"port\": 8675}, {\"name\": \"b\", \"port\": 309}]\n\t}\n\nThe resulting set of endpoints can be viewed as:\n\n\ta: [ 10.10.1.1:8675, 10.10.2.2:8675 ],\n\tb: [ 10.10.1.1:309, 10.10.2.2:309 ]", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "addresses": { - SchemaProps: spec.SchemaProps{ - Description: "IP addresses which offer the related ports that are marked as ready. These endpoints should be considered safe for load balancers and clients to utilize.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EndpointAddress"), - }, - }, - }, - }, - }, - "notReadyAddresses": { - SchemaProps: spec.SchemaProps{ - Description: "IP addresses which offer the related ports but are not currently marked as ready because they have not yet finished starting, have recently failed a readiness check, or have recently failed a liveness check.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EndpointAddress"), - }, - }, - }, - }, - }, - "ports": { - SchemaProps: spec.SchemaProps{ - Description: "Port numbers available on the related IP addresses.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EndpointPort"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.EndpointAddress", "k8s.io/api/core/v1.EndpointPort"}, - } -} - -func schema_k8sio_api_core_v1_Endpoints(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Endpoints is a collection of endpoints that implement the actual service. Example:\n\n\t Name: \"mysvc\",\n\t Subsets: [\n\t {\n\t Addresses: [{\"ip\": \"10.10.1.1\"}, {\"ip\": \"10.10.2.2\"}],\n\t Ports: [{\"name\": \"a\", \"port\": 8675}, {\"name\": \"b\", \"port\": 309}]\n\t },\n\t {\n\t Addresses: [{\"ip\": \"10.10.3.3\"}],\n\t Ports: [{\"name\": \"a\", \"port\": 93}, {\"name\": \"b\", \"port\": 76}]\n\t },\n\t]", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "subsets": { - SchemaProps: spec.SchemaProps{ - Description: "The set of all endpoints is the union of all subsets. Addresses are placed into subsets according to the IPs they share. A single address with multiple ports, some of which are ready and some of which are not (because they come from different containers) will result in the address being displayed in different subsets for the different ports. No address will appear in both Addresses and NotReadyAddresses in the same subset. Sets of addresses and ports that comprise a service.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EndpointSubset"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.EndpointSubset", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_EndpointsList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EndpointsList is a list of endpoints.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of endpoints.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Endpoints"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.Endpoints", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_EnvFromSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EnvFromSource represents the source of a set of ConfigMaps", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "prefix": { - SchemaProps: spec.SchemaProps{ - Description: "An optional identifier to prepend to each key in the ConfigMap. Must be a C_IDENTIFIER.", - Type: []string{"string"}, - Format: "", - }, - }, - "configMapRef": { - SchemaProps: spec.SchemaProps{ - Description: "The ConfigMap to select from", - Ref: ref("k8s.io/api/core/v1.ConfigMapEnvSource"), - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "The Secret to select from", - Ref: ref("k8s.io/api/core/v1.SecretEnvSource"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ConfigMapEnvSource", "k8s.io/api/core/v1.SecretEnvSource"}, - } -} - -func schema_k8sio_api_core_v1_EnvVar(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EnvVar represents an environment variable present in a Container.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the environment variable. Must be a C_IDENTIFIER.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "value": { - SchemaProps: spec.SchemaProps{ - Description: "Variable references $(VAR_NAME) are expanded using the previously defined environment variables in the container and any service environment variables. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Defaults to \"\".", - Type: []string{"string"}, - Format: "", - }, - }, - "valueFrom": { - SchemaProps: spec.SchemaProps{ - Description: "Source for the environment variable's value. Cannot be used if value is not empty.", - Ref: ref("k8s.io/api/core/v1.EnvVarSource"), - }, - }, - }, - Required: []string{"name"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.EnvVarSource"}, - } -} - -func schema_k8sio_api_core_v1_EnvVarSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EnvVarSource represents a source for the value of an EnvVar.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "fieldRef": { - SchemaProps: spec.SchemaProps{ - Description: "Selects a field of the pod: supports metadata.name, metadata.namespace, `metadata.labels['']`, `metadata.annotations['']`, spec.nodeName, spec.serviceAccountName, status.hostIP, status.podIP, status.podIPs.", - Ref: ref("k8s.io/api/core/v1.ObjectFieldSelector"), - }, - }, - "resourceFieldRef": { - SchemaProps: spec.SchemaProps{ - Description: "Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, limits.ephemeral-storage, requests.cpu, requests.memory and requests.ephemeral-storage) are currently supported.", - Ref: ref("k8s.io/api/core/v1.ResourceFieldSelector"), - }, - }, - "configMapKeyRef": { - SchemaProps: spec.SchemaProps{ - Description: "Selects a key of a ConfigMap.", - Ref: ref("k8s.io/api/core/v1.ConfigMapKeySelector"), - }, - }, - "secretKeyRef": { - SchemaProps: spec.SchemaProps{ - Description: "Selects a key of a secret in the pod's namespace", - Ref: ref("k8s.io/api/core/v1.SecretKeySelector"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ConfigMapKeySelector", "k8s.io/api/core/v1.ObjectFieldSelector", "k8s.io/api/core/v1.ResourceFieldSelector", "k8s.io/api/core/v1.SecretKeySelector"}, - } -} - -func schema_k8sio_api_core_v1_EphemeralContainer(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "An EphemeralContainer is a temporary container that you may add to an existing Pod for user-initiated activities such as debugging. Ephemeral containers have no resource or scheduling guarantees, and they will not be restarted when they exit or when a Pod is removed or restarted. The kubelet may evict a Pod if an ephemeral container causes the Pod to exceed its resource allocation.\n\nTo add an ephemeral container, use the ephemeralcontainers subresource of an existing Pod. Ephemeral containers may not be removed or restarted.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the ephemeral container specified as a DNS_LABEL. This name must be unique among all containers, init containers and ephemeral containers.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "image": { - SchemaProps: spec.SchemaProps{ - Description: "Container image name. More info: https://kubernetes.io/docs/concepts/containers/images", - Type: []string{"string"}, - Format: "", - }, - }, - "command": { - SchemaProps: spec.SchemaProps{ - Description: "Entrypoint array. Not executed within a shell. The image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "args": { - SchemaProps: spec.SchemaProps{ - Description: "Arguments to the entrypoint. The image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "workingDir": { - SchemaProps: spec.SchemaProps{ - Description: "Container's working directory. If not specified, the container runtime's default will be used, which might be configured in the container image. Cannot be updated.", - Type: []string{"string"}, - Format: "", - }, - }, - "ports": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "containerPort", - "protocol", - }, - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "containerPort", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Ports are not allowed for ephemeral containers.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerPort"), - }, - }, - }, - }, - }, - "envFrom": { - SchemaProps: spec.SchemaProps{ - Description: "List of sources to populate environment variables in the container. The keys defined within a source must be a C_IDENTIFIER. All invalid keys will be reported as an event when the container is starting. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EnvFromSource"), - }, - }, - }, - }, - }, - "env": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of environment variables to set in the container. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EnvVar"), - }, - }, - }, - }, - }, - "resources": { - SchemaProps: spec.SchemaProps{ - Description: "Resources are not allowed for ephemeral containers. Ephemeral containers use spare resources already allocated to the pod.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ResourceRequirements"), - }, - }, - "resizePolicy": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Resources resize policy for the container.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerResizePolicy"), - }, - }, - }, - }, - }, - "restartPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Restart policy for the container to manage the restart behavior of each container within a pod. This may only be set for init containers. You cannot set this field on ephemeral containers.", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeMounts": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "mountPath", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Pod volumes to mount into the container's filesystem. Subpath mounts are not allowed for ephemeral containers. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.VolumeMount"), - }, - }, - }, - }, - }, - "volumeDevices": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "devicePath", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "volumeDevices is the list of block devices to be used by the container.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.VolumeDevice"), - }, - }, - }, - }, - }, - "livenessProbe": { - SchemaProps: spec.SchemaProps{ - Description: "Probes are not allowed for ephemeral containers.", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "readinessProbe": { - SchemaProps: spec.SchemaProps{ - Description: "Probes are not allowed for ephemeral containers.", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "startupProbe": { - SchemaProps: spec.SchemaProps{ - Description: "Probes are not allowed for ephemeral containers.", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "lifecycle": { - SchemaProps: spec.SchemaProps{ - Description: "Lifecycle is not allowed for ephemeral containers.", - Ref: ref("k8s.io/api/core/v1.Lifecycle"), - }, - }, - "terminationMessagePath": { - SchemaProps: spec.SchemaProps{ - Description: "Optional: Path at which the file to which the container's termination message will be written is mounted into the container's filesystem. Message written is intended to be brief final status, such as an assertion failure message. Will be truncated by the node if greater than 4096 bytes. The total message length across all containers will be limited to 12kb. Defaults to /dev/termination-log. Cannot be updated.", - Type: []string{"string"}, - Format: "", - }, - }, - "terminationMessagePolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Indicate how the termination message should be populated. File will use the contents of terminationMessagePath to populate the container status message on both success and failure. FallbackToLogsOnError will use the last chunk of container log output if the termination message file is empty and the container exited with an error. The log output is limited to 2048 bytes or 80 lines, whichever is smaller. Defaults to File. Cannot be updated.\n\nPossible enum values:\n - `\"FallbackToLogsOnError\"` will read the most recent contents of the container logs for the container status message when the container exits with an error and the terminationMessagePath has no contents.\n - `\"File\"` is the default behavior and will set the container status message to the contents of the container's terminationMessagePath when the container exits.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"FallbackToLogsOnError", "File"}, - }, - }, - "imagePullPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More info: https://kubernetes.io/docs/concepts/containers/images#updating-images\n\nPossible enum values:\n - `\"Always\"` means that kubelet always attempts to pull the latest image. Container will fail If the pull fails.\n - `\"IfNotPresent\"` means that kubelet pulls if the image isn't present on disk. Container will fail if the image isn't present and the pull fails.\n - `\"Never\"` means that kubelet never pulls an image, but only uses a local image. Container will fail if the image isn't present", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Always", "IfNotPresent", "Never"}, - }, - }, - "securityContext": { - SchemaProps: spec.SchemaProps{ - Description: "Optional: SecurityContext defines the security options the ephemeral container should be run with. If set, the fields of SecurityContext override the equivalent fields of PodSecurityContext.", - Ref: ref("k8s.io/api/core/v1.SecurityContext"), - }, - }, - "stdin": { - SchemaProps: spec.SchemaProps{ - Description: "Whether this container should allocate a buffer for stdin in the container runtime. If this is not set, reads from stdin in the container will always result in EOF. Default is false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "stdinOnce": { - SchemaProps: spec.SchemaProps{ - Description: "Whether the container runtime should close the stdin channel after it has been opened by a single attach. When stdin is true the stdin stream will remain open across multiple attach sessions. If stdinOnce is set to true, stdin is opened on container start, is empty until the first client attaches to stdin, and then remains open and accepts data until the client disconnects, at which time stdin is closed and remains closed until the container is restarted. If this flag is false, a container processes that reads from stdin will never receive an EOF. Default is false", - Type: []string{"boolean"}, - Format: "", - }, - }, - "tty": { - SchemaProps: spec.SchemaProps{ - Description: "Whether this container should allocate a TTY for itself, also requires 'stdin' to be true. Default is false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "targetContainerName": { - SchemaProps: spec.SchemaProps{ - Description: "If set, the name of the container from PodSpec that this ephemeral container targets. The ephemeral container will be run in the namespaces (IPC, PID, etc) of this container. If not set then the ephemeral container uses the namespaces configured in the Pod spec.\n\nThe container runtime must implement support for this feature. If the runtime does not support namespace targeting then the result of setting this field is undefined.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ContainerPort", "k8s.io/api/core/v1.ContainerResizePolicy", "k8s.io/api/core/v1.EnvFromSource", "k8s.io/api/core/v1.EnvVar", "k8s.io/api/core/v1.Lifecycle", "k8s.io/api/core/v1.Probe", "k8s.io/api/core/v1.ResourceRequirements", "k8s.io/api/core/v1.SecurityContext", "k8s.io/api/core/v1.VolumeDevice", "k8s.io/api/core/v1.VolumeMount"}, - } -} - -func schema_k8sio_api_core_v1_EphemeralContainerCommon(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EphemeralContainerCommon is a copy of all fields in Container to be inlined in EphemeralContainer. This separate type allows easy conversion from EphemeralContainer to Container and allows separate documentation for the fields of EphemeralContainer. When a new field is added to Container it must be added here as well.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the ephemeral container specified as a DNS_LABEL. This name must be unique among all containers, init containers and ephemeral containers.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "image": { - SchemaProps: spec.SchemaProps{ - Description: "Container image name. More info: https://kubernetes.io/docs/concepts/containers/images", - Type: []string{"string"}, - Format: "", - }, - }, - "command": { - SchemaProps: spec.SchemaProps{ - Description: "Entrypoint array. Not executed within a shell. The image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "args": { - SchemaProps: spec.SchemaProps{ - Description: "Arguments to the entrypoint. The image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "workingDir": { - SchemaProps: spec.SchemaProps{ - Description: "Container's working directory. If not specified, the container runtime's default will be used, which might be configured in the container image. Cannot be updated.", - Type: []string{"string"}, - Format: "", - }, - }, - "ports": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "containerPort", - "protocol", - }, - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "containerPort", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Ports are not allowed for ephemeral containers.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerPort"), - }, - }, - }, - }, - }, - "envFrom": { - SchemaProps: spec.SchemaProps{ - Description: "List of sources to populate environment variables in the container. The keys defined within a source must be a C_IDENTIFIER. All invalid keys will be reported as an event when the container is starting. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EnvFromSource"), - }, - }, - }, - }, - }, - "env": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of environment variables to set in the container. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EnvVar"), - }, - }, - }, - }, - }, - "resources": { - SchemaProps: spec.SchemaProps{ - Description: "Resources are not allowed for ephemeral containers. Ephemeral containers use spare resources already allocated to the pod.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ResourceRequirements"), - }, - }, - "resizePolicy": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Resources resize policy for the container.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerResizePolicy"), - }, - }, - }, - }, - }, - "restartPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Restart policy for the container to manage the restart behavior of each container within a pod. This may only be set for init containers. You cannot set this field on ephemeral containers.", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeMounts": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "mountPath", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Pod volumes to mount into the container's filesystem. Subpath mounts are not allowed for ephemeral containers. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.VolumeMount"), - }, - }, - }, - }, - }, - "volumeDevices": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "devicePath", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "volumeDevices is the list of block devices to be used by the container.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.VolumeDevice"), - }, - }, - }, - }, - }, - "livenessProbe": { - SchemaProps: spec.SchemaProps{ - Description: "Probes are not allowed for ephemeral containers.", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "readinessProbe": { - SchemaProps: spec.SchemaProps{ - Description: "Probes are not allowed for ephemeral containers.", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "startupProbe": { - SchemaProps: spec.SchemaProps{ - Description: "Probes are not allowed for ephemeral containers.", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "lifecycle": { - SchemaProps: spec.SchemaProps{ - Description: "Lifecycle is not allowed for ephemeral containers.", - Ref: ref("k8s.io/api/core/v1.Lifecycle"), - }, - }, - "terminationMessagePath": { - SchemaProps: spec.SchemaProps{ - Description: "Optional: Path at which the file to which the container's termination message will be written is mounted into the container's filesystem. Message written is intended to be brief final status, such as an assertion failure message. Will be truncated by the node if greater than 4096 bytes. The total message length across all containers will be limited to 12kb. Defaults to /dev/termination-log. Cannot be updated.", - Type: []string{"string"}, - Format: "", - }, - }, - "terminationMessagePolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Indicate how the termination message should be populated. File will use the contents of terminationMessagePath to populate the container status message on both success and failure. FallbackToLogsOnError will use the last chunk of container log output if the termination message file is empty and the container exited with an error. The log output is limited to 2048 bytes or 80 lines, whichever is smaller. Defaults to File. Cannot be updated.\n\nPossible enum values:\n - `\"FallbackToLogsOnError\"` will read the most recent contents of the container logs for the container status message when the container exits with an error and the terminationMessagePath has no contents.\n - `\"File\"` is the default behavior and will set the container status message to the contents of the container's terminationMessagePath when the container exits.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"FallbackToLogsOnError", "File"}, - }, - }, - "imagePullPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More info: https://kubernetes.io/docs/concepts/containers/images#updating-images\n\nPossible enum values:\n - `\"Always\"` means that kubelet always attempts to pull the latest image. Container will fail If the pull fails.\n - `\"IfNotPresent\"` means that kubelet pulls if the image isn't present on disk. Container will fail if the image isn't present and the pull fails.\n - `\"Never\"` means that kubelet never pulls an image, but only uses a local image. Container will fail if the image isn't present", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Always", "IfNotPresent", "Never"}, - }, - }, - "securityContext": { - SchemaProps: spec.SchemaProps{ - Description: "Optional: SecurityContext defines the security options the ephemeral container should be run with. If set, the fields of SecurityContext override the equivalent fields of PodSecurityContext.", - Ref: ref("k8s.io/api/core/v1.SecurityContext"), - }, - }, - "stdin": { - SchemaProps: spec.SchemaProps{ - Description: "Whether this container should allocate a buffer for stdin in the container runtime. If this is not set, reads from stdin in the container will always result in EOF. Default is false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "stdinOnce": { - SchemaProps: spec.SchemaProps{ - Description: "Whether the container runtime should close the stdin channel after it has been opened by a single attach. When stdin is true the stdin stream will remain open across multiple attach sessions. If stdinOnce is set to true, stdin is opened on container start, is empty until the first client attaches to stdin, and then remains open and accepts data until the client disconnects, at which time stdin is closed and remains closed until the container is restarted. If this flag is false, a container processes that reads from stdin will never receive an EOF. Default is false", - Type: []string{"boolean"}, - Format: "", - }, - }, - "tty": { - SchemaProps: spec.SchemaProps{ - Description: "Whether this container should allocate a TTY for itself, also requires 'stdin' to be true. Default is false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"name"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ContainerPort", "k8s.io/api/core/v1.ContainerResizePolicy", "k8s.io/api/core/v1.EnvFromSource", "k8s.io/api/core/v1.EnvVar", "k8s.io/api/core/v1.Lifecycle", "k8s.io/api/core/v1.Probe", "k8s.io/api/core/v1.ResourceRequirements", "k8s.io/api/core/v1.SecurityContext", "k8s.io/api/core/v1.VolumeDevice", "k8s.io/api/core/v1.VolumeMount"}, - } -} - -func schema_k8sio_api_core_v1_EphemeralVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents an ephemeral volume that is handled by a normal storage driver.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "volumeClaimTemplate": { - SchemaProps: spec.SchemaProps{ - Description: "Will be used to create a stand-alone PVC to provision the volume. The pod in which this EphemeralVolumeSource is embedded will be the owner of the PVC, i.e. the PVC will be deleted together with the pod. The name of the PVC will be `-` where `` is the name from the `PodSpec.Volumes` array entry. Pod validation will reject the pod if the concatenated name is not valid for a PVC (for example, too long).\n\nAn existing PVC with that name that is not owned by the pod will *not* be used for the pod to avoid using an unrelated volume by mistake. Starting the pod is then blocked until the unrelated PVC is removed. If such a pre-created PVC is meant to be used by the pod, the PVC has to updated with an owner reference to the pod once the pod exists. Normally this should not be necessary, but it may be useful when manually reconstructing a broken cluster.\n\nThis field is read-only and no changes will be made by Kubernetes to the PVC after it has been created.\n\nRequired, must not be nil.", - Ref: ref("k8s.io/api/core/v1.PersistentVolumeClaimTemplate"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PersistentVolumeClaimTemplate"}, - } -} - -func schema_k8sio_api_core_v1_Event(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Event is a report of an event somewhere in the cluster. Events have a limited retention time and triggers and messages may evolve with time. Event consumers should not rely on the timing of an event with a given Reason reflecting a consistent underlying trigger, or the continued existence of events with that Reason. Events should be treated as informative, best-effort, supplemental data.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "involvedObject": { - SchemaProps: spec.SchemaProps{ - Description: "The object that this event is about.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ObjectReference"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "This should be a short, machine understandable string that gives the reason for the transition into the object's current status.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "A human-readable description of the status of this operation.", - Type: []string{"string"}, - Format: "", - }, - }, - "source": { - SchemaProps: spec.SchemaProps{ - Description: "The component reporting this event. Should be a short machine understandable string.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EventSource"), - }, - }, - "firstTimestamp": { - SchemaProps: spec.SchemaProps{ - Description: "The time at which the event was first recorded. (Time of server receipt is in TypeMeta.)", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "lastTimestamp": { - SchemaProps: spec.SchemaProps{ - Description: "The time at which the most recent occurrence of this event was recorded.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "count": { - SchemaProps: spec.SchemaProps{ - Description: "The number of times this event has occurred.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of this event (Normal, Warning), new types could be added in the future", - Type: []string{"string"}, - Format: "", - }, - }, - "eventTime": { - SchemaProps: spec.SchemaProps{ - Description: "Time when this Event was first observed.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.MicroTime"), - }, - }, - "series": { - SchemaProps: spec.SchemaProps{ - Description: "Data about the Event series this event represents or nil if it's a singleton Event.", - Ref: ref("k8s.io/api/core/v1.EventSeries"), - }, - }, - "action": { - SchemaProps: spec.SchemaProps{ - Description: "What action was taken/failed regarding to the Regarding object.", - Type: []string{"string"}, - Format: "", - }, - }, - "related": { - SchemaProps: spec.SchemaProps{ - Description: "Optional secondary object for more complex actions.", - Ref: ref("k8s.io/api/core/v1.ObjectReference"), - }, - }, - "reportingComponent": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the controller that emitted this Event, e.g. `kubernetes.io/kubelet`.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "reportingInstance": { - SchemaProps: spec.SchemaProps{ - Description: "ID of the controller instance, e.g. `kubelet-xyzf`.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"metadata", "involvedObject"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.EventSeries", "k8s.io/api/core/v1.EventSource", "k8s.io/api/core/v1.ObjectReference", "k8s.io/apimachinery/pkg/apis/meta/v1.MicroTime", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_EventList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EventList is a list of events.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of events", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Event"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.Event", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_EventSeries(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EventSeries contain information on series of events, i.e. thing that was/is happening continuously for some time.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "count": { - SchemaProps: spec.SchemaProps{ - Description: "Number of occurrences in this series up to the last heartbeat time", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "lastObservedTime": { - SchemaProps: spec.SchemaProps{ - Description: "Time of the last occurrence observed", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.MicroTime"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.MicroTime"}, - } -} - -func schema_k8sio_api_core_v1_EventSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "EventSource contains information for an event.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "component": { - SchemaProps: spec.SchemaProps{ - Description: "Component from which the event is generated.", - Type: []string{"string"}, - Format: "", - }, - }, - "host": { - SchemaProps: spec.SchemaProps{ - Description: "Node name on which the event is generated.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ExecAction(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ExecAction describes a \"run in container\" action.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "command": { - SchemaProps: spec.SchemaProps{ - Description: "Command is the command line to execute inside the container, the working directory for the command is root ('/') in the container's filesystem. The command is simply exec'd, it is not run inside a shell, so traditional shell instructions ('|', etc) won't work. To use a shell, you need to explicitly call out to that shell. Exit status of 0 is treated as live/healthy and non-zero is unhealthy.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_FCVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Fibre Channel volume. Fibre Channel volumes can only be mounted as read/write once. Fibre Channel volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "targetWWNs": { - SchemaProps: spec.SchemaProps{ - Description: "targetWWNs is Optional: FC target worldwide names (WWNs)", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "lun": { - SchemaProps: spec.SchemaProps{ - Description: "lun is Optional: FC target lun number", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly is Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "wwids": { - SchemaProps: spec.SchemaProps{ - Description: "wwids Optional: FC volume world wide identifiers (wwids) Either wwids or combination of targetWWNs and lun must be set, but not both simultaneously.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_FlexPersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "FlexPersistentVolumeSource represents a generic persistent volume resource that is provisioned/attached using an exec based plugin.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "driver": { - SchemaProps: spec.SchemaProps{ - Description: "driver is the name of the driver to use for this volume.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". The default filesystem depends on FlexVolume script.", - Type: []string{"string"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef is Optional: SecretRef is reference to the secret object containing sensitive information to pass to the plugin scripts. This may be empty if no secret object is specified. If the secret object contains more than one secret, all secrets are passed to the plugin scripts.", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly is Optional: defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "options": { - SchemaProps: spec.SchemaProps{ - Description: "options is Optional: this field holds extra command options if any.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"driver"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.SecretReference"}, - } -} - -func schema_k8sio_api_core_v1_FlexVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "FlexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "driver": { - SchemaProps: spec.SchemaProps{ - Description: "driver is the name of the driver to use for this volume.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". The default filesystem depends on FlexVolume script.", - Type: []string{"string"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef is Optional: secretRef is reference to the secret object containing sensitive information to pass to the plugin scripts. This may be empty if no secret object is specified. If the secret object contains more than one secret, all secrets are passed to the plugin scripts.", - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly is Optional: defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "options": { - SchemaProps: spec.SchemaProps{ - Description: "options is Optional: this field holds extra command options if any.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"driver"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LocalObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_FlockerVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Flocker volume mounted by the Flocker agent. One and only one of datasetName and datasetUUID should be set. Flocker volumes do not support ownership management or SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "datasetName": { - SchemaProps: spec.SchemaProps{ - Description: "datasetName is Name of the dataset stored as metadata -> name on the dataset for Flocker should be considered as deprecated", - Type: []string{"string"}, - Format: "", - }, - }, - "datasetUUID": { - SchemaProps: spec.SchemaProps{ - Description: "datasetUUID is the UUID of the dataset. This is unique identifier of a Flocker dataset", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_GCEPersistentDiskVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Persistent Disk resource in Google Compute Engine.\n\nA GCE PD must exist before mounting to a container. The disk must also be in the same GCE project and zone as the kubelet. A GCE PD can only be mounted as read/write once or read-only many times. GCE PDs support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "pdName": { - SchemaProps: spec.SchemaProps{ - Description: "pdName is unique name of the PD resource in GCE. Used to identify the disk in GCE. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", - Type: []string{"string"}, - Format: "", - }, - }, - "partition": { - SchemaProps: spec.SchemaProps{ - Description: "partition is the partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as \"1\". Similarly, the volume partition for /dev/sda is \"0\" (or you can leave the property empty). More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"pdName"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_GRPCAction(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "port": { - SchemaProps: spec.SchemaProps{ - Description: "Port number of the gRPC service. Number must be in the range 1 to 65535.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "service": { - SchemaProps: spec.SchemaProps{ - Description: "Service is the name of the service to place in the gRPC HealthCheckRequest (see https://github.com/grpc/grpc/blob/master/doc/health-checking.md).\n\nIf this is not specified, the default behavior is defined by gRPC.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"port"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_GitRepoVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a volume that is populated with the contents of a git repository. Git repo volumes do not support ownership management. Git repo volumes support SELinux relabeling.\n\nDEPRECATED: GitRepo is deprecated. To provision a container with a git repo, mount an EmptyDir into an InitContainer that clones the repo using git, then mount the EmptyDir into the Pod's container.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "repository": { - SchemaProps: spec.SchemaProps{ - Description: "repository is the URL", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "revision": { - SchemaProps: spec.SchemaProps{ - Description: "revision is the commit hash for the specified revision.", - Type: []string{"string"}, - Format: "", - }, - }, - "directory": { - SchemaProps: spec.SchemaProps{ - Description: "directory is the target directory name. Must not contain or start with '..'. If '.' is supplied, the volume directory will be the git repository. Otherwise, if specified, the volume will contain the git repository in the subdirectory with the given name.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"repository"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_GlusterfsPersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Glusterfs mount that lasts the lifetime of a pod. Glusterfs volumes do not support ownership management or SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "endpoints": { - SchemaProps: spec.SchemaProps{ - Description: "endpoints is the endpoint name that details Glusterfs topology. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "path is the Glusterfs volume path. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly here will force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod", - Type: []string{"boolean"}, - Format: "", - }, - }, - "endpointsNamespace": { - SchemaProps: spec.SchemaProps{ - Description: "endpointsNamespace is the namespace that contains Glusterfs endpoint. If this field is empty, the EndpointNamespace defaults to the same namespace as the bound PVC. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"endpoints", "path"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_GlusterfsVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Glusterfs mount that lasts the lifetime of a pod. Glusterfs volumes do not support ownership management or SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "endpoints": { - SchemaProps: spec.SchemaProps{ - Description: "endpoints is the endpoint name that details Glusterfs topology. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "path is the Glusterfs volume path. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly here will force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"endpoints", "path"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_HTTPGetAction(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "HTTPGetAction describes an action based on HTTP Get requests.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "path": { - SchemaProps: spec.SchemaProps{ - Description: "Path to access on the HTTP server.", - Type: []string{"string"}, - Format: "", - }, - }, - "port": { - SchemaProps: spec.SchemaProps{ - Description: "Name or number of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.", - Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), - }, - }, - "host": { - SchemaProps: spec.SchemaProps{ - Description: "Host name to connect to, defaults to the pod IP. You probably want to set \"Host\" in httpHeaders instead.", - Type: []string{"string"}, - Format: "", - }, - }, - "scheme": { - SchemaProps: spec.SchemaProps{ - Description: "Scheme to use for connecting to the host. Defaults to HTTP.\n\nPossible enum values:\n - `\"HTTP\"` means that the scheme used will be http://\n - `\"HTTPS\"` means that the scheme used will be https://", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"HTTP", "HTTPS"}, - }, - }, - "httpHeaders": { - SchemaProps: spec.SchemaProps{ - Description: "Custom headers to set in the request. HTTP allows repeated headers.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.HTTPHeader"), - }, - }, - }, - }, - }, - }, - Required: []string{"port"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.HTTPHeader", "k8s.io/apimachinery/pkg/util/intstr.IntOrString"}, - } -} - -func schema_k8sio_api_core_v1_HTTPHeader(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "HTTPHeader describes a custom header to be used in HTTP probes", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "The header field name. This will be canonicalized upon output, so case-variant names will be understood as the same header.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "value": { - SchemaProps: spec.SchemaProps{ - Description: "The header field value", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name", "value"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_HostAlias(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "HostAlias holds the mapping between IP and hostnames that will be injected as an entry in the pod's hosts file.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "ip": { - SchemaProps: spec.SchemaProps{ - Description: "IP address of the host file entry.", - Type: []string{"string"}, - Format: "", - }, - }, - "hostnames": { - SchemaProps: spec.SchemaProps{ - Description: "Hostnames for the above IP address.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_HostIP(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "HostIP represents a single IP address allocated to the host.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "ip": { - SchemaProps: spec.SchemaProps{ - Description: "IP is the IP address assigned to the host", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_HostPathVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a host path mapped into a pod. Host path volumes do not support ownership management or SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "path": { - SchemaProps: spec.SchemaProps{ - Description: "path of the directory on the host. If the path is a symlink, it will follow the link to the real path. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "type": { - SchemaProps: spec.SchemaProps{ - Description: "type for HostPath Volume Defaults to \"\" More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath\n\nPossible enum values:\n - `\"\"` For backwards compatible, leave it empty if unset\n - `\"BlockDevice\"` A block device must exist at the given path\n - `\"CharDevice\"` A character device must exist at the given path\n - `\"Directory\"` A directory must exist at the given path\n - `\"DirectoryOrCreate\"` If nothing exists at the given path, an empty directory will be created there as needed with file mode 0755, having the same group and ownership with Kubelet.\n - `\"File\"` A file must exist at the given path\n - `\"FileOrCreate\"` If nothing exists at the given path, an empty file will be created there as needed with file mode 0644, having the same group and ownership with Kubelet.\n - `\"Socket\"` A UNIX socket must exist at the given path", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"", "BlockDevice", "CharDevice", "Directory", "DirectoryOrCreate", "File", "FileOrCreate", "Socket"}, - }, - }, - }, - Required: []string{"path"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ISCSIPersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ISCSIPersistentVolumeSource represents an ISCSI disk. ISCSI volumes can only be mounted as read/write once. ISCSI volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "targetPortal": { - SchemaProps: spec.SchemaProps{ - Description: "targetPortal is iSCSI Target Portal. The Portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260).", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "iqn": { - SchemaProps: spec.SchemaProps{ - Description: "iqn is Target iSCSI Qualified Name.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "lun": { - SchemaProps: spec.SchemaProps{ - Description: "lun is iSCSI Target Lun number.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "iscsiInterface": { - SchemaProps: spec.SchemaProps{ - Description: "iscsiInterface is the interface Name that uses an iSCSI transport. Defaults to 'default' (tcp).", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#iscsi", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "portals": { - SchemaProps: spec.SchemaProps{ - Description: "portals is the iSCSI Target Portal List. The Portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260).", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "chapAuthDiscovery": { - SchemaProps: spec.SchemaProps{ - Description: "chapAuthDiscovery defines whether support iSCSI Discovery CHAP authentication", - Type: []string{"boolean"}, - Format: "", - }, - }, - "chapAuthSession": { - SchemaProps: spec.SchemaProps{ - Description: "chapAuthSession defines whether support iSCSI Session CHAP authentication", - Type: []string{"boolean"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef is the CHAP Secret for iSCSI target and initiator authentication", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - "initiatorName": { - SchemaProps: spec.SchemaProps{ - Description: "initiatorName is the custom iSCSI Initiator Name. If initiatorName is specified with iscsiInterface simultaneously, new iSCSI interface : will be created for the connection.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"targetPortal", "iqn", "lun"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.SecretReference"}, - } -} - -func schema_k8sio_api_core_v1_ISCSIVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents an ISCSI disk. ISCSI volumes can only be mounted as read/write once. ISCSI volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "targetPortal": { - SchemaProps: spec.SchemaProps{ - Description: "targetPortal is iSCSI Target Portal. The Portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260).", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "iqn": { - SchemaProps: spec.SchemaProps{ - Description: "iqn is the target iSCSI Qualified Name.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "lun": { - SchemaProps: spec.SchemaProps{ - Description: "lun represents iSCSI Target Lun number.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "iscsiInterface": { - SchemaProps: spec.SchemaProps{ - Description: "iscsiInterface is the interface Name that uses an iSCSI transport. Defaults to 'default' (tcp).", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#iscsi", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "portals": { - SchemaProps: spec.SchemaProps{ - Description: "portals is the iSCSI Target Portal List. The portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260).", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "chapAuthDiscovery": { - SchemaProps: spec.SchemaProps{ - Description: "chapAuthDiscovery defines whether support iSCSI Discovery CHAP authentication", - Type: []string{"boolean"}, - Format: "", - }, - }, - "chapAuthSession": { - SchemaProps: spec.SchemaProps{ - Description: "chapAuthSession defines whether support iSCSI Session CHAP authentication", - Type: []string{"boolean"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef is the CHAP Secret for iSCSI target and initiator authentication", - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - "initiatorName": { - SchemaProps: spec.SchemaProps{ - Description: "initiatorName is the custom iSCSI Initiator Name. If initiatorName is specified with iscsiInterface simultaneously, new iSCSI interface : will be created for the connection.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"targetPortal", "iqn", "lun"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LocalObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_KeyToPath(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Maps a string key to a path within a volume.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "key": { - SchemaProps: spec.SchemaProps{ - Description: "key is the key to project.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "path is the relative path of the file to map the key to. May not be an absolute path. May not contain the path element '..'. May not start with the string '..'.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "mode": { - SchemaProps: spec.SchemaProps{ - Description: "mode is Optional: mode bits used to set permissions on this file. Must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - Required: []string{"key", "path"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_Lifecycle(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Lifecycle describes actions that the management system should take in response to container lifecycle events. For the PostStart and PreStop lifecycle handlers, management of the container blocks until the action is complete, unless the container process fails, in which case the handler is aborted.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "postStart": { - SchemaProps: spec.SchemaProps{ - Description: "PostStart is called immediately after a container is created. If the handler fails, the container is terminated and restarted according to its restart policy. Other management of the container blocks until the hook completes. More info: https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks", - Ref: ref("k8s.io/api/core/v1.LifecycleHandler"), - }, - }, - "preStop": { - SchemaProps: spec.SchemaProps{ - Description: "PreStop is called immediately before a container is terminated due to an API request or management event such as liveness/startup probe failure, preemption, resource contention, etc. The handler is not called if the container crashes or exits. The Pod's termination grace period countdown begins before the PreStop hook is executed. Regardless of the outcome of the handler, the container will eventually terminate within the Pod's termination grace period (unless delayed by finalizers). Other management of the container blocks until the hook completes or until the termination grace period is reached. More info: https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks", - Ref: ref("k8s.io/api/core/v1.LifecycleHandler"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LifecycleHandler"}, - } -} - -func schema_k8sio_api_core_v1_LifecycleHandler(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "LifecycleHandler defines a specific action that should be taken in a lifecycle hook. One and only one of the fields, except TCPSocket must be specified.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "exec": { - SchemaProps: spec.SchemaProps{ - Description: "Exec specifies the action to take.", - Ref: ref("k8s.io/api/core/v1.ExecAction"), - }, - }, - "httpGet": { - SchemaProps: spec.SchemaProps{ - Description: "HTTPGet specifies the http request to perform.", - Ref: ref("k8s.io/api/core/v1.HTTPGetAction"), - }, - }, - "tcpSocket": { - SchemaProps: spec.SchemaProps{ - Description: "Deprecated. TCPSocket is NOT supported as a LifecycleHandler and kept for the backward compatibility. There are no validation of this field and lifecycle hooks will fail in runtime when tcp handler is specified.", - Ref: ref("k8s.io/api/core/v1.TCPSocketAction"), - }, - }, - "sleep": { - SchemaProps: spec.SchemaProps{ - Description: "Sleep represents the duration that the container should sleep before being terminated.", - Ref: ref("k8s.io/api/core/v1.SleepAction"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ExecAction", "k8s.io/api/core/v1.HTTPGetAction", "k8s.io/api/core/v1.SleepAction", "k8s.io/api/core/v1.TCPSocketAction"}, - } -} - -func schema_k8sio_api_core_v1_LimitRange(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "LimitRange sets resource usage limits for each kind of resource in a Namespace.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Spec defines the limits enforced. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.LimitRangeSpec"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LimitRangeSpec", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_LimitRangeItem(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "LimitRangeItem defines a min/max usage limit for any resource that matches on kind.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of resource that this limit applies to.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "max": { - SchemaProps: spec.SchemaProps{ - Description: "Max usage constraints on this kind by resource name.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "min": { - SchemaProps: spec.SchemaProps{ - Description: "Min usage constraints on this kind by resource name.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "default": { - SchemaProps: spec.SchemaProps{ - Description: "Default resource requirement limit value by resource name if resource limit is omitted.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "defaultRequest": { - SchemaProps: spec.SchemaProps{ - Description: "DefaultRequest is the default resource requirement request value by resource name if resource request is omitted.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "maxLimitRequestRatio": { - SchemaProps: spec.SchemaProps{ - Description: "MaxLimitRequestRatio if specified, the named resource must have a request and limit that are both non-zero where limit divided by request is less than or equal to the enumerated value; this represents the max burst for the named resource.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - }, - Required: []string{"type"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_LimitRangeList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "LimitRangeList is a list of LimitRange items.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is a list of LimitRange objects. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.LimitRange"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LimitRange", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_LimitRangeSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "LimitRangeSpec defines a min/max usage limit for resources that match on kind.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "limits": { - SchemaProps: spec.SchemaProps{ - Description: "Limits is the list of LimitRangeItem objects that are enforced.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.LimitRangeItem"), - }, - }, - }, - }, - }, - }, - Required: []string{"limits"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LimitRangeItem"}, - } -} - -func schema_k8sio_api_core_v1_List(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "List holds a list of objects, which may not be known by the server.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of objects", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/runtime.RawExtension"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "k8s.io/apimachinery/pkg/runtime.RawExtension"}, - } -} - -func schema_k8sio_api_core_v1_LoadBalancerIngress(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "LoadBalancerIngress represents the status of a load-balancer ingress point: traffic intended for the service should be sent to an ingress point.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "ip": { - SchemaProps: spec.SchemaProps{ - Description: "IP is set for load-balancer ingress points that are IP based (typically GCE or OpenStack load-balancers)", - Type: []string{"string"}, - Format: "", - }, - }, - "hostname": { - SchemaProps: spec.SchemaProps{ - Description: "Hostname is set for load-balancer ingress points that are DNS based (typically AWS load-balancers)", - Type: []string{"string"}, - Format: "", - }, - }, - "ipMode": { - SchemaProps: spec.SchemaProps{ - Description: "IPMode specifies how the load-balancer IP behaves, and may only be specified when the ip field is specified. Setting this to \"VIP\" indicates that traffic is delivered to the node with the destination set to the load-balancer's IP and port. Setting this to \"Proxy\" indicates that traffic is delivered to the node or pod with the destination set to the node's IP and node port or the pod's IP and port. Service implementations may use this information to adjust traffic routing.", - Type: []string{"string"}, - Format: "", - }, - }, - "ports": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Ports is a list of records of service ports If used, every port defined in the service should have an entry in it", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PortStatus"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PortStatus"}, - } -} - -func schema_k8sio_api_core_v1_LoadBalancerStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "LoadBalancerStatus represents the status of a load-balancer.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "ingress": { - SchemaProps: spec.SchemaProps{ - Description: "Ingress is a list containing ingress points for the load-balancer. Traffic intended for the service should be sent to these ingress points.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.LoadBalancerIngress"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LoadBalancerIngress"}, - } -} - -func schema_k8sio_api_core_v1_LocalObjectReference(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "LocalObjectReference contains enough information to let you locate the referenced object inside the same namespace.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_LocalVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Local represents directly-attached storage with node affinity (Beta feature)", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "path": { - SchemaProps: spec.SchemaProps{ - Description: "path of the full path to the volume on the node. It can be either a directory or block device (disk, partition, ...).", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type to mount. It applies only when the Path is a block device. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". The default value is to auto-select a filesystem if unspecified.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"path"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ModifyVolumeStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ModifyVolumeStatus represents the status object of ControllerModifyVolume operation", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "targetVolumeAttributesClassName": { - SchemaProps: spec.SchemaProps{ - Description: "targetVolumeAttributesClassName is the name of the VolumeAttributesClass the PVC currently being reconciled", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "status is the status of the ControllerModifyVolume operation. It can be in any of following states:\n - Pending\n Pending indicates that the PersistentVolumeClaim cannot be modified due to unmet requirements, such as\n the specified VolumeAttributesClass not existing.\n - InProgress\n InProgress indicates that the volume is being modified.\n - Infeasible\n Infeasible indicates that the request has been rejected as invalid by the CSI driver. To\n\t resolve the error, a valid VolumeAttributesClass needs to be specified.\nNote: New statuses can be added in the future. Consumers should check for unknown statuses and fail appropriately.\n\nPossible enum values:\n - `\"InProgress\"` InProgress indicates that the volume is being modified\n - `\"Infeasible\"` Infeasible indicates that the request has been rejected as invalid by the CSI driver. To resolve the error, a valid VolumeAttributesClass needs to be specified\n - `\"Pending\"` Pending indicates that the PersistentVolumeClaim cannot be modified due to unmet requirements, such as the specified VolumeAttributesClass not existing", - Default: "", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"InProgress", "Infeasible", "Pending"}, - }, - }, - }, - Required: []string{"status"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_NFSVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents an NFS mount that lasts the lifetime of a pod. NFS volumes do not support ownership management or SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "server": { - SchemaProps: spec.SchemaProps{ - Description: "server is the hostname or IP address of the NFS server. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "path that is exported by the NFS server. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly here will force the NFS export to be mounted with read-only permissions. Defaults to false. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"server", "path"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_Namespace(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Namespace provides a scope for Names. Use of multiple namespaces is optional.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Spec defines the behavior of the Namespace. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NamespaceSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status describes the current status of a Namespace. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NamespaceStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NamespaceSpec", "k8s.io/api/core/v1.NamespaceStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_NamespaceCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NamespaceCondition contains details about state of namespace.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of namespace controller condition.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status of the condition, one of True, False, Unknown.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "lastTransitionTime": { - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_NamespaceList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NamespaceList is a list of Namespaces.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is the list of Namespace objects in the list. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Namespace"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.Namespace", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_NamespaceSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NamespaceSpec describes the attributes on a Namespace.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "finalizers": { - SchemaProps: spec.SchemaProps{ - Description: "Finalizers is an opaque list of values that must be empty to permanently remove object from storage. More info: https://kubernetes.io/docs/tasks/administer-cluster/namespaces/", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_NamespaceStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NamespaceStatus is information about the current status of a Namespace.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "phase": { - SchemaProps: spec.SchemaProps{ - Description: "Phase is the current lifecycle phase of the namespace. More info: https://kubernetes.io/docs/tasks/administer-cluster/namespaces/\n\nPossible enum values:\n - `\"Active\"` means the namespace is available for use in the system\n - `\"Terminating\"` means the namespace is undergoing graceful termination", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Active", "Terminating"}, - }, - }, - "conditions": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Represents the latest available observations of a namespace's current state.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NamespaceCondition"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NamespaceCondition"}, - } -} - -func schema_k8sio_api_core_v1_Node(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Node is a worker node in Kubernetes. Each node will have a unique identifier in the cache (i.e. in etcd).", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Spec defines the behavior of a node. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NodeSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Most recently observed status of the node. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NodeStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NodeSpec", "k8s.io/api/core/v1.NodeStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_NodeAddress(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeAddress contains information for the node's address.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Node address type, one of Hostname, ExternalIP or InternalIP.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "address": { - SchemaProps: spec.SchemaProps{ - Description: "The node address.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "address"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_NodeAffinity(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Node affinity is a group of node affinity scheduling rules.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "requiredDuringSchedulingIgnoredDuringExecution": { - SchemaProps: spec.SchemaProps{ - Description: "If the affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to an update), the system may or may not try to eventually evict the pod from its node.", - Ref: ref("k8s.io/api/core/v1.NodeSelector"), - }, - }, - "preferredDuringSchedulingIgnoredDuringExecution": { - SchemaProps: spec.SchemaProps{ - Description: "The scheduler will prefer to schedule pods to nodes that satisfy the affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding \"weight\" to the sum if the node matches the corresponding matchExpressions; the node(s) with the highest sum are the most preferred.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PreferredSchedulingTerm"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NodeSelector", "k8s.io/api/core/v1.PreferredSchedulingTerm"}, - } -} - -func schema_k8sio_api_core_v1_NodeCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeCondition contains condition information for a node.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of node condition.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status of the condition, one of True, False, Unknown.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "lastHeartbeatTime": { - SchemaProps: spec.SchemaProps{ - Description: "Last time we got an update on a given condition.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "lastTransitionTime": { - SchemaProps: spec.SchemaProps{ - Description: "Last time the condition transit from one status to another.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "(brief) reason for the condition's last transition.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "Human readable message indicating details about last transition.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_NodeConfigSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeConfigSource specifies a source of node configuration. Exactly one subfield (excluding metadata) must be non-nil. This API is deprecated since 1.22", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "configMap": { - SchemaProps: spec.SchemaProps{ - Description: "ConfigMap is a reference to a Node's ConfigMap", - Ref: ref("k8s.io/api/core/v1.ConfigMapNodeConfigSource"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ConfigMapNodeConfigSource"}, - } -} - -func schema_k8sio_api_core_v1_NodeConfigStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeConfigStatus describes the status of the config assigned by Node.Spec.ConfigSource.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "assigned": { - SchemaProps: spec.SchemaProps{ - Description: "Assigned reports the checkpointed config the node will try to use. When Node.Spec.ConfigSource is updated, the node checkpoints the associated config payload to local disk, along with a record indicating intended config. The node refers to this record to choose its config checkpoint, and reports this record in Assigned. Assigned only updates in the status after the record has been checkpointed to disk. When the Kubelet is restarted, it tries to make the Assigned config the Active config by loading and validating the checkpointed payload identified by Assigned.", - Ref: ref("k8s.io/api/core/v1.NodeConfigSource"), - }, - }, - "active": { - SchemaProps: spec.SchemaProps{ - Description: "Active reports the checkpointed config the node is actively using. Active will represent either the current version of the Assigned config, or the current LastKnownGood config, depending on whether attempting to use the Assigned config results in an error.", - Ref: ref("k8s.io/api/core/v1.NodeConfigSource"), - }, - }, - "lastKnownGood": { - SchemaProps: spec.SchemaProps{ - Description: "LastKnownGood reports the checkpointed config the node will fall back to when it encounters an error attempting to use the Assigned config. The Assigned config becomes the LastKnownGood config when the node determines that the Assigned config is stable and correct. This is currently implemented as a 10-minute soak period starting when the local record of Assigned config is updated. If the Assigned config is Active at the end of this period, it becomes the LastKnownGood. Note that if Spec.ConfigSource is reset to nil (use local defaults), the LastKnownGood is also immediately reset to nil, because the local default config is always assumed good. You should not make assumptions about the node's method of determining config stability and correctness, as this may change or become configurable in the future.", - Ref: ref("k8s.io/api/core/v1.NodeConfigSource"), - }, - }, - "error": { - SchemaProps: spec.SchemaProps{ - Description: "Error describes any problems reconciling the Spec.ConfigSource to the Active config. Errors may occur, for example, attempting to checkpoint Spec.ConfigSource to the local Assigned record, attempting to checkpoint the payload associated with Spec.ConfigSource, attempting to load or validate the Assigned config, etc. Errors may occur at different points while syncing config. Earlier errors (e.g. download or checkpointing errors) will not result in a rollback to LastKnownGood, and may resolve across Kubelet retries. Later errors (e.g. loading or validating a checkpointed config) will result in a rollback to LastKnownGood. In the latter case, it is usually possible to resolve the error by fixing the config assigned in Spec.ConfigSource. You can find additional information for debugging by searching the error message in the Kubelet log. Error is a human-readable description of the error state; machines can check whether or not Error is empty, but should not rely on the stability of the Error text across Kubelet versions.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NodeConfigSource"}, - } -} - -func schema_k8sio_api_core_v1_NodeDaemonEndpoints(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeDaemonEndpoints lists ports opened by daemons running on the Node.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kubeletEndpoint": { - SchemaProps: spec.SchemaProps{ - Description: "Endpoint on which Kubelet is listening.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.DaemonEndpoint"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.DaemonEndpoint"}, - } -} - -func schema_k8sio_api_core_v1_NodeList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeList is the whole list of all Nodes which have been registered with master.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of nodes", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Node"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.Node", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_NodeProxyOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeProxyOptions is the query options to a Node's proxy call.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "Path is the URL path to use for the current proxy request to node.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_NodeResources(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeResources is an object for conveying resource information about a node. see https://kubernetes.io/docs/concepts/architecture/nodes/#capacity for more details.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "Capacity": { - SchemaProps: spec.SchemaProps{ - Description: "Capacity represents the available resources of a node", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - }, - Required: []string{"Capacity"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_NodeSelector(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A node selector represents the union of the results of one or more label queries over a set of nodes; that is, it represents the OR of the selectors represented by the node selector terms.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "nodeSelectorTerms": { - SchemaProps: spec.SchemaProps{ - Description: "Required. A list of node selector terms. The terms are ORed.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NodeSelectorTerm"), - }, - }, - }, - }, - }, - }, - Required: []string{"nodeSelectorTerms"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NodeSelectorTerm"}, - } -} - -func schema_k8sio_api_core_v1_NodeSelectorRequirement(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A node selector requirement is a selector that contains values, a key, and an operator that relates the key and values.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "key": { - SchemaProps: spec.SchemaProps{ - Description: "The label key that the selector applies to.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "operator": { - SchemaProps: spec.SchemaProps{ - Description: "Represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt.\n\nPossible enum values:\n - `\"DoesNotExist\"`\n - `\"Exists\"`\n - `\"Gt\"`\n - `\"In\"`\n - `\"Lt\"`\n - `\"NotIn\"`", - Default: "", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"DoesNotExist", "Exists", "Gt", "In", "Lt", "NotIn"}, - }, - }, - "values": { - SchemaProps: spec.SchemaProps{ - Description: "An array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. If the operator is Gt or Lt, the values array must have a single element, which will be interpreted as an integer. This array is replaced during a strategic merge patch.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"key", "operator"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_NodeSelectorTerm(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A null or empty node selector term matches no objects. The requirements of them are ANDed. The TopologySelectorTerm type implements a subset of the NodeSelectorTerm.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "matchExpressions": { - SchemaProps: spec.SchemaProps{ - Description: "A list of node selector requirements by node's labels.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NodeSelectorRequirement"), - }, - }, - }, - }, - }, - "matchFields": { - SchemaProps: spec.SchemaProps{ - Description: "A list of node selector requirements by node's fields.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NodeSelectorRequirement"), - }, - }, - }, - }, - }, - }, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NodeSelectorRequirement"}, - } -} - -func schema_k8sio_api_core_v1_NodeSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeSpec describes the attributes that a node is created with.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "podCIDR": { - SchemaProps: spec.SchemaProps{ - Description: "PodCIDR represents the pod IP range assigned to the node.", - Type: []string{"string"}, - Format: "", - }, - }, - "podCIDRs": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "podCIDRs represents the IP ranges assigned to the node for usage by Pods on that node. If this field is specified, the 0th entry must match the podCIDR field. It may contain at most 1 value for each of IPv4 and IPv6.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "providerID": { - SchemaProps: spec.SchemaProps{ - Description: "ID of the node assigned by the cloud provider in the format: ://", - Type: []string{"string"}, - Format: "", - }, - }, - "unschedulable": { - SchemaProps: spec.SchemaProps{ - Description: "Unschedulable controls node schedulability of new pods. By default, node is schedulable. More info: https://kubernetes.io/docs/concepts/nodes/node/#manual-node-administration", - Type: []string{"boolean"}, - Format: "", - }, - }, - "taints": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, the node's taints.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Taint"), - }, - }, - }, - }, - }, - "configSource": { - SchemaProps: spec.SchemaProps{ - Description: "Deprecated: Previously used to specify the source of the node's configuration for the DynamicKubeletConfig feature. This feature is removed.", - Ref: ref("k8s.io/api/core/v1.NodeConfigSource"), - }, - }, - "externalID": { - SchemaProps: spec.SchemaProps{ - Description: "Deprecated. Not all kubelets will set this field. Remove field after 1.13. see: https://issues.k8s.io/61966", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NodeConfigSource", "k8s.io/api/core/v1.Taint"}, - } -} - -func schema_k8sio_api_core_v1_NodeStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeStatus is information about the current status of a node.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "capacity": { - SchemaProps: spec.SchemaProps{ - Description: "Capacity represents the total resources of a node. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#capacity", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "allocatable": { - SchemaProps: spec.SchemaProps{ - Description: "Allocatable represents the resources of a node that are available for scheduling. Defaults to Capacity.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "phase": { - SchemaProps: spec.SchemaProps{ - Description: "NodePhase is the recently observed lifecycle phase of the node. More info: https://kubernetes.io/docs/concepts/nodes/node/#phase The field is never populated, and now is deprecated.\n\nPossible enum values:\n - `\"Pending\"` means the node has been created/added by the system, but not configured.\n - `\"Running\"` means the node has been configured and has Kubernetes components running.\n - `\"Terminated\"` means the node has been removed from the cluster.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Pending", "Running", "Terminated"}, - }, - }, - "conditions": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Conditions is an array of current observed node conditions. More info: https://kubernetes.io/docs/concepts/nodes/node/#condition", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NodeCondition"), - }, - }, - }, - }, - }, - "addresses": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of addresses reachable to the node. Queried from cloud provider, if available. More info: https://kubernetes.io/docs/concepts/nodes/node/#addresses Note: This field is declared as mergeable, but the merge key is not sufficiently unique, which can cause data corruption when it is merged. Callers should instead use a full-replacement patch. See https://pr.k8s.io/79391 for an example. Consumers should assume that addresses can change during the lifetime of a Node. However, there are some exceptions where this may not be possible, such as Pods that inherit a Node's address in its own status or consumers of the downward API (status.hostIP).", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NodeAddress"), - }, - }, - }, - }, - }, - "daemonEndpoints": { - SchemaProps: spec.SchemaProps{ - Description: "Endpoints of daemons running on the Node.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NodeDaemonEndpoints"), - }, - }, - "nodeInfo": { - SchemaProps: spec.SchemaProps{ - Description: "Set of ids/uuids to uniquely identify the node. More info: https://kubernetes.io/docs/concepts/nodes/node/#info", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NodeSystemInfo"), - }, - }, - "images": { - SchemaProps: spec.SchemaProps{ - Description: "List of container images on this node", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerImage"), - }, - }, - }, - }, - }, - "volumesInUse": { - SchemaProps: spec.SchemaProps{ - Description: "List of attachable volumes in use (mounted) by the node.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "volumesAttached": { - SchemaProps: spec.SchemaProps{ - Description: "List of volumes that are attached to the node.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.AttachedVolume"), - }, - }, - }, - }, - }, - "config": { - SchemaProps: spec.SchemaProps{ - Description: "Status of the config assigned to the node via the dynamic Kubelet config feature.", - Ref: ref("k8s.io/api/core/v1.NodeConfigStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.AttachedVolume", "k8s.io/api/core/v1.ContainerImage", "k8s.io/api/core/v1.NodeAddress", "k8s.io/api/core/v1.NodeCondition", "k8s.io/api/core/v1.NodeConfigStatus", "k8s.io/api/core/v1.NodeDaemonEndpoints", "k8s.io/api/core/v1.NodeSystemInfo", "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_NodeSystemInfo(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "NodeSystemInfo is a set of ids/uuids to uniquely identify the node.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "machineID": { - SchemaProps: spec.SchemaProps{ - Description: "MachineID reported by the node. For unique machine identification in the cluster this field is preferred. Learn more from man(5) machine-id: http://man7.org/linux/man-pages/man5/machine-id.5.html", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "systemUUID": { - SchemaProps: spec.SchemaProps{ - Description: "SystemUUID reported by the node. For unique machine identification MachineID is preferred. This field is specific to Red Hat hosts https://access.redhat.com/documentation/en-us/red_hat_subscription_management/1/html/rhsm/uuid", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "bootID": { - SchemaProps: spec.SchemaProps{ - Description: "Boot ID reported by the node.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "kernelVersion": { - SchemaProps: spec.SchemaProps{ - Description: "Kernel Version reported by the node from 'uname -r' (e.g. 3.16.0-0.bpo.4-amd64).", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "osImage": { - SchemaProps: spec.SchemaProps{ - Description: "OS Image reported by the node from /etc/os-release (e.g. Debian GNU/Linux 7 (wheezy)).", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "containerRuntimeVersion": { - SchemaProps: spec.SchemaProps{ - Description: "ContainerRuntime Version reported by the node through runtime remote API (e.g. containerd://1.4.2).", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "kubeletVersion": { - SchemaProps: spec.SchemaProps{ - Description: "Kubelet Version reported by the node.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "kubeProxyVersion": { - SchemaProps: spec.SchemaProps{ - Description: "KubeProxy Version reported by the node.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "operatingSystem": { - SchemaProps: spec.SchemaProps{ - Description: "The Operating System reported by the node", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "architecture": { - SchemaProps: spec.SchemaProps{ - Description: "The Architecture reported by the node", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"machineID", "systemUUID", "bootID", "kernelVersion", "osImage", "containerRuntimeVersion", "kubeletVersion", "kubeProxyVersion", "operatingSystem", "architecture"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ObjectFieldSelector(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ObjectFieldSelector selects an APIVersioned field of an object.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "Version of the schema the FieldPath is written in terms of, defaults to \"v1\".", - Type: []string{"string"}, - Format: "", - }, - }, - "fieldPath": { - SchemaProps: spec.SchemaProps{ - Description: "Path of the field to select in the specified API version.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"fieldPath"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ObjectReference(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ObjectReference contains enough information to let you inspect or modify the referred object.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "namespace": { - SchemaProps: spec.SchemaProps{ - Description: "Namespace of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/", - Type: []string{"string"}, - Format: "", - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Type: []string{"string"}, - Format: "", - }, - }, - "uid": { - SchemaProps: spec.SchemaProps{ - Description: "UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#uids", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "API version of the referent.", - Type: []string{"string"}, - Format: "", - }, - }, - "resourceVersion": { - SchemaProps: spec.SchemaProps{ - Description: "Specific resourceVersion to which this reference is made, if any. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency", - Type: []string{"string"}, - Format: "", - }, - }, - "fieldPath": { - SchemaProps: spec.SchemaProps{ - Description: "If referring to a piece of an object instead of an entire object, this string should contain a valid JSON/Go field access statement, such as desiredState.manifest.containers[2]. For example, if the object reference is to a container within a pod, this would take on a value like: \"spec.containers{name}\" (where \"name\" refers to the name of the container that triggered the event) or if no container name is specified \"spec.containers[2]\" (container with index 2 in this pod). This syntax is chosen only to have some well-defined way of referencing a part of an object.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PersistentVolume(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolume (PV) is a storage resource provisioned by an administrator. It is analogous to a node. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "spec defines a specification of a persistent volume owned by the cluster. Provisioned by an administrator. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistent-volumes", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PersistentVolumeSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "status represents the current information/status for the persistent volume. Populated by the system. Read-only. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistent-volumes", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PersistentVolumeStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PersistentVolumeSpec", "k8s.io/api/core/v1.PersistentVolumeStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeClaim(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeClaim is a user's request for and claim to a persistent volume", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "spec defines the desired characteristics of a volume requested by a pod author. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PersistentVolumeClaimSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "status represents the current information/status of a persistent volume claim. Read-only. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PersistentVolumeClaimStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PersistentVolumeClaimSpec", "k8s.io/api/core/v1.PersistentVolumeClaimStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeClaimCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeClaimCondition contains details about state of pvc", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "lastProbeTime": { - SchemaProps: spec.SchemaProps{ - Description: "lastProbeTime is the time we probed the condition.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "lastTransitionTime": { - SchemaProps: spec.SchemaProps{ - Description: "lastTransitionTime is the time the condition transitioned from one status to another.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "reason is a unique, this should be a short, machine understandable string that gives the reason for condition's last transition. If it reports \"ResizeStarted\" that means the underlying persistent volume is being resized.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "message is the human-readable message indicating details about last transition.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeClaimList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeClaimList is a list of PersistentVolumeClaim items.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "items is a list of persistent volume claims. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PersistentVolumeClaim"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PersistentVolumeClaim", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeClaimSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeClaimSpec describes the common attributes of storage devices and allows a Source for provider-specific attributes", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "accessModes": { - SchemaProps: spec.SchemaProps{ - Description: "accessModes contains the desired access modes the volume should have. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#access-modes-1", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "selector": { - SchemaProps: spec.SchemaProps{ - Description: "selector is a label query over volumes to consider for binding.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), - }, - }, - "resources": { - SchemaProps: spec.SchemaProps{ - Description: "resources represents the minimum resources the volume should have. If RecoverVolumeExpansionFailure feature is enabled users are allowed to specify resource requirements that are lower than previous value but must still be higher than capacity recorded in the status field of the claim. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#resources", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.VolumeResourceRequirements"), - }, - }, - "volumeName": { - SchemaProps: spec.SchemaProps{ - Description: "volumeName is the binding reference to the PersistentVolume backing this claim.", - Type: []string{"string"}, - Format: "", - }, - }, - "storageClassName": { - SchemaProps: spec.SchemaProps{ - Description: "storageClassName is the name of the StorageClass required by the claim. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#class-1", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeMode": { - SchemaProps: spec.SchemaProps{ - Description: "volumeMode defines what type of volume is required by the claim. Value of Filesystem is implied when not included in claim spec.\n\nPossible enum values:\n - `\"Block\"` means the volume will not be formatted with a filesystem and will remain a raw block device.\n - `\"Filesystem\"` means the volume will be or is formatted with a filesystem.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Block", "Filesystem"}, - }, - }, - "dataSource": { - SchemaProps: spec.SchemaProps{ - Description: "dataSource field can be used to specify either: * An existing VolumeSnapshot object (snapshot.storage.k8s.io/VolumeSnapshot) * An existing PVC (PersistentVolumeClaim) If the provisioner or an external controller can support the specified data source, it will create a new volume based on the contents of the specified data source. When the AnyVolumeDataSource feature gate is enabled, dataSource contents will be copied to dataSourceRef, and dataSourceRef contents will be copied to dataSource when dataSourceRef.namespace is not specified. If the namespace is specified, then dataSourceRef will not be copied to dataSource.", - Ref: ref("k8s.io/api/core/v1.TypedLocalObjectReference"), - }, - }, - "dataSourceRef": { - SchemaProps: spec.SchemaProps{ - Description: "dataSourceRef specifies the object from which to populate the volume with data, if a non-empty volume is desired. This may be any object from a non-empty API group (non core object) or a PersistentVolumeClaim object. When this field is specified, volume binding will only succeed if the type of the specified object matches some installed volume populator or dynamic provisioner. This field will replace the functionality of the dataSource field and as such if both fields are non-empty, they must have the same value. For backwards compatibility, when namespace isn't specified in dataSourceRef, both fields (dataSource and dataSourceRef) will be set to the same value automatically if one of them is empty and the other is non-empty. When namespace is specified in dataSourceRef, dataSource isn't set to the same value and must be empty. There are three important differences between dataSource and dataSourceRef: * While dataSource only allows two specific types of objects, dataSourceRef\n allows any non-core object, as well as PersistentVolumeClaim objects.\n* While dataSource ignores disallowed values (dropping them), dataSourceRef\n preserves all values, and generates an error if a disallowed value is\n specified.\n* While dataSource only allows local objects, dataSourceRef allows objects\n in any namespaces.\n(Beta) Using this field requires the AnyVolumeDataSource feature gate to be enabled. (Alpha) Using the namespace field of dataSourceRef requires the CrossNamespaceVolumeDataSource feature gate to be enabled.", - Ref: ref("k8s.io/api/core/v1.TypedObjectReference"), - }, - }, - "volumeAttributesClassName": { - SchemaProps: spec.SchemaProps{ - Description: "volumeAttributesClassName may be used to set the VolumeAttributesClass used by this claim. If specified, the CSI driver will create or update the volume with the attributes defined in the corresponding VolumeAttributesClass. This has a different purpose than storageClassName, it can be changed after the claim is created. An empty string value means that no VolumeAttributesClass will be applied to the claim but it's not allowed to reset this field to empty string once it is set. If unspecified and the PersistentVolumeClaim is unbound, the default VolumeAttributesClass will be set by the persistentvolume controller if it exists. If the resource referred to by volumeAttributesClass does not exist, this PersistentVolumeClaim will be set to a Pending state, as reflected by the modifyVolumeStatus field, until such as a resource exists. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#volumeattributesclass (Alpha) Using this field requires the VolumeAttributesClass feature gate to be enabled.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.TypedLocalObjectReference", "k8s.io/api/core/v1.TypedObjectReference", "k8s.io/api/core/v1.VolumeResourceRequirements", "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"}, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeClaimStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeClaimStatus is the current status of a persistent volume claim.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "phase": { - SchemaProps: spec.SchemaProps{ - Description: "phase represents the current phase of PersistentVolumeClaim.\n\nPossible enum values:\n - `\"Bound\"` used for PersistentVolumeClaims that are bound\n - `\"Lost\"` used for PersistentVolumeClaims that lost their underlying PersistentVolume. The claim was bound to a PersistentVolume and this volume does not exist any longer and all data on it was lost.\n - `\"Pending\"` used for PersistentVolumeClaims that are not yet bound", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Bound", "Lost", "Pending"}, - }, - }, - "accessModes": { - SchemaProps: spec.SchemaProps{ - Description: "accessModes contains the actual access modes the volume backing the PVC has. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#access-modes-1", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "capacity": { - SchemaProps: spec.SchemaProps{ - Description: "capacity represents the actual resources of the underlying volume.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "conditions": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "conditions is the current Condition of persistent volume claim. If underlying persistent volume is being resized then the Condition will be set to 'ResizeStarted'.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PersistentVolumeClaimCondition"), - }, - }, - }, - }, - }, - "allocatedResources": { - SchemaProps: spec.SchemaProps{ - Description: "allocatedResources tracks the resources allocated to a PVC including its capacity. Key names follow standard Kubernetes label syntax. Valid values are either:\n\t* Un-prefixed keys:\n\t\t- storage - the capacity of the volume.\n\t* Custom resources must use implementation-defined prefixed names such as \"example.com/my-custom-resource\"\nApart from above values - keys that are unprefixed or have kubernetes.io prefix are considered reserved and hence may not be used.\n\nCapacity reported here may be larger than the actual capacity when a volume expansion operation is requested. For storage quota, the larger value from allocatedResources and PVC.spec.resources is used. If allocatedResources is not set, PVC.spec.resources alone is used for quota calculation. If a volume expansion capacity request is lowered, allocatedResources is only lowered if there are no expansion operations in progress and if the actual volume capacity is equal or lower than the requested capacity.\n\nA controller that receives PVC update with previously unknown resourceName should ignore the update for the purpose it was designed. For example - a controller that only is responsible for resizing capacity of the volume, should ignore PVC updates that change other valid resources associated with PVC.\n\nThis is an alpha field and requires enabling RecoverVolumeExpansionFailure feature.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "allocatedResourceStatuses": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "granular", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "allocatedResourceStatuses stores status of resource being resized for the given PVC. Key names follow standard Kubernetes label syntax. Valid values are either:\n\t* Un-prefixed keys:\n\t\t- storage - the capacity of the volume.\n\t* Custom resources must use implementation-defined prefixed names such as \"example.com/my-custom-resource\"\nApart from above values - keys that are unprefixed or have kubernetes.io prefix are considered reserved and hence may not be used.\n\nClaimResourceStatus can be in any of following states:\n\t- ControllerResizeInProgress:\n\t\tState set when resize controller starts resizing the volume in control-plane.\n\t- ControllerResizeFailed:\n\t\tState set when resize has failed in resize controller with a terminal error.\n\t- NodeResizePending:\n\t\tState set when resize controller has finished resizing the volume but further resizing of\n\t\tvolume is needed on the node.\n\t- NodeResizeInProgress:\n\t\tState set when kubelet starts resizing the volume.\n\t- NodeResizeFailed:\n\t\tState set when resizing has failed in kubelet with a terminal error. Transient errors don't set\n\t\tNodeResizeFailed.\nFor example: if expanding a PVC for more capacity - this field can be one of the following states:\n\t- pvc.status.allocatedResourceStatus['storage'] = \"ControllerResizeInProgress\"\n - pvc.status.allocatedResourceStatus['storage'] = \"ControllerResizeFailed\"\n - pvc.status.allocatedResourceStatus['storage'] = \"NodeResizePending\"\n - pvc.status.allocatedResourceStatus['storage'] = \"NodeResizeInProgress\"\n - pvc.status.allocatedResourceStatus['storage'] = \"NodeResizeFailed\"\nWhen this field is not set, it means that no resize operation is in progress for the given PVC.\n\nA controller that receives PVC update with previously unknown resourceName or ClaimResourceStatus should ignore the update for the purpose it was designed. For example - a controller that only is responsible for resizing capacity of the volume, should ignore PVC updates that change other valid resources associated with PVC.\n\nThis is an alpha field and requires enabling RecoverVolumeExpansionFailure feature.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "currentVolumeAttributesClassName": { - SchemaProps: spec.SchemaProps{ - Description: "currentVolumeAttributesClassName is the current name of the VolumeAttributesClass the PVC is using. When unset, there is no VolumeAttributeClass applied to this PersistentVolumeClaim This is an alpha field and requires enabling VolumeAttributesClass feature.", - Type: []string{"string"}, - Format: "", - }, - }, - "modifyVolumeStatus": { - SchemaProps: spec.SchemaProps{ - Description: "ModifyVolumeStatus represents the status object of ControllerModifyVolume operation. When this is unset, there is no ModifyVolume operation being attempted. This is an alpha field and requires enabling VolumeAttributesClass feature.", - Ref: ref("k8s.io/api/core/v1.ModifyVolumeStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ModifyVolumeStatus", "k8s.io/api/core/v1.PersistentVolumeClaimCondition", "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeClaimTemplate(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeClaimTemplate is used to produce PersistentVolumeClaim objects as part of an EphemeralVolumeSource.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "May contain labels and annotations that will be copied into the PVC when creating it. No other fields are allowed and will be rejected during validation.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "The specification for the PersistentVolumeClaim. The entire content is copied unchanged into the PVC that gets created from this template. The same fields as in a PersistentVolumeClaim are also valid here.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PersistentVolumeClaimSpec"), - }, - }, - }, - Required: []string{"spec"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PersistentVolumeClaimSpec", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeClaimVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeClaimVolumeSource references the user's PVC in the same namespace. This volume finds the bound PV and mounts that volume for the pod. A PersistentVolumeClaimVolumeSource is, essentially, a wrapper around another type of volume that is owned by someone else (the system).", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "claimName": { - SchemaProps: spec.SchemaProps{ - Description: "claimName is the name of a PersistentVolumeClaim in the same namespace as the pod using this volume. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly Will force the ReadOnly setting in VolumeMounts. Default false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"claimName"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeList is a list of PersistentVolume items.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "items is a list of persistent volumes. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PersistentVolume"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PersistentVolume", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeSource is similar to VolumeSource but meant for the administrator who creates PVs. Exactly one of its members must be set.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "gcePersistentDisk": { - SchemaProps: spec.SchemaProps{ - Description: "gcePersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", - Ref: ref("k8s.io/api/core/v1.GCEPersistentDiskVolumeSource"), - }, - }, - "awsElasticBlockStore": { - SchemaProps: spec.SchemaProps{ - Description: "awsElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore", - Ref: ref("k8s.io/api/core/v1.AWSElasticBlockStoreVolumeSource"), - }, - }, - "hostPath": { - SchemaProps: spec.SchemaProps{ - Description: "hostPath represents a directory on the host. Provisioned by a developer or tester. This is useful for single-node development and testing only! On-host storage is not supported in any way and WILL NOT WORK in a multi-node cluster. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath", - Ref: ref("k8s.io/api/core/v1.HostPathVolumeSource"), - }, - }, - "glusterfs": { - SchemaProps: spec.SchemaProps{ - Description: "glusterfs represents a Glusterfs volume that is attached to a host and exposed to the pod. Provisioned by an admin. More info: https://examples.k8s.io/volumes/glusterfs/README.md", - Ref: ref("k8s.io/api/core/v1.GlusterfsPersistentVolumeSource"), - }, - }, - "nfs": { - SchemaProps: spec.SchemaProps{ - Description: "nfs represents an NFS mount on the host. Provisioned by an admin. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs", - Ref: ref("k8s.io/api/core/v1.NFSVolumeSource"), - }, - }, - "rbd": { - SchemaProps: spec.SchemaProps{ - Description: "rbd represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/rbd/README.md", - Ref: ref("k8s.io/api/core/v1.RBDPersistentVolumeSource"), - }, - }, - "iscsi": { - SchemaProps: spec.SchemaProps{ - Description: "iscsi represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin.", - Ref: ref("k8s.io/api/core/v1.ISCSIPersistentVolumeSource"), - }, - }, - "cinder": { - SchemaProps: spec.SchemaProps{ - Description: "cinder represents a cinder volume attached and mounted on kubelets host machine. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - Ref: ref("k8s.io/api/core/v1.CinderPersistentVolumeSource"), - }, - }, - "cephfs": { - SchemaProps: spec.SchemaProps{ - Description: "cephFS represents a Ceph FS mount on the host that shares a pod's lifetime", - Ref: ref("k8s.io/api/core/v1.CephFSPersistentVolumeSource"), - }, - }, - "fc": { - SchemaProps: spec.SchemaProps{ - Description: "fc represents a Fibre Channel resource that is attached to a kubelet's host machine and then exposed to the pod.", - Ref: ref("k8s.io/api/core/v1.FCVolumeSource"), - }, - }, - "flocker": { - SchemaProps: spec.SchemaProps{ - Description: "flocker represents a Flocker volume attached to a kubelet's host machine and exposed to the pod for its usage. This depends on the Flocker control service being running", - Ref: ref("k8s.io/api/core/v1.FlockerVolumeSource"), - }, - }, - "flexVolume": { - SchemaProps: spec.SchemaProps{ - Description: "flexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin.", - Ref: ref("k8s.io/api/core/v1.FlexPersistentVolumeSource"), - }, - }, - "azureFile": { - SchemaProps: spec.SchemaProps{ - Description: "azureFile represents an Azure File Service mount on the host and bind mount to the pod.", - Ref: ref("k8s.io/api/core/v1.AzureFilePersistentVolumeSource"), - }, - }, - "vsphereVolume": { - SchemaProps: spec.SchemaProps{ - Description: "vsphereVolume represents a vSphere volume attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.VsphereVirtualDiskVolumeSource"), - }, - }, - "quobyte": { - SchemaProps: spec.SchemaProps{ - Description: "quobyte represents a Quobyte mount on the host that shares a pod's lifetime", - Ref: ref("k8s.io/api/core/v1.QuobyteVolumeSource"), - }, - }, - "azureDisk": { - SchemaProps: spec.SchemaProps{ - Description: "azureDisk represents an Azure Data Disk mount on the host and bind mount to the pod.", - Ref: ref("k8s.io/api/core/v1.AzureDiskVolumeSource"), - }, - }, - "photonPersistentDisk": { - SchemaProps: spec.SchemaProps{ - Description: "photonPersistentDisk represents a PhotonController persistent disk attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.PhotonPersistentDiskVolumeSource"), - }, - }, - "portworxVolume": { - SchemaProps: spec.SchemaProps{ - Description: "portworxVolume represents a portworx volume attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.PortworxVolumeSource"), - }, - }, - "scaleIO": { - SchemaProps: spec.SchemaProps{ - Description: "scaleIO represents a ScaleIO persistent volume attached and mounted on Kubernetes nodes.", - Ref: ref("k8s.io/api/core/v1.ScaleIOPersistentVolumeSource"), - }, - }, - "local": { - SchemaProps: spec.SchemaProps{ - Description: "local represents directly-attached storage with node affinity", - Ref: ref("k8s.io/api/core/v1.LocalVolumeSource"), - }, - }, - "storageos": { - SchemaProps: spec.SchemaProps{ - Description: "storageOS represents a StorageOS volume that is attached to the kubelet's host machine and mounted into the pod More info: https://examples.k8s.io/volumes/storageos/README.md", - Ref: ref("k8s.io/api/core/v1.StorageOSPersistentVolumeSource"), - }, - }, - "csi": { - SchemaProps: spec.SchemaProps{ - Description: "csi represents storage that is handled by an external CSI driver (Beta feature).", - Ref: ref("k8s.io/api/core/v1.CSIPersistentVolumeSource"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.AWSElasticBlockStoreVolumeSource", "k8s.io/api/core/v1.AzureDiskVolumeSource", "k8s.io/api/core/v1.AzureFilePersistentVolumeSource", "k8s.io/api/core/v1.CSIPersistentVolumeSource", "k8s.io/api/core/v1.CephFSPersistentVolumeSource", "k8s.io/api/core/v1.CinderPersistentVolumeSource", "k8s.io/api/core/v1.FCVolumeSource", "k8s.io/api/core/v1.FlexPersistentVolumeSource", "k8s.io/api/core/v1.FlockerVolumeSource", "k8s.io/api/core/v1.GCEPersistentDiskVolumeSource", "k8s.io/api/core/v1.GlusterfsPersistentVolumeSource", "k8s.io/api/core/v1.HostPathVolumeSource", "k8s.io/api/core/v1.ISCSIPersistentVolumeSource", "k8s.io/api/core/v1.LocalVolumeSource", "k8s.io/api/core/v1.NFSVolumeSource", "k8s.io/api/core/v1.PhotonPersistentDiskVolumeSource", "k8s.io/api/core/v1.PortworxVolumeSource", "k8s.io/api/core/v1.QuobyteVolumeSource", "k8s.io/api/core/v1.RBDPersistentVolumeSource", "k8s.io/api/core/v1.ScaleIOPersistentVolumeSource", "k8s.io/api/core/v1.StorageOSPersistentVolumeSource", "k8s.io/api/core/v1.VsphereVirtualDiskVolumeSource"}, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeSpec is the specification of a persistent volume.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "capacity": { - SchemaProps: spec.SchemaProps{ - Description: "capacity is the description of the persistent volume's resources and capacity. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#capacity", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "gcePersistentDisk": { - SchemaProps: spec.SchemaProps{ - Description: "gcePersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", - Ref: ref("k8s.io/api/core/v1.GCEPersistentDiskVolumeSource"), - }, - }, - "awsElasticBlockStore": { - SchemaProps: spec.SchemaProps{ - Description: "awsElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore", - Ref: ref("k8s.io/api/core/v1.AWSElasticBlockStoreVolumeSource"), - }, - }, - "hostPath": { - SchemaProps: spec.SchemaProps{ - Description: "hostPath represents a directory on the host. Provisioned by a developer or tester. This is useful for single-node development and testing only! On-host storage is not supported in any way and WILL NOT WORK in a multi-node cluster. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath", - Ref: ref("k8s.io/api/core/v1.HostPathVolumeSource"), - }, - }, - "glusterfs": { - SchemaProps: spec.SchemaProps{ - Description: "glusterfs represents a Glusterfs volume that is attached to a host and exposed to the pod. Provisioned by an admin. More info: https://examples.k8s.io/volumes/glusterfs/README.md", - Ref: ref("k8s.io/api/core/v1.GlusterfsPersistentVolumeSource"), - }, - }, - "nfs": { - SchemaProps: spec.SchemaProps{ - Description: "nfs represents an NFS mount on the host. Provisioned by an admin. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs", - Ref: ref("k8s.io/api/core/v1.NFSVolumeSource"), - }, - }, - "rbd": { - SchemaProps: spec.SchemaProps{ - Description: "rbd represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/rbd/README.md", - Ref: ref("k8s.io/api/core/v1.RBDPersistentVolumeSource"), - }, - }, - "iscsi": { - SchemaProps: spec.SchemaProps{ - Description: "iscsi represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin.", - Ref: ref("k8s.io/api/core/v1.ISCSIPersistentVolumeSource"), - }, - }, - "cinder": { - SchemaProps: spec.SchemaProps{ - Description: "cinder represents a cinder volume attached and mounted on kubelets host machine. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - Ref: ref("k8s.io/api/core/v1.CinderPersistentVolumeSource"), - }, - }, - "cephfs": { - SchemaProps: spec.SchemaProps{ - Description: "cephFS represents a Ceph FS mount on the host that shares a pod's lifetime", - Ref: ref("k8s.io/api/core/v1.CephFSPersistentVolumeSource"), - }, - }, - "fc": { - SchemaProps: spec.SchemaProps{ - Description: "fc represents a Fibre Channel resource that is attached to a kubelet's host machine and then exposed to the pod.", - Ref: ref("k8s.io/api/core/v1.FCVolumeSource"), - }, - }, - "flocker": { - SchemaProps: spec.SchemaProps{ - Description: "flocker represents a Flocker volume attached to a kubelet's host machine and exposed to the pod for its usage. This depends on the Flocker control service being running", - Ref: ref("k8s.io/api/core/v1.FlockerVolumeSource"), - }, - }, - "flexVolume": { - SchemaProps: spec.SchemaProps{ - Description: "flexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin.", - Ref: ref("k8s.io/api/core/v1.FlexPersistentVolumeSource"), - }, - }, - "azureFile": { - SchemaProps: spec.SchemaProps{ - Description: "azureFile represents an Azure File Service mount on the host and bind mount to the pod.", - Ref: ref("k8s.io/api/core/v1.AzureFilePersistentVolumeSource"), - }, - }, - "vsphereVolume": { - SchemaProps: spec.SchemaProps{ - Description: "vsphereVolume represents a vSphere volume attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.VsphereVirtualDiskVolumeSource"), - }, - }, - "quobyte": { - SchemaProps: spec.SchemaProps{ - Description: "quobyte represents a Quobyte mount on the host that shares a pod's lifetime", - Ref: ref("k8s.io/api/core/v1.QuobyteVolumeSource"), - }, - }, - "azureDisk": { - SchemaProps: spec.SchemaProps{ - Description: "azureDisk represents an Azure Data Disk mount on the host and bind mount to the pod.", - Ref: ref("k8s.io/api/core/v1.AzureDiskVolumeSource"), - }, - }, - "photonPersistentDisk": { - SchemaProps: spec.SchemaProps{ - Description: "photonPersistentDisk represents a PhotonController persistent disk attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.PhotonPersistentDiskVolumeSource"), - }, - }, - "portworxVolume": { - SchemaProps: spec.SchemaProps{ - Description: "portworxVolume represents a portworx volume attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.PortworxVolumeSource"), - }, - }, - "scaleIO": { - SchemaProps: spec.SchemaProps{ - Description: "scaleIO represents a ScaleIO persistent volume attached and mounted on Kubernetes nodes.", - Ref: ref("k8s.io/api/core/v1.ScaleIOPersistentVolumeSource"), - }, - }, - "local": { - SchemaProps: spec.SchemaProps{ - Description: "local represents directly-attached storage with node affinity", - Ref: ref("k8s.io/api/core/v1.LocalVolumeSource"), - }, - }, - "storageos": { - SchemaProps: spec.SchemaProps{ - Description: "storageOS represents a StorageOS volume that is attached to the kubelet's host machine and mounted into the pod More info: https://examples.k8s.io/volumes/storageos/README.md", - Ref: ref("k8s.io/api/core/v1.StorageOSPersistentVolumeSource"), - }, - }, - "csi": { - SchemaProps: spec.SchemaProps{ - Description: "csi represents storage that is handled by an external CSI driver (Beta feature).", - Ref: ref("k8s.io/api/core/v1.CSIPersistentVolumeSource"), - }, - }, - "accessModes": { - SchemaProps: spec.SchemaProps{ - Description: "accessModes contains all ways the volume can be mounted. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#access-modes", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "claimRef": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "granular", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "claimRef is part of a bi-directional binding between PersistentVolume and PersistentVolumeClaim. Expected to be non-nil when bound. claim.VolumeName is the authoritative bind between PV and PVC. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#binding", - Ref: ref("k8s.io/api/core/v1.ObjectReference"), - }, - }, - "persistentVolumeReclaimPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "persistentVolumeReclaimPolicy defines what happens to a persistent volume when released from its claim. Valid options are Retain (default for manually created PersistentVolumes), Delete (default for dynamically provisioned PersistentVolumes), and Recycle (deprecated). Recycle must be supported by the volume plugin underlying this PersistentVolume. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#reclaiming\n\nPossible enum values:\n - `\"Delete\"` means the volume will be deleted from Kubernetes on release from its claim. The volume plugin must support Deletion.\n - `\"Recycle\"` means the volume will be recycled back into the pool of unbound persistent volumes on release from its claim. The volume plugin must support Recycling.\n - `\"Retain\"` means the volume will be left in its current phase (Released) for manual reclamation by the administrator. The default policy is Retain.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Delete", "Recycle", "Retain"}, - }, - }, - "storageClassName": { - SchemaProps: spec.SchemaProps{ - Description: "storageClassName is the name of StorageClass to which this persistent volume belongs. Empty value means that this volume does not belong to any StorageClass.", - Type: []string{"string"}, - Format: "", - }, - }, - "mountOptions": { - SchemaProps: spec.SchemaProps{ - Description: "mountOptions is the list of mount options, e.g. [\"ro\", \"soft\"]. Not validated - mount will simply fail if one is invalid. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes/#mount-options", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "volumeMode": { - SchemaProps: spec.SchemaProps{ - Description: "volumeMode defines if a volume is intended to be used with a formatted filesystem or to remain in raw block state. Value of Filesystem is implied when not included in spec.\n\nPossible enum values:\n - `\"Block\"` means the volume will not be formatted with a filesystem and will remain a raw block device.\n - `\"Filesystem\"` means the volume will be or is formatted with a filesystem.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Block", "Filesystem"}, - }, - }, - "nodeAffinity": { - SchemaProps: spec.SchemaProps{ - Description: "nodeAffinity defines constraints that limit what nodes this volume can be accessed from. This field influences the scheduling of pods that use this volume.", - Ref: ref("k8s.io/api/core/v1.VolumeNodeAffinity"), - }, - }, - "volumeAttributesClassName": { - SchemaProps: spec.SchemaProps{ - Description: "Name of VolumeAttributesClass to which this persistent volume belongs. Empty value is not allowed. When this field is not set, it indicates that this volume does not belong to any VolumeAttributesClass. This field is mutable and can be changed by the CSI driver after a volume has been updated successfully to a new class. For an unbound PersistentVolume, the volumeAttributesClassName will be matched with unbound PersistentVolumeClaims during the binding process. This is an alpha field and requires enabling VolumeAttributesClass feature.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.AWSElasticBlockStoreVolumeSource", "k8s.io/api/core/v1.AzureDiskVolumeSource", "k8s.io/api/core/v1.AzureFilePersistentVolumeSource", "k8s.io/api/core/v1.CSIPersistentVolumeSource", "k8s.io/api/core/v1.CephFSPersistentVolumeSource", "k8s.io/api/core/v1.CinderPersistentVolumeSource", "k8s.io/api/core/v1.FCVolumeSource", "k8s.io/api/core/v1.FlexPersistentVolumeSource", "k8s.io/api/core/v1.FlockerVolumeSource", "k8s.io/api/core/v1.GCEPersistentDiskVolumeSource", "k8s.io/api/core/v1.GlusterfsPersistentVolumeSource", "k8s.io/api/core/v1.HostPathVolumeSource", "k8s.io/api/core/v1.ISCSIPersistentVolumeSource", "k8s.io/api/core/v1.LocalVolumeSource", "k8s.io/api/core/v1.NFSVolumeSource", "k8s.io/api/core/v1.ObjectReference", "k8s.io/api/core/v1.PhotonPersistentDiskVolumeSource", "k8s.io/api/core/v1.PortworxVolumeSource", "k8s.io/api/core/v1.QuobyteVolumeSource", "k8s.io/api/core/v1.RBDPersistentVolumeSource", "k8s.io/api/core/v1.ScaleIOPersistentVolumeSource", "k8s.io/api/core/v1.StorageOSPersistentVolumeSource", "k8s.io/api/core/v1.VolumeNodeAffinity", "k8s.io/api/core/v1.VsphereVirtualDiskVolumeSource", "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_PersistentVolumeStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PersistentVolumeStatus is the current status of a persistent volume.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "phase": { - SchemaProps: spec.SchemaProps{ - Description: "phase indicates if a volume is available, bound to a claim, or released by a claim. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#phase\n\nPossible enum values:\n - `\"Available\"` used for PersistentVolumes that are not yet bound Available volumes are held by the binder and matched to PersistentVolumeClaims\n - `\"Bound\"` used for PersistentVolumes that are bound\n - `\"Failed\"` used for PersistentVolumes that failed to be correctly recycled or deleted after being released from a claim\n - `\"Pending\"` used for PersistentVolumes that are not available\n - `\"Released\"` used for PersistentVolumes where the bound PersistentVolumeClaim was deleted released volumes must be recycled before becoming available again this phase is used by the persistent volume claim binder to signal to another process to reclaim the resource", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Available", "Bound", "Failed", "Pending", "Released"}, - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "message is a human-readable message indicating details about why the volume is in this state.", - Type: []string{"string"}, - Format: "", - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "reason is a brief CamelCase string that describes any failure and is meant for machine parsing and tidy display in the CLI.", - Type: []string{"string"}, - Format: "", - }, - }, - "lastPhaseTransitionTime": { - SchemaProps: spec.SchemaProps{ - Description: "lastPhaseTransitionTime is the time the phase transitioned from one to another and automatically resets to current time everytime a volume phase transitions. This is a beta field and requires the PersistentVolumeLastPhaseTransitionTime feature to be enabled (enabled by default).", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_PhotonPersistentDiskVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Photon Controller persistent disk resource.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "pdID": { - SchemaProps: spec.SchemaProps{ - Description: "pdID is the ID that identifies Photon Controller persistent disk", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"pdID"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_Pod(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Pod is a collection of containers that can run on a host. This resource is created by clients and scheduled onto hosts.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Specification of the desired behavior of the pod. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Most recently observed status of the pod. This data may not be up to date. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodSpec", "k8s.io/api/core/v1.PodStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_PodAffinity(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Pod affinity is a group of inter pod affinity scheduling rules.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "requiredDuringSchedulingIgnoredDuringExecution": { - SchemaProps: spec.SchemaProps{ - Description: "If the affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to a pod label update), the system may or may not try to eventually evict the pod from its node. When there are multiple elements, the lists of nodes corresponding to each podAffinityTerm are intersected, i.e. all terms must be satisfied.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodAffinityTerm"), - }, - }, - }, - }, - }, - "preferredDuringSchedulingIgnoredDuringExecution": { - SchemaProps: spec.SchemaProps{ - Description: "The scheduler will prefer to schedule pods to nodes that satisfy the affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding \"weight\" to the sum if the node has pods which matches the corresponding podAffinityTerm; the node(s) with the highest sum are the most preferred.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.WeightedPodAffinityTerm"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodAffinityTerm", "k8s.io/api/core/v1.WeightedPodAffinityTerm"}, - } -} - -func schema_k8sio_api_core_v1_PodAffinityTerm(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Defines a set of pods (namely those matching the labelSelector relative to the given namespace(s)) that this pod should be co-located (affinity) or not co-located (anti-affinity) with, where co-located is defined as running on a node whose value of the label with key matches that of any node on which a pod of the set of pods is running", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "labelSelector": { - SchemaProps: spec.SchemaProps{ - Description: "A label query over a set of resources, in this case pods. If it's null, this PodAffinityTerm matches with no Pods.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), - }, - }, - "namespaces": { - SchemaProps: spec.SchemaProps{ - Description: "namespaces specifies a static list of namespace names that the term applies to. The term is applied to the union of the namespaces listed in this field and the ones selected by namespaceSelector. null or empty namespaces list and null namespaceSelector means \"this pod's namespace\".", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "topologyKey": { - SchemaProps: spec.SchemaProps{ - Description: "This pod should be co-located (affinity) or not co-located (anti-affinity) with the pods matching the labelSelector in the specified namespaces, where co-located is defined as running on a node whose value of the label with key topologyKey matches that of any node on which any of the selected pods is running. Empty topologyKey is not allowed.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "namespaceSelector": { - SchemaProps: spec.SchemaProps{ - Description: "A label query over the set of namespaces that the term applies to. The term is applied to the union of the namespaces selected by this field and the ones listed in the namespaces field. null selector and null or empty namespaces list means \"this pod's namespace\". An empty selector ({}) matches all namespaces.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), - }, - }, - "matchLabelKeys": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "MatchLabelKeys is a set of pod label keys to select which pods will be taken into consideration. The keys are used to lookup values from the incoming pod labels, those key-value labels are merged with `LabelSelector` as `key in (value)` to select the group of existing pods which pods will be taken into consideration for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming pod labels will be ignored. The default value is empty. The same key is forbidden to exist in both MatchLabelKeys and LabelSelector. Also, MatchLabelKeys cannot be set when LabelSelector isn't set. This is an alpha field and requires enabling MatchLabelKeysInPodAffinity feature gate.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "mismatchLabelKeys": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "MismatchLabelKeys is a set of pod label keys to select which pods will be taken into consideration. The keys are used to lookup values from the incoming pod labels, those key-value labels are merged with `LabelSelector` as `key notin (value)` to select the group of existing pods which pods will be taken into consideration for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming pod labels will be ignored. The default value is empty. The same key is forbidden to exist in both MismatchLabelKeys and LabelSelector. Also, MismatchLabelKeys cannot be set when LabelSelector isn't set. This is an alpha field and requires enabling MatchLabelKeysInPodAffinity feature gate.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"topologyKey"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"}, - } -} - -func schema_k8sio_api_core_v1_PodAntiAffinity(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Pod anti affinity is a group of inter pod anti affinity scheduling rules.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "requiredDuringSchedulingIgnoredDuringExecution": { - SchemaProps: spec.SchemaProps{ - Description: "If the anti-affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the anti-affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to a pod label update), the system may or may not try to eventually evict the pod from its node. When there are multiple elements, the lists of nodes corresponding to each podAffinityTerm are intersected, i.e. all terms must be satisfied.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodAffinityTerm"), - }, - }, - }, - }, - }, - "preferredDuringSchedulingIgnoredDuringExecution": { - SchemaProps: spec.SchemaProps{ - Description: "The scheduler will prefer to schedule pods to nodes that satisfy the anti-affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling anti-affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding \"weight\" to the sum if the node has pods which matches the corresponding podAffinityTerm; the node(s) with the highest sum are the most preferred.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.WeightedPodAffinityTerm"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodAffinityTerm", "k8s.io/api/core/v1.WeightedPodAffinityTerm"}, - } -} - -func schema_k8sio_api_core_v1_PodAttachOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodAttachOptions is the query options to a Pod's remote attach call.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "stdin": { - SchemaProps: spec.SchemaProps{ - Description: "Stdin if true, redirects the standard input stream of the pod for this call. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "stdout": { - SchemaProps: spec.SchemaProps{ - Description: "Stdout if true indicates that stdout is to be redirected for the attach call. Defaults to true.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "stderr": { - SchemaProps: spec.SchemaProps{ - Description: "Stderr if true indicates that stderr is to be redirected for the attach call. Defaults to true.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "tty": { - SchemaProps: spec.SchemaProps{ - Description: "TTY if true indicates that a tty will be allocated for the attach call. This is passed through the container runtime so the tty is allocated on the worker node by the container runtime. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "container": { - SchemaProps: spec.SchemaProps{ - Description: "The container in which to execute the command. Defaults to only container if there is only one container in the pod.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PodCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodCondition contains details for the current condition of this pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type is the type of the condition. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-conditions", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status is the status of the condition. Can be True, False, Unknown. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-conditions", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "lastProbeTime": { - SchemaProps: spec.SchemaProps{ - Description: "Last time we probed the condition.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "lastTransitionTime": { - SchemaProps: spec.SchemaProps{ - Description: "Last time the condition transitioned from one status to another.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "Unique, one-word, CamelCase reason for the condition's last transition.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "Human-readable message indicating details about last transition.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_PodDNSConfig(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodDNSConfig defines the DNS parameters of a pod in addition to those generated from DNSPolicy.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "nameservers": { - SchemaProps: spec.SchemaProps{ - Description: "A list of DNS name server IP addresses. This will be appended to the base nameservers generated from DNSPolicy. Duplicated nameservers will be removed.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "searches": { - SchemaProps: spec.SchemaProps{ - Description: "A list of DNS search domains for host-name lookup. This will be appended to the base search paths generated from DNSPolicy. Duplicated search paths will be removed.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "options": { - SchemaProps: spec.SchemaProps{ - Description: "A list of DNS resolver options. This will be merged with the base options generated from DNSPolicy. Duplicated entries will be removed. Resolution options given in Options will override those that appear in the base DNSPolicy.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodDNSConfigOption"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodDNSConfigOption"}, - } -} - -func schema_k8sio_api_core_v1_PodDNSConfigOption(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodDNSConfigOption defines DNS resolver options of a pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Required.", - Type: []string{"string"}, - Format: "", - }, - }, - "value": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PodExecOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodExecOptions is the query options to a Pod's remote exec call.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "stdin": { - SchemaProps: spec.SchemaProps{ - Description: "Redirect the standard input stream of the pod for this call. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "stdout": { - SchemaProps: spec.SchemaProps{ - Description: "Redirect the standard output stream of the pod for this call.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "stderr": { - SchemaProps: spec.SchemaProps{ - Description: "Redirect the standard error stream of the pod for this call.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "tty": { - SchemaProps: spec.SchemaProps{ - Description: "TTY if true indicates that a tty will be allocated for the exec call. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "container": { - SchemaProps: spec.SchemaProps{ - Description: "Container in which to execute the command. Defaults to only container if there is only one container in the pod.", - Type: []string{"string"}, - Format: "", - }, - }, - "command": { - SchemaProps: spec.SchemaProps{ - Description: "Command is the remote command to execute. argv array. Not executed within a shell.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"command"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PodIP(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodIP represents a single IP address allocated to the pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "ip": { - SchemaProps: spec.SchemaProps{ - Description: "IP is the IP address assigned to the pod", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PodList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodList is a list of Pods.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of pods. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Pod"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.Pod", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_PodLogOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodLogOptions is the query options for a Pod's logs REST call.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "container": { - SchemaProps: spec.SchemaProps{ - Description: "The container for which to stream logs. Defaults to only container if there is one container in the pod.", - Type: []string{"string"}, - Format: "", - }, - }, - "follow": { - SchemaProps: spec.SchemaProps{ - Description: "Follow the log stream of the pod. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "previous": { - SchemaProps: spec.SchemaProps{ - Description: "Return previous terminated container logs. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "sinceSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "A relative time in seconds before the current time from which to show logs. If this value precedes the time a pod was started, only logs since the pod start will be returned. If this value is in the future, no logs will be returned. Only one of sinceSeconds or sinceTime may be specified.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "sinceTime": { - SchemaProps: spec.SchemaProps{ - Description: "An RFC3339 timestamp from which to show logs. If this value precedes the time a pod was started, only logs since the pod start will be returned. If this value is in the future, no logs will be returned. Only one of sinceSeconds or sinceTime may be specified.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "timestamps": { - SchemaProps: spec.SchemaProps{ - Description: "If true, add an RFC3339 or RFC3339Nano timestamp at the beginning of every line of log output. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "tailLines": { - SchemaProps: spec.SchemaProps{ - Description: "If set, the number of lines from the end of the logs to show. If not specified, logs are shown from the creation of the container or sinceSeconds or sinceTime", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "limitBytes": { - SchemaProps: spec.SchemaProps{ - Description: "If set, the number of bytes to read from the server before terminating the log output. This may not display a complete final line of logging, and may return slightly more or slightly less than the specified limit.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "insecureSkipTLSVerifyBackend": { - SchemaProps: spec.SchemaProps{ - Description: "insecureSkipTLSVerifyBackend indicates that the apiserver should not confirm the validity of the serving certificate of the backend it is connecting to. This will make the HTTPS connection between the apiserver and the backend insecure. This means the apiserver cannot verify the log data it is receiving came from the real kubelet. If the kubelet is configured to verify the apiserver's TLS credentials, it does not mean the connection to the real kubelet is vulnerable to a man in the middle attack (e.g. an attacker could not intercept the actual log data coming from the real kubelet).", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_PodOS(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodOS defines the OS parameters of a pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name is the name of the operating system. The currently supported values are linux and windows. Additional value may be defined in future and can be one of: https://github.com/opencontainers/runtime-spec/blob/master/config.md#platform-specific-configuration Clients should expect to handle additional values and treat unrecognized values in this field as os: null", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PodPortForwardOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodPortForwardOptions is the query options to a Pod's port forward call when using WebSockets. The `port` query parameter must specify the port or ports (comma separated) to forward over. Port forwarding over SPDY does not use these options. It requires the port to be passed in the `port` header as part of request.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "ports": { - SchemaProps: spec.SchemaProps{ - Description: "List of ports to forward Required when using WebSockets", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PodProxyOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodProxyOptions is the query options to a Pod's proxy call.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "Path is the URL path to use for the current proxy request to pod.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PodReadinessGate(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodReadinessGate contains the reference to a pod condition", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "conditionType": { - SchemaProps: spec.SchemaProps{ - Description: "ConditionType refers to a condition in the pod's condition list with matching type.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"conditionType"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PodResourceClaim(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodResourceClaim references exactly one ResourceClaim through a ClaimSource. It adds a name to it that uniquely identifies the ResourceClaim inside the Pod. Containers that need access to the ResourceClaim reference it with this name.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name uniquely identifies this resource claim inside the pod. This must be a DNS_LABEL.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "source": { - SchemaProps: spec.SchemaProps{ - Description: "Source describes where to find the ResourceClaim.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ClaimSource"), - }, - }, - }, - Required: []string{"name"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ClaimSource"}, - } -} - -func schema_k8sio_api_core_v1_PodResourceClaimStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodResourceClaimStatus is stored in the PodStatus for each PodResourceClaim which references a ResourceClaimTemplate. It stores the generated name for the corresponding ResourceClaim.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name uniquely identifies this resource claim inside the pod. This must match the name of an entry in pod.spec.resourceClaims, which implies that the string must be a DNS_LABEL.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "resourceClaimName": { - SchemaProps: spec.SchemaProps{ - Description: "ResourceClaimName is the name of the ResourceClaim that was generated for the Pod in the namespace of the Pod. It this is unset, then generating a ResourceClaim was not necessary. The pod.spec.resourceClaims entry can be ignored in this case.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PodSchedulingGate(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodSchedulingGate is associated to a Pod to guard its scheduling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the scheduling gate. Each scheduling gate must have a unique name field.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PodSecurityContext(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodSecurityContext holds pod-level security attributes and common container settings. Some fields are also present in container.securityContext. Field values of container.securityContext take precedence over field values of PodSecurityContext.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "seLinuxOptions": { - SchemaProps: spec.SchemaProps{ - Description: "The SELinux context to be applied to all containers. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container. Note that this field cannot be set when spec.os.name is windows.", - Ref: ref("k8s.io/api/core/v1.SELinuxOptions"), - }, - }, - "windowsOptions": { - SchemaProps: spec.SchemaProps{ - Description: "The Windows specific settings applied to all containers. If unspecified, the options within a container's SecurityContext will be used. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. Note that this field cannot be set when spec.os.name is linux.", - Ref: ref("k8s.io/api/core/v1.WindowsSecurityContextOptions"), - }, - }, - "runAsUser": { - SchemaProps: spec.SchemaProps{ - Description: "The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container. Note that this field cannot be set when spec.os.name is windows.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "runAsGroup": { - SchemaProps: spec.SchemaProps{ - Description: "The GID to run the entrypoint of the container process. Uses runtime default if unset. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container. Note that this field cannot be set when spec.os.name is windows.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "runAsNonRoot": { - SchemaProps: spec.SchemaProps{ - Description: "Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. If unset or false, no such validation will be performed. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "supplementalGroups": { - SchemaProps: spec.SchemaProps{ - Description: "A list of groups applied to the first process run in each container, in addition to the container's primary GID, the fsGroup (if specified), and group memberships defined in the container image for the uid of the container process. If unspecified, no additional groups are added to any container. Note that group memberships defined in the container image for the uid of the container process are still effective, even if they are not included in this list. Note that this field cannot be set when spec.os.name is windows.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: 0, - Type: []string{"integer"}, - Format: "int64", - }, - }, - }, - }, - }, - "fsGroup": { - SchemaProps: spec.SchemaProps{ - Description: "A special supplemental group that applies to all containers in a pod. Some volume types allow the Kubelet to change the ownership of that volume to be owned by the pod:\n\n1. The owning GID will be the FSGroup 2. The setgid bit is set (new files created in the volume will be owned by FSGroup) 3. The permission bits are OR'd with rw-rw----\n\nIf unset, the Kubelet will not modify the ownership and permissions of any volume. Note that this field cannot be set when spec.os.name is windows.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "sysctls": { - SchemaProps: spec.SchemaProps{ - Description: "Sysctls hold a list of namespaced sysctls used for the pod. Pods with unsupported sysctls (by the container runtime) might fail to launch. Note that this field cannot be set when spec.os.name is windows.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Sysctl"), - }, - }, - }, - }, - }, - "fsGroupChangePolicy": { - SchemaProps: spec.SchemaProps{ - Description: "fsGroupChangePolicy defines behavior of changing ownership and permission of the volume before being exposed inside Pod. This field will only apply to volume types which support fsGroup based ownership(and permissions). It will have no effect on ephemeral volume types such as: secret, configmaps and emptydir. Valid values are \"OnRootMismatch\" and \"Always\". If not specified, \"Always\" is used. Note that this field cannot be set when spec.os.name is windows.\n\nPossible enum values:\n - `\"Always\"` indicates that volume's ownership and permissions should always be changed whenever volume is mounted inside a Pod. This the default behavior.\n - `\"OnRootMismatch\"` indicates that volume's ownership and permissions will be changed only when permission and ownership of root directory does not match with expected permissions on the volume. This can help shorten the time it takes to change ownership and permissions of a volume.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Always", "OnRootMismatch"}, - }, - }, - "seccompProfile": { - SchemaProps: spec.SchemaProps{ - Description: "The seccomp options to use by the containers in this pod. Note that this field cannot be set when spec.os.name is windows.", - Ref: ref("k8s.io/api/core/v1.SeccompProfile"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.SELinuxOptions", "k8s.io/api/core/v1.SeccompProfile", "k8s.io/api/core/v1.Sysctl", "k8s.io/api/core/v1.WindowsSecurityContextOptions"}, - } -} - -func schema_k8sio_api_core_v1_PodSignature(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Describes the class of pods that should avoid this node. Exactly one field should be set.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "podController": { - SchemaProps: spec.SchemaProps{ - Description: "Reference to controller whose pods should avoid this node.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.OwnerReference"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.OwnerReference"}, - } -} - -func schema_k8sio_api_core_v1_PodSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodSpec is a description of a pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "volumes": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge,retainKeys", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Volume"), - }, - }, - }, - }, - }, - "initContainers": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of initialization containers belonging to the pod. Init containers are executed in order prior to containers being started. If any init container fails, the pod is considered to have failed and is handled according to its restartPolicy. The name for an init container or normal container must be unique among all containers. Init containers may not have Lifecycle actions, Readiness probes, Liveness probes, or Startup probes. The resourceRequirements of an init container are taken into account during scheduling by finding the highest request/limit for each resource type, and then using the max of of that value or the sum of the normal containers. Limits are applied to init containers in a similar fashion. Init containers cannot currently be added or removed. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Container"), - }, - }, - }, - }, - }, - "containers": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of containers belonging to the pod. Containers cannot currently be added or removed. There must be at least one container in a Pod. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Container"), - }, - }, - }, - }, - }, - "ephemeralContainers": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of ephemeral containers run in this pod. Ephemeral containers may be run in an existing pod to perform user-initiated actions such as debugging. This list cannot be specified when creating a pod, and it cannot be modified by updating the pod spec. In order to add an ephemeral container to an existing pod, use the pod's ephemeralcontainers subresource.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EphemeralContainer"), - }, - }, - }, - }, - }, - "restartPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Restart policy for all containers within the pod. One of Always, OnFailure, Never. In some contexts, only a subset of those values may be permitted. Default to Always. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy\n\nPossible enum values:\n - `\"Always\"`\n - `\"Never\"`\n - `\"OnFailure\"`", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Always", "Never", "OnFailure"}, - }, - }, - "terminationGracePeriodSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Optional duration in seconds the pod needs to terminate gracefully. May be decreased in delete request. Value must be non-negative integer. The value zero indicates stop immediately via the kill signal (no opportunity to shut down). If this value is nil, the default grace period will be used instead. The grace period is the duration in seconds after the processes running in the pod are sent a termination signal and the time when the processes are forcibly halted with a kill signal. Set this value longer than the expected cleanup time for your process. Defaults to 30 seconds.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "activeDeadlineSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Optional duration in seconds the pod may be active on the node relative to StartTime before the system will actively try to mark it failed and kill associated containers. Value must be a positive integer.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "dnsPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Set DNS policy for the pod. Defaults to \"ClusterFirst\". Valid values are 'ClusterFirstWithHostNet', 'ClusterFirst', 'Default' or 'None'. DNS parameters given in DNSConfig will be merged with the policy selected with DNSPolicy. To have DNS options set along with hostNetwork, you have to specify DNS policy explicitly to 'ClusterFirstWithHostNet'.\n\nPossible enum values:\n - `\"ClusterFirst\"` indicates that the pod should use cluster DNS first unless hostNetwork is true, if it is available, then fall back on the default (as determined by kubelet) DNS settings.\n - `\"ClusterFirstWithHostNet\"` indicates that the pod should use cluster DNS first, if it is available, then fall back on the default (as determined by kubelet) DNS settings.\n - `\"Default\"` indicates that the pod should use the default (as determined by kubelet) DNS settings.\n - `\"None\"` indicates that the pod should use empty DNS settings. DNS parameters such as nameservers and search paths should be defined via DNSConfig.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"ClusterFirst", "ClusterFirstWithHostNet", "Default", "None"}, - }, - }, - "nodeSelector": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "NodeSelector is a selector which must be true for the pod to fit on a node. Selector which must match a node's labels for the pod to be scheduled on that node. More info: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "serviceAccountName": { - SchemaProps: spec.SchemaProps{ - Description: "ServiceAccountName is the name of the ServiceAccount to use to run this pod. More info: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/", - Type: []string{"string"}, - Format: "", - }, - }, - "serviceAccount": { - SchemaProps: spec.SchemaProps{ - Description: "DeprecatedServiceAccount is a depreciated alias for ServiceAccountName. Deprecated: Use serviceAccountName instead.", - Type: []string{"string"}, - Format: "", - }, - }, - "automountServiceAccountToken": { - SchemaProps: spec.SchemaProps{ - Description: "AutomountServiceAccountToken indicates whether a service account token should be automatically mounted.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "nodeName": { - SchemaProps: spec.SchemaProps{ - Description: "NodeName is a request to schedule this pod onto a specific node. If it is non-empty, the scheduler simply schedules this pod onto that node, assuming that it fits resource requirements.", - Type: []string{"string"}, - Format: "", - }, - }, - "hostNetwork": { - SchemaProps: spec.SchemaProps{ - Description: "Host networking requested for this pod. Use the host's network namespace. If this option is set, the ports that will be used must be specified. Default to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "hostPID": { - SchemaProps: spec.SchemaProps{ - Description: "Use the host's pid namespace. Optional: Default to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "hostIPC": { - SchemaProps: spec.SchemaProps{ - Description: "Use the host's ipc namespace. Optional: Default to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "shareProcessNamespace": { - SchemaProps: spec.SchemaProps{ - Description: "Share a single process namespace between all of the containers in a pod. When this is set containers will be able to view and signal processes from other containers in the same pod, and the first process in each container will not be assigned PID 1. HostPID and ShareProcessNamespace cannot both be set. Optional: Default to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "securityContext": { - SchemaProps: spec.SchemaProps{ - Description: "SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field.", - Ref: ref("k8s.io/api/core/v1.PodSecurityContext"), - }, - }, - "imagePullSecrets": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. If specified, these secrets will be passed to individual puller implementations for them to use. More info: https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - }, - }, - }, - "hostname": { - SchemaProps: spec.SchemaProps{ - Description: "Specifies the hostname of the Pod If not specified, the pod's hostname will be set to a system-defined value.", - Type: []string{"string"}, - Format: "", - }, - }, - "subdomain": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, the fully qualified Pod hostname will be \"...svc.\". If not specified, the pod will not have a domainname at all.", - Type: []string{"string"}, - Format: "", - }, - }, - "affinity": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, the pod's scheduling constraints", - Ref: ref("k8s.io/api/core/v1.Affinity"), - }, - }, - "schedulerName": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, the pod will be dispatched by specified scheduler. If not specified, the pod will be dispatched by default scheduler.", - Type: []string{"string"}, - Format: "", - }, - }, - "tolerations": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, the pod's tolerations.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Toleration"), - }, - }, - }, - }, - }, - "hostAliases": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "ip", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "HostAliases is an optional list of hosts and IPs that will be injected into the pod's hosts file if specified. This is only valid for non-hostNetwork pods.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.HostAlias"), - }, - }, - }, - }, - }, - "priorityClassName": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, indicates the pod's priority. \"system-node-critical\" and \"system-cluster-critical\" are two special keywords which indicate the highest priorities with the former being the highest priority. Any other name must be defined by creating a PriorityClass object with that name. If not specified, the pod priority will be default or zero if there is no default.", - Type: []string{"string"}, - Format: "", - }, - }, - "priority": { - SchemaProps: spec.SchemaProps{ - Description: "The priority value. Various system components use this field to find the priority of the pod. When Priority Admission Controller is enabled, it prevents users from setting this field. The admission controller populates this field from PriorityClassName. The higher the value, the higher the priority.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "dnsConfig": { - SchemaProps: spec.SchemaProps{ - Description: "Specifies the DNS parameters of a pod. Parameters specified here will be merged to the generated DNS configuration based on DNSPolicy.", - Ref: ref("k8s.io/api/core/v1.PodDNSConfig"), - }, - }, - "readinessGates": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, all readiness gates will be evaluated for pod readiness. A pod is ready when all its containers are ready AND all conditions specified in the readiness gates have status equal to \"True\" More info: https://git.k8s.io/enhancements/keps/sig-network/580-pod-readiness-gates", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodReadinessGate"), - }, - }, - }, - }, - }, - "runtimeClassName": { - SchemaProps: spec.SchemaProps{ - Description: "RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group, which should be used to run this pod. If no RuntimeClass resource matches the named class, the pod will not be run. If unset or empty, the \"legacy\" RuntimeClass will be used, which is an implicit class with an empty definition that uses the default runtime handler. More info: https://git.k8s.io/enhancements/keps/sig-node/585-runtime-class", - Type: []string{"string"}, - Format: "", - }, - }, - "enableServiceLinks": { - SchemaProps: spec.SchemaProps{ - Description: "EnableServiceLinks indicates whether information about services should be injected into pod's environment variables, matching the syntax of Docker links. Optional: Defaults to true.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "preemptionPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "PreemptionPolicy is the Policy for preempting pods with lower priority. One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset.\n\nPossible enum values:\n - `\"Never\"` means that pod never preempts other pods with lower priority.\n - `\"PreemptLowerPriority\"` means that pod can preempt other pods with lower priority.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Never", "PreemptLowerPriority"}, - }, - }, - "overhead": { - SchemaProps: spec.SchemaProps{ - Description: "Overhead represents the resource overhead associated with running a pod for a given RuntimeClass. This field will be autopopulated at admission time by the RuntimeClass admission controller. If the RuntimeClass admission controller is enabled, overhead must not be set in Pod create requests. The RuntimeClass admission controller will reject Pod create requests which have the overhead already set. If RuntimeClass is configured and selected in the PodSpec, Overhead will be set to the value defined in the corresponding RuntimeClass, otherwise it will remain unset and treated as zero. More info: https://git.k8s.io/enhancements/keps/sig-node/688-pod-overhead/README.md", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "topologySpreadConstraints": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "topologyKey", - "whenUnsatisfiable", - }, - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "topologyKey", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "TopologySpreadConstraints describes how a group of pods ought to spread across topology domains. Scheduler will schedule pods in a way which abides by the constraints. All topologySpreadConstraints are ANDed.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.TopologySpreadConstraint"), - }, - }, - }, - }, - }, - "setHostnameAsFQDN": { - SchemaProps: spec.SchemaProps{ - Description: "If true the pod's hostname will be configured as the pod's FQDN, rather than the leaf name (the default). In Linux containers, this means setting the FQDN in the hostname field of the kernel (the nodename field of struct utsname). In Windows containers, this means setting the registry value of hostname for the registry key HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters to FQDN. If a pod does not have FQDN, this has no effect. Default to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "os": { - SchemaProps: spec.SchemaProps{ - Description: "Specifies the OS of the containers in the pod. Some pod and container fields are restricted if this is set.\n\nIf the OS field is set to linux, the following fields must be unset: -securityContext.windowsOptions\n\nIf the OS field is set to windows, following fields must be unset: - spec.hostPID - spec.hostIPC - spec.hostUsers - spec.securityContext.seLinuxOptions - spec.securityContext.seccompProfile - spec.securityContext.fsGroup - spec.securityContext.fsGroupChangePolicy - spec.securityContext.sysctls - spec.shareProcessNamespace - spec.securityContext.runAsUser - spec.securityContext.runAsGroup - spec.securityContext.supplementalGroups - spec.containers[*].securityContext.seLinuxOptions - spec.containers[*].securityContext.seccompProfile - spec.containers[*].securityContext.capabilities - spec.containers[*].securityContext.readOnlyRootFilesystem - spec.containers[*].securityContext.privileged - spec.containers[*].securityContext.allowPrivilegeEscalation - spec.containers[*].securityContext.procMount - spec.containers[*].securityContext.runAsUser - spec.containers[*].securityContext.runAsGroup", - Ref: ref("k8s.io/api/core/v1.PodOS"), - }, - }, - "hostUsers": { - SchemaProps: spec.SchemaProps{ - Description: "Use the host's user namespace. Optional: Default to true. If set to true or not present, the pod will be run in the host user namespace, useful for when the pod needs a feature only available to the host user namespace, such as loading a kernel module with CAP_SYS_MODULE. When set to false, a new userns is created for the pod. Setting false is useful for mitigating container breakout vulnerabilities even allowing users to run their containers as root without actually having root privileges on the host. This field is alpha-level and is only honored by servers that enable the UserNamespacesSupport feature.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "schedulingGates": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "name", - }, - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "SchedulingGates is an opaque list of values that if specified will block scheduling the pod. If schedulingGates is not empty, the pod will stay in the SchedulingGated state and the scheduler will not attempt to schedule the pod.\n\nSchedulingGates can only be set at pod creation time, and be removed only afterwards.\n\nThis is a beta feature enabled by the PodSchedulingReadiness feature gate.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodSchedulingGate"), - }, - }, - }, - }, - }, - "resourceClaims": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "name", - }, - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge,retainKeys", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "ResourceClaims defines which ResourceClaims must be allocated and reserved before the Pod is allowed to start. The resources will be made available to those containers which consume them by name.\n\nThis is an alpha field and requires enabling the DynamicResourceAllocation feature gate.\n\nThis field is immutable.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodResourceClaim"), - }, - }, - }, - }, - }, - }, - Required: []string{"containers"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.Affinity", "k8s.io/api/core/v1.Container", "k8s.io/api/core/v1.EphemeralContainer", "k8s.io/api/core/v1.HostAlias", "k8s.io/api/core/v1.LocalObjectReference", "k8s.io/api/core/v1.PodDNSConfig", "k8s.io/api/core/v1.PodOS", "k8s.io/api/core/v1.PodReadinessGate", "k8s.io/api/core/v1.PodResourceClaim", "k8s.io/api/core/v1.PodSchedulingGate", "k8s.io/api/core/v1.PodSecurityContext", "k8s.io/api/core/v1.Toleration", "k8s.io/api/core/v1.TopologySpreadConstraint", "k8s.io/api/core/v1.Volume", "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_PodStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodStatus represents information about the status of a pod. Status may trail the actual state of a system, especially if the node that hosts the pod cannot contact the control plane.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "phase": { - SchemaProps: spec.SchemaProps{ - Description: "The phase of a Pod is a simple, high-level summary of where the Pod is in its lifecycle. The conditions array, the reason and message fields, and the individual container status arrays contain more detail about the pod's status. There are five possible phase values:\n\nPending: The pod has been accepted by the Kubernetes system, but one or more of the container images has not been created. This includes time before being scheduled as well as time spent downloading images over the network, which could take a while. Running: The pod has been bound to a node, and all of the containers have been created. At least one container is still running, or is in the process of starting or restarting. Succeeded: All containers in the pod have terminated in success, and will not be restarted. Failed: All containers in the pod have terminated, and at least one container has terminated in failure. The container either exited with non-zero status or was terminated by the system. Unknown: For some reason the state of the pod could not be obtained, typically due to an error in communicating with the host of the pod.\n\nMore info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-phase\n\nPossible enum values:\n - `\"Failed\"` means that all containers in the pod have terminated, and at least one container has terminated in a failure (exited with a non-zero exit code or was stopped by the system).\n - `\"Pending\"` means the pod has been accepted by the system, but one or more of the containers has not been started. This includes time before being bound to a node, as well as time spent pulling images onto the host.\n - `\"Running\"` means the pod has been bound to a node and all of the containers have been started. At least one container is still running or is in the process of being restarted.\n - `\"Succeeded\"` means that all containers in the pod have voluntarily terminated with a container exit code of 0, and the system is not going to restart any of these containers.\n - `\"Unknown\"` means that for some reason the state of the pod could not be obtained, typically due to an error in communicating with the host of the pod. Deprecated: It isn't being set since 2015 (74da3b14b0c0f658b3bb8d2def5094686d0e9095)", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Failed", "Pending", "Running", "Succeeded", "Unknown"}, - }, - }, - "conditions": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Current service state of pod. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-conditions", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodCondition"), - }, - }, - }, - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "A human readable message indicating details about why the pod is in this condition.", - Type: []string{"string"}, - Format: "", - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "A brief CamelCase message indicating details about why the pod is in this state. e.g. 'Evicted'", - Type: []string{"string"}, - Format: "", - }, - }, - "nominatedNodeName": { - SchemaProps: spec.SchemaProps{ - Description: "nominatedNodeName is set only when this pod preempts other pods on the node, but it cannot be scheduled right away as preemption victims receive their graceful termination periods. This field does not guarantee that the pod will be scheduled on this node. Scheduler may decide to place the pod elsewhere if other nodes become available sooner. Scheduler may also decide to give the resources on this node to a higher priority pod that is created after preemption. As a result, this field may be different than PodSpec.nodeName when the pod is scheduled.", - Type: []string{"string"}, - Format: "", - }, - }, - "hostIP": { - SchemaProps: spec.SchemaProps{ - Description: "hostIP holds the IP address of the host to which the pod is assigned. Empty if the pod has not started yet. A pod can be assigned to a node that has a problem in kubelet which in turns mean that HostIP will not be updated even if there is a node is assigned to pod", - Type: []string{"string"}, - Format: "", - }, - }, - "hostIPs": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - "x-kubernetes-patch-merge-key": "ip", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "hostIPs holds the IP addresses allocated to the host. If this field is specified, the first entry must match the hostIP field. This list is empty if the pod has not started yet. A pod can be assigned to a node that has a problem in kubelet which in turns means that HostIPs will not be updated even if there is a node is assigned to this pod.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.HostIP"), - }, - }, - }, - }, - }, - "podIP": { - SchemaProps: spec.SchemaProps{ - Description: "podIP address allocated to the pod. Routable at least within the cluster. Empty if not yet allocated.", - Type: []string{"string"}, - Format: "", - }, - }, - "podIPs": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "ip", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "podIPs holds the IP addresses allocated to the pod. If this field is specified, the 0th entry must match the podIP field. Pods may be allocated at most 1 value for each of IPv4 and IPv6. This list is empty if no IPs have been allocated yet.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodIP"), - }, - }, - }, - }, - }, - "startTime": { - SchemaProps: spec.SchemaProps{ - Description: "RFC 3339 date and time at which the object was acknowledged by the Kubelet. This is before the Kubelet pulled the container image(s) for the pod.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "initContainerStatuses": { - SchemaProps: spec.SchemaProps{ - Description: "The list has one entry per init container in the manifest. The most recent successful init container will have ready = true, the most recently started container will have startTime set. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-and-container-status", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerStatus"), - }, - }, - }, - }, - }, - "containerStatuses": { - SchemaProps: spec.SchemaProps{ - Description: "The list has one entry per container in the manifest. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-and-container-status", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerStatus"), - }, - }, - }, - }, - }, - "qosClass": { - SchemaProps: spec.SchemaProps{ - Description: "The Quality of Service (QOS) classification assigned to the pod based on resource requirements See PodQOSClass type for available QOS classes More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-qos/#quality-of-service-classes\n\nPossible enum values:\n - `\"BestEffort\"` is the BestEffort qos class.\n - `\"Burstable\"` is the Burstable qos class.\n - `\"Guaranteed\"` is the Guaranteed qos class.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"BestEffort", "Burstable", "Guaranteed"}, - }, - }, - "ephemeralContainerStatuses": { - SchemaProps: spec.SchemaProps{ - Description: "Status for any ephemeral containers that have run in this pod.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerStatus"), - }, - }, - }, - }, - }, - "resize": { - SchemaProps: spec.SchemaProps{ - Description: "Status of resources resize desired for pod's containers. It is empty if no resources resize is pending. Any changes to container resources will automatically set this to \"Proposed\"", - Type: []string{"string"}, - Format: "", - }, - }, - "resourceClaimStatuses": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "name", - }, - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge,retainKeys", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Status of resource claims.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodResourceClaimStatus"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ContainerStatus", "k8s.io/api/core/v1.HostIP", "k8s.io/api/core/v1.PodCondition", "k8s.io/api/core/v1.PodIP", "k8s.io/api/core/v1.PodResourceClaimStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_PodStatusResult(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodStatusResult is a wrapper for PodStatus returned by kubelet that can be encode/decoded", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Most recently observed status of the pod. This data may not be up to date. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_PodTemplate(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodTemplate describes a template for creating copies of a predefined pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "template": { - SchemaProps: spec.SchemaProps{ - Description: "Template defines the pods that will be created from this pod template. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodTemplateSpec"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodTemplateSpec", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_PodTemplateList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodTemplateList is a list of PodTemplates.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of pod templates", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodTemplate"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodTemplate", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_PodTemplateSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodTemplateSpec describes the data a pod should have when created from a template", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Specification of the desired behavior of the pod. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodSpec"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodSpec", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_PortStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "port": { - SchemaProps: spec.SchemaProps{ - Description: "Port is the port number of the service port of which status is recorded here", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "protocol": { - SchemaProps: spec.SchemaProps{ - Description: "Protocol is the protocol of the service port of which status is recorded here The supported values are: \"TCP\", \"UDP\", \"SCTP\"\n\nPossible enum values:\n - `\"SCTP\"` is the SCTP protocol.\n - `\"TCP\"` is the TCP protocol.\n - `\"UDP\"` is the UDP protocol.", - Default: "", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"SCTP", "TCP", "UDP"}, - }, - }, - "error": { - SchemaProps: spec.SchemaProps{ - Description: "Error is to record the problem with the service port The format of the error shall comply with the following rules: - built-in error values shall be specified in this file and those shall use\n CamelCase names\n- cloud provider specific error values must have names that comply with the\n format foo.example.com/CamelCase.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"port", "protocol"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PortworxVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PortworxVolumeSource represents a Portworx volume resource.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "volumeID": { - SchemaProps: spec.SchemaProps{ - Description: "volumeID uniquely identifies a Portworx volume", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fSType represents the filesystem type to mount Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\". Implicitly inferred to be \"ext4\" if unspecified.", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"volumeID"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_PreferAvoidPodsEntry(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Describes a class of pods that should avoid this node.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "podSignature": { - SchemaProps: spec.SchemaProps{ - Description: "The class of pods.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodSignature"), - }, - }, - "evictionTime": { - SchemaProps: spec.SchemaProps{ - Description: "Time at which this entry was added to the list.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "(brief) reason why this entry was added to the list.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "Human readable message indicating why this entry was added to the list.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"podSignature"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodSignature", "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_PreferredSchedulingTerm(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "An empty preferred scheduling term matches all objects with implicit weight 0 (i.e. it's a no-op). A null preferred scheduling term matches no objects (i.e. is also a no-op).", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "weight": { - SchemaProps: spec.SchemaProps{ - Description: "Weight associated with matching the corresponding nodeSelectorTerm, in the range 1-100.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "preference": { - SchemaProps: spec.SchemaProps{ - Description: "A node selector term, associated with the corresponding weight.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.NodeSelectorTerm"), - }, - }, - }, - Required: []string{"weight", "preference"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NodeSelectorTerm"}, - } -} - -func schema_k8sio_api_core_v1_Probe(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Probe describes a health check to be performed against a container to determine whether it is alive or ready to receive traffic.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "exec": { - SchemaProps: spec.SchemaProps{ - Description: "Exec specifies the action to take.", - Ref: ref("k8s.io/api/core/v1.ExecAction"), - }, - }, - "httpGet": { - SchemaProps: spec.SchemaProps{ - Description: "HTTPGet specifies the http request to perform.", - Ref: ref("k8s.io/api/core/v1.HTTPGetAction"), - }, - }, - "tcpSocket": { - SchemaProps: spec.SchemaProps{ - Description: "TCPSocket specifies an action involving a TCP port.", - Ref: ref("k8s.io/api/core/v1.TCPSocketAction"), - }, - }, - "grpc": { - SchemaProps: spec.SchemaProps{ - Description: "GRPC specifies an action involving a GRPC port.", - Ref: ref("k8s.io/api/core/v1.GRPCAction"), - }, - }, - "initialDelaySeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Number of seconds after the container has started before liveness probes are initiated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "timeoutSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Number of seconds after which the probe times out. Defaults to 1 second. Minimum value is 1. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "periodSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "How often (in seconds) to perform the probe. Default to 10 seconds. Minimum value is 1.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "successThreshold": { - SchemaProps: spec.SchemaProps{ - Description: "Minimum consecutive successes for the probe to be considered successful after having failed. Defaults to 1. Must be 1 for liveness and startup. Minimum value is 1.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "failureThreshold": { - SchemaProps: spec.SchemaProps{ - Description: "Minimum consecutive failures for the probe to be considered failed after having succeeded. Defaults to 3. Minimum value is 1.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "terminationGracePeriodSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Optional duration in seconds the pod needs to terminate gracefully upon probe failure. The grace period is the duration in seconds after the processes running in the pod are sent a termination signal and the time when the processes are forcibly halted with a kill signal. Set this value longer than the expected cleanup time for your process. If this value is nil, the pod's terminationGracePeriodSeconds will be used. Otherwise, this value overrides the value provided by the pod spec. Value must be non-negative integer. The value zero indicates stop immediately via the kill signal (no opportunity to shut down). This is a beta field and requires enabling ProbeTerminationGracePeriod feature gate. Minimum value is 1. spec.terminationGracePeriodSeconds is used if unset.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ExecAction", "k8s.io/api/core/v1.GRPCAction", "k8s.io/api/core/v1.HTTPGetAction", "k8s.io/api/core/v1.TCPSocketAction"}, - } -} - -func schema_k8sio_api_core_v1_ProbeHandler(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ProbeHandler defines a specific action that should be taken in a probe. One and only one of the fields must be specified.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "exec": { - SchemaProps: spec.SchemaProps{ - Description: "Exec specifies the action to take.", - Ref: ref("k8s.io/api/core/v1.ExecAction"), - }, - }, - "httpGet": { - SchemaProps: spec.SchemaProps{ - Description: "HTTPGet specifies the http request to perform.", - Ref: ref("k8s.io/api/core/v1.HTTPGetAction"), - }, - }, - "tcpSocket": { - SchemaProps: spec.SchemaProps{ - Description: "TCPSocket specifies an action involving a TCP port.", - Ref: ref("k8s.io/api/core/v1.TCPSocketAction"), - }, - }, - "grpc": { - SchemaProps: spec.SchemaProps{ - Description: "GRPC specifies an action involving a GRPC port.", - Ref: ref("k8s.io/api/core/v1.GRPCAction"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ExecAction", "k8s.io/api/core/v1.GRPCAction", "k8s.io/api/core/v1.HTTPGetAction", "k8s.io/api/core/v1.TCPSocketAction"}, - } -} - -func schema_k8sio_api_core_v1_ProjectedVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a projected volume source", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "sources": { - SchemaProps: spec.SchemaProps{ - Description: "sources is the list of volume projections", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.VolumeProjection"), - }, - }, - }, - }, - }, - "defaultMode": { - SchemaProps: spec.SchemaProps{ - Description: "defaultMode are the mode bits used to set permissions on created files by default. Must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.VolumeProjection"}, - } -} - -func schema_k8sio_api_core_v1_QuobyteVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Quobyte mount that lasts the lifetime of a pod. Quobyte volumes do not support ownership management or SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "registry": { - SchemaProps: spec.SchemaProps{ - Description: "registry represents a single or multiple Quobyte Registry services specified as a string as host:port pair (multiple entries are separated with commas) which acts as the central registry for volumes", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "volume": { - SchemaProps: spec.SchemaProps{ - Description: "volume is a string that references an already created Quobyte volume by name.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly here will force the Quobyte volume to be mounted with read-only permissions. Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "user": { - SchemaProps: spec.SchemaProps{ - Description: "user to map volume access to Defaults to serivceaccount user", - Type: []string{"string"}, - Format: "", - }, - }, - "group": { - SchemaProps: spec.SchemaProps{ - Description: "group to map volume access to Default is no group", - Type: []string{"string"}, - Format: "", - }, - }, - "tenant": { - SchemaProps: spec.SchemaProps{ - Description: "tenant owning the given Quobyte volume in the Backend Used with dynamically provisioned Quobyte volumes, value is set by the plugin", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"registry", "volume"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_RBDPersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Rados Block Device mount that lasts the lifetime of a pod. RBD volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "monitors": { - SchemaProps: spec.SchemaProps{ - Description: "monitors is a collection of Ceph monitors. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "image": { - SchemaProps: spec.SchemaProps{ - Description: "image is the rados image name. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#rbd", - Type: []string{"string"}, - Format: "", - }, - }, - "pool": { - SchemaProps: spec.SchemaProps{ - Description: "pool is the rados pool name. Default is rbd. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Type: []string{"string"}, - Format: "", - }, - }, - "user": { - SchemaProps: spec.SchemaProps{ - Description: "user is the rados user name. Default is admin. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Type: []string{"string"}, - Format: "", - }, - }, - "keyring": { - SchemaProps: spec.SchemaProps{ - Description: "keyring is the path to key ring for RBDUser. Default is /etc/ceph/keyring. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Type: []string{"string"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef is name of the authentication secret for RBDUser. If provided overrides keyring. Default is nil. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"monitors", "image"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.SecretReference"}, - } -} - -func schema_k8sio_api_core_v1_RBDVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a Rados Block Device mount that lasts the lifetime of a pod. RBD volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "monitors": { - SchemaProps: spec.SchemaProps{ - Description: "monitors is a collection of Ceph monitors. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "image": { - SchemaProps: spec.SchemaProps{ - Description: "image is the rados image name. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#rbd", - Type: []string{"string"}, - Format: "", - }, - }, - "pool": { - SchemaProps: spec.SchemaProps{ - Description: "pool is the rados pool name. Default is rbd. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Type: []string{"string"}, - Format: "", - }, - }, - "user": { - SchemaProps: spec.SchemaProps{ - Description: "user is the rados user name. Default is admin. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Type: []string{"string"}, - Format: "", - }, - }, - "keyring": { - SchemaProps: spec.SchemaProps{ - Description: "keyring is the path to key ring for RBDUser. Default is /etc/ceph/keyring. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Type: []string{"string"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef is name of the authentication secret for RBDUser. If provided overrides keyring. Default is nil. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"monitors", "image"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LocalObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_RangeAllocation(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "RangeAllocation is not a public type.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "range": { - SchemaProps: spec.SchemaProps{ - Description: "Range is string that identifies the range represented by 'data'.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "data": { - SchemaProps: spec.SchemaProps{ - Description: "Data is a bit array containing all allocated addresses in the previous segment.", - Type: []string{"string"}, - Format: "byte", - }, - }, - }, - Required: []string{"range", "data"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_ReplicationController(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ReplicationController represents the configuration of a replication controller.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "If the Labels of a ReplicationController are empty, they are defaulted to be the same as the Pod(s) that the replication controller manages. Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Spec defines the specification of the desired behavior of the replication controller. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ReplicationControllerSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status is the most recently observed status of the replication controller. This data may be out of date by some window of time. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ReplicationControllerStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ReplicationControllerSpec", "k8s.io/api/core/v1.ReplicationControllerStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_ReplicationControllerCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ReplicationControllerCondition describes the state of a replication controller at a certain point.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of replication controller condition.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status of the condition, one of True, False, Unknown.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "lastTransitionTime": { - SchemaProps: spec.SchemaProps{ - Description: "The last time the condition transitioned from one status to another.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "The reason for the condition's last transition.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "A human readable message indicating details about the transition.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_ReplicationControllerList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ReplicationControllerList is a collection of replication controllers.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of replication controllers. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ReplicationController"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ReplicationController", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_ReplicationControllerSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ReplicationControllerSpec is the specification of a replication controller.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "replicas": { - SchemaProps: spec.SchemaProps{ - Description: "Replicas is the number of desired replicas. This is a pointer to distinguish between explicit zero and unspecified. Defaults to 1. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#what-is-a-replicationcontroller", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "minReadySeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready)", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "selector": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Selector is a label query over pods that should match the Replicas count. If Selector is empty, it is defaulted to the labels present on the Pod template. Label keys and values that must match in order to be controlled by this replication controller, if empty defaulted to labels on Pod template. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "template": { - SchemaProps: spec.SchemaProps{ - Description: "Template is the object that describes the pod that will be created if insufficient replicas are detected. This takes precedence over a TemplateRef. The only allowed template.spec.restartPolicy value is \"Always\". More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#pod-template", - Ref: ref("k8s.io/api/core/v1.PodTemplateSpec"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodTemplateSpec"}, - } -} - -func schema_k8sio_api_core_v1_ReplicationControllerStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ReplicationControllerStatus represents the current status of a replication controller.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "replicas": { - SchemaProps: spec.SchemaProps{ - Description: "Replicas is the most recently observed number of replicas. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#what-is-a-replicationcontroller", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "fullyLabeledReplicas": { - SchemaProps: spec.SchemaProps{ - Description: "The number of pods that have labels matching the labels of the pod template of the replication controller.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "readyReplicas": { - SchemaProps: spec.SchemaProps{ - Description: "The number of ready replicas for this replication controller.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "availableReplicas": { - SchemaProps: spec.SchemaProps{ - Description: "The number of available replicas (ready for at least minReadySeconds) for this replication controller.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "observedGeneration": { - SchemaProps: spec.SchemaProps{ - Description: "ObservedGeneration reflects the generation of the most recently observed replication controller.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "conditions": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Represents the latest available observations of a replication controller's current state.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ReplicationControllerCondition"), - }, - }, - }, - }, - }, - }, - Required: []string{"replicas"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ReplicationControllerCondition"}, - } -} - -func schema_k8sio_api_core_v1_ResourceClaim(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ResourceClaim references one entry in PodSpec.ResourceClaims.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name must match the name of one entry in pod.spec.resourceClaims of the Pod where this field is used. It makes that resource available inside a container.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ResourceFieldSelector(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ResourceFieldSelector represents container resources (cpu, memory) and their output format", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "containerName": { - SchemaProps: spec.SchemaProps{ - Description: "Container name: required for volumes, optional for env vars", - Type: []string{"string"}, - Format: "", - }, - }, - "resource": { - SchemaProps: spec.SchemaProps{ - Description: "Required: resource to select", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "divisor": { - SchemaProps: spec.SchemaProps{ - Description: "Specifies the output format of the exposed resources, defaults to \"1\"", - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - Required: []string{"resource"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_ResourceQuota(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ResourceQuota sets aggregate quota restrictions enforced per namespace", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Spec defines the desired quota. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ResourceQuotaSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status defines the actual enforced quota and its current usage. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ResourceQuotaStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ResourceQuotaSpec", "k8s.io/api/core/v1.ResourceQuotaStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_ResourceQuotaList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ResourceQuotaList is a list of ResourceQuota items.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is a list of ResourceQuota objects. More info: https://kubernetes.io/docs/concepts/policy/resource-quotas/", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ResourceQuota"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ResourceQuota", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_ResourceQuotaSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ResourceQuotaSpec defines the desired hard limits to enforce for Quota.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "hard": { - SchemaProps: spec.SchemaProps{ - Description: "hard is the set of desired hard limits for each named resource. More info: https://kubernetes.io/docs/concepts/policy/resource-quotas/", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "scopes": { - SchemaProps: spec.SchemaProps{ - Description: "A collection of filters that must match each object tracked by a quota. If not specified, the quota matches all objects.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "scopeSelector": { - SchemaProps: spec.SchemaProps{ - Description: "scopeSelector is also a collection of filters like scopes that must match each object tracked by a quota but expressed using ScopeSelectorOperator in combination with possible values. For a resource to match, both scopes AND scopeSelector (if specified in spec), must be matched.", - Ref: ref("k8s.io/api/core/v1.ScopeSelector"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ScopeSelector", "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_ResourceQuotaStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ResourceQuotaStatus defines the enforced hard limits and observed use.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "hard": { - SchemaProps: spec.SchemaProps{ - Description: "Hard is the set of enforced hard limits for each named resource. More info: https://kubernetes.io/docs/concepts/policy/resource-quotas/", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "used": { - SchemaProps: spec.SchemaProps{ - Description: "Used is the current observed total usage of the resource in the namespace.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_ResourceRequirements(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ResourceRequirements describes the compute resource requirements.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "limits": { - SchemaProps: spec.SchemaProps{ - Description: "Limits describes the maximum amount of compute resources allowed. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "requests": { - SchemaProps: spec.SchemaProps{ - Description: "Requests describes the minimum amount of compute resources required. If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value. Requests cannot exceed Limits. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "claims": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "name", - }, - "x-kubernetes-list-type": "map", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Claims lists the names of resources, defined in spec.resourceClaims, that are used by this container.\n\nThis is an alpha field and requires enabling the DynamicResourceAllocation feature gate.\n\nThis field is immutable. It can only be set for containers.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ResourceClaim"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ResourceClaim", "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_SELinuxOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "SELinuxOptions are the labels to be applied to the container", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "user": { - SchemaProps: spec.SchemaProps{ - Description: "User is a SELinux user label that applies to the container.", - Type: []string{"string"}, - Format: "", - }, - }, - "role": { - SchemaProps: spec.SchemaProps{ - Description: "Role is a SELinux role label that applies to the container.", - Type: []string{"string"}, - Format: "", - }, - }, - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type is a SELinux type label that applies to the container.", - Type: []string{"string"}, - Format: "", - }, - }, - "level": { - SchemaProps: spec.SchemaProps{ - Description: "Level is SELinux level label that applies to the container.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ScaleIOPersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ScaleIOPersistentVolumeSource represents a persistent ScaleIO volume", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "gateway": { - SchemaProps: spec.SchemaProps{ - Description: "gateway is the host address of the ScaleIO API Gateway.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "system": { - SchemaProps: spec.SchemaProps{ - Description: "system is the name of the storage system as configured in ScaleIO.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef references to the secret for ScaleIO user and other sensitive information. If this is not provided, Login operation will fail.", - Ref: ref("k8s.io/api/core/v1.SecretReference"), - }, - }, - "sslEnabled": { - SchemaProps: spec.SchemaProps{ - Description: "sslEnabled is the flag to enable/disable SSL communication with Gateway, default false", - Type: []string{"boolean"}, - Format: "", - }, - }, - "protectionDomain": { - SchemaProps: spec.SchemaProps{ - Description: "protectionDomain is the name of the ScaleIO Protection Domain for the configured storage.", - Type: []string{"string"}, - Format: "", - }, - }, - "storagePool": { - SchemaProps: spec.SchemaProps{ - Description: "storagePool is the ScaleIO Storage Pool associated with the protection domain.", - Type: []string{"string"}, - Format: "", - }, - }, - "storageMode": { - SchemaProps: spec.SchemaProps{ - Description: "storageMode indicates whether the storage for a volume should be ThickProvisioned or ThinProvisioned. Default is ThinProvisioned.", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeName": { - SchemaProps: spec.SchemaProps{ - Description: "volumeName is the name of a volume already created in the ScaleIO system that is associated with this volume source.", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Default is \"xfs\"", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"gateway", "system", "secretRef"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.SecretReference"}, - } -} - -func schema_k8sio_api_core_v1_ScaleIOVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ScaleIOVolumeSource represents a persistent ScaleIO volume", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "gateway": { - SchemaProps: spec.SchemaProps{ - Description: "gateway is the host address of the ScaleIO API Gateway.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "system": { - SchemaProps: spec.SchemaProps{ - Description: "system is the name of the storage system as configured in ScaleIO.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef references to the secret for ScaleIO user and other sensitive information. If this is not provided, Login operation will fail.", - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - "sslEnabled": { - SchemaProps: spec.SchemaProps{ - Description: "sslEnabled Flag enable/disable SSL communication with Gateway, default false", - Type: []string{"boolean"}, - Format: "", - }, - }, - "protectionDomain": { - SchemaProps: spec.SchemaProps{ - Description: "protectionDomain is the name of the ScaleIO Protection Domain for the configured storage.", - Type: []string{"string"}, - Format: "", - }, - }, - "storagePool": { - SchemaProps: spec.SchemaProps{ - Description: "storagePool is the ScaleIO Storage Pool associated with the protection domain.", - Type: []string{"string"}, - Format: "", - }, - }, - "storageMode": { - SchemaProps: spec.SchemaProps{ - Description: "storageMode indicates whether the storage for a volume should be ThickProvisioned or ThinProvisioned. Default is ThinProvisioned.", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeName": { - SchemaProps: spec.SchemaProps{ - Description: "volumeName is the name of a volume already created in the ScaleIO system that is associated with this volume source.", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Default is \"xfs\".", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"gateway", "system", "secretRef"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LocalObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_ScopeSelector(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A scope selector represents the AND of the selectors represented by the scoped-resource selector requirements.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "matchExpressions": { - SchemaProps: spec.SchemaProps{ - Description: "A list of scope selector requirements by scope of the resources.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ScopedResourceSelectorRequirement"), - }, - }, - }, - }, - }, - }, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ScopedResourceSelectorRequirement"}, - } -} - -func schema_k8sio_api_core_v1_ScopedResourceSelectorRequirement(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A scoped-resource selector requirement is a selector that contains values, a scope name, and an operator that relates the scope name and values.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "scopeName": { - SchemaProps: spec.SchemaProps{ - Description: "The name of the scope that the selector applies to.\n\nPossible enum values:\n - `\"BestEffort\"` Match all pod objects that have best effort quality of service\n - `\"CrossNamespacePodAffinity\"` Match all pod objects that have cross-namespace pod (anti)affinity mentioned.\n - `\"NotBestEffort\"` Match all pod objects that do not have best effort quality of service\n - `\"NotTerminating\"` Match all pod objects where spec.activeDeadlineSeconds is nil\n - `\"PriorityClass\"` Match all pod objects that have priority class mentioned\n - `\"Terminating\"` Match all pod objects where spec.activeDeadlineSeconds >=0", - Default: "", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"BestEffort", "CrossNamespacePodAffinity", "NotBestEffort", "NotTerminating", "PriorityClass", "Terminating"}, - }, - }, - "operator": { - SchemaProps: spec.SchemaProps{ - Description: "Represents a scope's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist.\n\nPossible enum values:\n - `\"DoesNotExist\"`\n - `\"Exists\"`\n - `\"In\"`\n - `\"NotIn\"`", - Default: "", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"DoesNotExist", "Exists", "In", "NotIn"}, - }, - }, - "values": { - SchemaProps: spec.SchemaProps{ - Description: "An array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"scopeName", "operator"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_SeccompProfile(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "SeccompProfile defines a pod/container's seccomp profile settings. Only one profile source may be set.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "type indicates which kind of seccomp profile will be applied. Valid options are:\n\nLocalhost - a profile defined in a file on the node should be used. RuntimeDefault - the container runtime default profile should be used. Unconfined - no profile should be applied.\n\nPossible enum values:\n - `\"Localhost\"` indicates a profile defined in a file on the node should be used. The file's location relative to /seccomp.\n - `\"RuntimeDefault\"` represents the default container runtime seccomp profile.\n - `\"Unconfined\"` indicates no seccomp profile is applied (A.K.A. unconfined).", - Default: "", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Localhost", "RuntimeDefault", "Unconfined"}, - }, - }, - "localhostProfile": { - SchemaProps: spec.SchemaProps{ - Description: "localhostProfile indicates a profile defined in a file on the node should be used. The profile must be preconfigured on the node to work. Must be a descending path, relative to the kubelet's configured seccomp profile location. Must be set if type is \"Localhost\". Must NOT be set for any other type.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-unions": []interface{}{ - map[string]interface{}{ - "discriminator": "type", - "fields-to-discriminateBy": map[string]interface{}{ - "localhostProfile": "LocalhostProfile", - }, - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_Secret(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Secret holds secret data of a certain type. The total bytes of the values in the Data field must be less than MaxSecretSize bytes.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "immutable": { - SchemaProps: spec.SchemaProps{ - Description: "Immutable, if set to true, ensures that data stored in the Secret cannot be updated (only object metadata can be modified). If not set to true, the field can be modified at any time. Defaulted to nil.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "data": { - SchemaProps: spec.SchemaProps{ - Description: "Data contains the secret data. Each key must consist of alphanumeric characters, '-', '_' or '.'. The serialized form of the secret data is a base64 encoded string, representing the arbitrary (possibly non-string) data value here. Described in https://tools.ietf.org/html/rfc4648#section-4", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "byte", - }, - }, - }, - }, - }, - "stringData": { - SchemaProps: spec.SchemaProps{ - Description: "stringData allows specifying non-binary secret data in string form. It is provided as a write-only input field for convenience. All keys and values are merged into the data field on write, overwriting any existing values. The stringData field is never output when reading from the API.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Used to facilitate programmatic handling of secret data. More info: https://kubernetes.io/docs/concepts/configuration/secret/#secret-types", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_SecretEnvSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "SecretEnvSource selects a Secret to populate the environment variables with.\n\nThe contents of the target Secret's Data field will represent the key-value pairs as environment variables.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Type: []string{"string"}, - Format: "", - }, - }, - "optional": { - SchemaProps: spec.SchemaProps{ - Description: "Specify whether the Secret must be defined", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_SecretKeySelector(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "SecretKeySelector selects a key of a Secret.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Type: []string{"string"}, - Format: "", - }, - }, - "key": { - SchemaProps: spec.SchemaProps{ - Description: "The key of the secret to select from. Must be a valid secret key.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "optional": { - SchemaProps: spec.SchemaProps{ - Description: "Specify whether the Secret or its key must be defined", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"key"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_SecretList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "SecretList is a list of Secret.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "Items is a list of secret objects. More info: https://kubernetes.io/docs/concepts/configuration/secret", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Secret"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.Secret", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_SecretProjection(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Adapts a secret into a projected volume.\n\nThe contents of the target Secret's Data field will be presented in a projected volume as files using the keys in the Data field as the file names. Note that this is identical to a secret volume source without the default mode.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Type: []string{"string"}, - Format: "", - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "items if unspecified, each key-value pair in the Data field of the referenced Secret will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the Secret, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.KeyToPath"), - }, - }, - }, - }, - }, - "optional": { - SchemaProps: spec.SchemaProps{ - Description: "optional field specify whether the Secret or its key must be defined", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.KeyToPath"}, - } -} - -func schema_k8sio_api_core_v1_SecretReference(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "SecretReference represents a Secret Reference. It has enough information to retrieve secret in any namespace", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "name is unique within a namespace to reference a secret resource.", - Type: []string{"string"}, - Format: "", - }, - }, - "namespace": { - SchemaProps: spec.SchemaProps{ - Description: "namespace defines the space within which the secret name must be unique.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_SecretVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Adapts a Secret into a volume.\n\nThe contents of the target Secret's Data field will be presented in a volume as files using the keys in the Data field as the file names. Secret volumes support ownership management and SELinux relabeling.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "secretName": { - SchemaProps: spec.SchemaProps{ - Description: "secretName is the name of the secret in the pod's namespace to use. More info: https://kubernetes.io/docs/concepts/storage/volumes#secret", - Type: []string{"string"}, - Format: "", - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "items If unspecified, each key-value pair in the Data field of the referenced Secret will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the Secret, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.KeyToPath"), - }, - }, - }, - }, - }, - "defaultMode": { - SchemaProps: spec.SchemaProps{ - Description: "defaultMode is Optional: mode bits used to set permissions on created files by default. Must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "optional": { - SchemaProps: spec.SchemaProps{ - Description: "optional field specify whether the Secret or its keys must be defined", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.KeyToPath"}, - } -} - -func schema_k8sio_api_core_v1_SecurityContext(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "SecurityContext holds security configuration that will be applied to a container. Some fields are present in both SecurityContext and PodSecurityContext. When both are set, the values in SecurityContext take precedence.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "capabilities": { - SchemaProps: spec.SchemaProps{ - Description: "The capabilities to add/drop when running containers. Defaults to the default set of capabilities granted by the container runtime. Note that this field cannot be set when spec.os.name is windows.", - Ref: ref("k8s.io/api/core/v1.Capabilities"), - }, - }, - "privileged": { - SchemaProps: spec.SchemaProps{ - Description: "Run container in privileged mode. Processes in privileged containers are essentially equivalent to root on the host. Defaults to false. Note that this field cannot be set when spec.os.name is windows.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "seLinuxOptions": { - SchemaProps: spec.SchemaProps{ - Description: "The SELinux context to be applied to the container. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. Note that this field cannot be set when spec.os.name is windows.", - Ref: ref("k8s.io/api/core/v1.SELinuxOptions"), - }, - }, - "windowsOptions": { - SchemaProps: spec.SchemaProps{ - Description: "The Windows specific settings applied to all containers. If unspecified, the options from the PodSecurityContext will be used. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. Note that this field cannot be set when spec.os.name is linux.", - Ref: ref("k8s.io/api/core/v1.WindowsSecurityContextOptions"), - }, - }, - "runAsUser": { - SchemaProps: spec.SchemaProps{ - Description: "The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. Note that this field cannot be set when spec.os.name is windows.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "runAsGroup": { - SchemaProps: spec.SchemaProps{ - Description: "The GID to run the entrypoint of the container process. Uses runtime default if unset. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. Note that this field cannot be set when spec.os.name is windows.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "runAsNonRoot": { - SchemaProps: spec.SchemaProps{ - Description: "Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. If unset or false, no such validation will be performed. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "readOnlyRootFilesystem": { - SchemaProps: spec.SchemaProps{ - Description: "Whether this container has a read-only root filesystem. Default is false. Note that this field cannot be set when spec.os.name is windows.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "allowPrivilegeEscalation": { - SchemaProps: spec.SchemaProps{ - Description: "AllowPrivilegeEscalation controls whether a process can gain more privileges than its parent process. This bool directly controls if the no_new_privs flag will be set on the container process. AllowPrivilegeEscalation is true always when the container is: 1) run as Privileged 2) has CAP_SYS_ADMIN Note that this field cannot be set when spec.os.name is windows.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "procMount": { - SchemaProps: spec.SchemaProps{ - Description: "procMount denotes the type of proc mount to use for the containers. The default is DefaultProcMount which uses the container runtime defaults for readonly paths and masked paths. This requires the ProcMountType feature flag to be enabled. Note that this field cannot be set when spec.os.name is windows.\n\nPossible enum values:\n - `\"Default\"` uses the container runtime defaults for readonly and masked paths for /proc. Most container runtimes mask certain paths in /proc to avoid accidental security exposure of special devices or information.\n - `\"Unmasked\"` bypasses the default masking behavior of the container runtime and ensures the newly created /proc the container stays in tact with no modifications.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Default", "Unmasked"}, - }, - }, - "seccompProfile": { - SchemaProps: spec.SchemaProps{ - Description: "The seccomp options to use by this container. If seccomp options are provided at both the pod & container level, the container options override the pod options. Note that this field cannot be set when spec.os.name is windows.", - Ref: ref("k8s.io/api/core/v1.SeccompProfile"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.Capabilities", "k8s.io/api/core/v1.SELinuxOptions", "k8s.io/api/core/v1.SeccompProfile", "k8s.io/api/core/v1.WindowsSecurityContextOptions"}, - } -} - -func schema_k8sio_api_core_v1_SerializedReference(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "SerializedReference is a reference to serialized object.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "reference": { - SchemaProps: spec.SchemaProps{ - Description: "The reference to an object in the system.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ObjectReference"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_Service(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Service is a named abstraction of software service (for example, mysql) consisting of local port (for example 3306) that the proxy listens on, and the selector that determines which pods will answer requests sent through the proxy.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Description: "Spec defines the behavior of a service. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ServiceSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Most recently observed status of the service. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ServiceStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ServiceSpec", "k8s.io/api/core/v1.ServiceStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_ServiceAccount(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ServiceAccount binds together: * a name, understood by users, and perhaps by peripheral systems, for an identity * a principal that can be authenticated and authorized * a set of secrets", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "secrets": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Secrets is a list of the secrets in the same namespace that pods running using this ServiceAccount are allowed to use. Pods are only limited to this list if this service account has a \"kubernetes.io/enforce-mountable-secrets\" annotation set to \"true\". This field should not be used to find auto-generated service account token secrets for use outside of pods. Instead, tokens can be requested directly using the TokenRequest API, or service account token secrets can be manually created. More info: https://kubernetes.io/docs/concepts/configuration/secret", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ObjectReference"), - }, - }, - }, - }, - }, - "imagePullSecrets": { - SchemaProps: spec.SchemaProps{ - Description: "ImagePullSecrets is a list of references to secrets in the same namespace to use for pulling any images in pods that reference this ServiceAccount. ImagePullSecrets are distinct from Secrets because Secrets can be mounted in the pod, but ImagePullSecrets are only accessed by the kubelet. More info: https://kubernetes.io/docs/concepts/containers/images/#specifying-imagepullsecrets-on-a-pod", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - }, - }, - }, - "automountServiceAccountToken": { - SchemaProps: spec.SchemaProps{ - Description: "AutomountServiceAccountToken indicates whether pods running as this service account should have an API token automatically mounted. Can be overridden at the pod level.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LocalObjectReference", "k8s.io/api/core/v1.ObjectReference", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_k8sio_api_core_v1_ServiceAccountList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ServiceAccountList is a list of ServiceAccount objects", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of ServiceAccounts. More info: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ServiceAccount"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ServiceAccount", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_ServiceAccountTokenProjection(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ServiceAccountTokenProjection represents a projected service account token volume. This projection can be used to insert a service account token into the pods runtime filesystem for use against APIs (Kubernetes API Server or otherwise).", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "audience": { - SchemaProps: spec.SchemaProps{ - Description: "audience is the intended audience of the token. A recipient of a token must identify itself with an identifier specified in the audience of the token, and otherwise should reject the token. The audience defaults to the identifier of the apiserver.", - Type: []string{"string"}, - Format: "", - }, - }, - "expirationSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "expirationSeconds is the requested duration of validity of the service account token. As the token approaches expiration, the kubelet volume plugin will proactively rotate the service account token. The kubelet will start trying to rotate the token if the token is older than 80 percent of its time to live or if the token is older than 24 hours.Defaults to 1 hour and must be at least 10 minutes.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "path is the path relative to the mount point of the file to project the token into.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"path"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ServiceList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ServiceList holds a list of services.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of services", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.Service"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.Service", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, - } -} - -func schema_k8sio_api_core_v1_ServicePort(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ServicePort contains information on service's port.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "The name of this port within the service. This must be a DNS_LABEL. All ports within a ServiceSpec must have unique names. When considering the endpoints for a Service, this must match the 'name' field in the EndpointPort. Optional if only one ServicePort is defined on this service.", - Type: []string{"string"}, - Format: "", - }, - }, - "protocol": { - SchemaProps: spec.SchemaProps{ - Description: "The IP protocol for this port. Supports \"TCP\", \"UDP\", and \"SCTP\". Default is TCP.\n\nPossible enum values:\n - `\"SCTP\"` is the SCTP protocol.\n - `\"TCP\"` is the TCP protocol.\n - `\"UDP\"` is the UDP protocol.", - Default: "TCP", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"SCTP", "TCP", "UDP"}, - }, - }, - "appProtocol": { - SchemaProps: spec.SchemaProps{ - Description: "The application protocol for this port. This is used as a hint for implementations to offer richer behavior for protocols that they understand. This field follows standard Kubernetes label syntax. Valid values are either:\n\n* Un-prefixed protocol names - reserved for IANA standard service names (as per RFC-6335 and https://www.iana.org/assignments/service-names).\n\n* Kubernetes-defined prefixed names:\n * 'kubernetes.io/h2c' - HTTP/2 prior knowledge over cleartext as described in https://www.rfc-editor.org/rfc/rfc9113.html#name-starting-http-2-with-prior-\n * 'kubernetes.io/ws' - WebSocket over cleartext as described in https://www.rfc-editor.org/rfc/rfc6455\n * 'kubernetes.io/wss' - WebSocket over TLS as described in https://www.rfc-editor.org/rfc/rfc6455\n\n* Other protocols should use implementation-defined prefixed names such as mycompany.com/my-custom-protocol.", - Type: []string{"string"}, - Format: "", - }, - }, - "port": { - SchemaProps: spec.SchemaProps{ - Description: "The port that will be exposed by this service.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "targetPort": { - SchemaProps: spec.SchemaProps{ - Description: "Number or name of the port to access on the pods targeted by the service. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME. If this is a string, it will be looked up as a named port in the target Pod's container ports. If this is not specified, the value of the 'port' field is used (an identity map). This field is ignored for services with clusterIP=None, and should be omitted or set equal to the 'port' field. More info: https://kubernetes.io/docs/concepts/services-networking/service/#defining-a-service", - Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), - }, - }, - "nodePort": { - SchemaProps: spec.SchemaProps{ - Description: "The port on each node on which this service is exposed when type is NodePort or LoadBalancer. Usually assigned by the system. If a value is specified, in-range, and not in use it will be used, otherwise the operation will fail. If not specified, a port will be allocated if this Service requires one. If this field is specified when creating a Service which does not need it, creation will fail. This field will be wiped when updating a Service to no longer need it (e.g. changing type from NodePort to ClusterIP). More info: https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport", - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - Required: []string{"port"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/util/intstr.IntOrString"}, - } -} - -func schema_k8sio_api_core_v1_ServiceProxyOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ServiceProxyOptions is the query options to a Service's proxy call.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "path": { - SchemaProps: spec.SchemaProps{ - Description: "Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_ServiceSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ServiceSpec describes the attributes that a user creates on a service.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "ports": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "port", - "protocol", - }, - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "port", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "The list of ports that are exposed by this service. More info: https://kubernetes.io/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ServicePort"), - }, - }, - }, - }, - }, - "selector": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Route service traffic to pods with label keys and values matching this selector. If empty or not present, the service is assumed to have an external process managing its endpoints, which Kubernetes will not modify. Only applies to types ClusterIP, NodePort, and LoadBalancer. Ignored if type is ExternalName. More info: https://kubernetes.io/docs/concepts/services-networking/service/", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "clusterIP": { - SchemaProps: spec.SchemaProps{ - Description: "clusterIP is the IP address of the service and is usually assigned randomly. If an address is specified manually, is in-range (as per system configuration), and is not in use, it will be allocated to the service; otherwise creation of the service will fail. This field may not be changed through updates unless the type field is also being changed to ExternalName (which requires this field to be blank) or the type field is being changed from ExternalName (in which case this field may optionally be specified, as describe above). Valid values are \"None\", empty string (\"\"), or a valid IP address. Setting this to \"None\" makes a \"headless service\" (no virtual IP), which is useful when direct endpoint connections are preferred and proxying is not required. Only applies to types ClusterIP, NodePort, and LoadBalancer. If this field is specified when creating a Service of type ExternalName, creation will fail. This field will be wiped when updating a Service to type ExternalName. More info: https://kubernetes.io/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies", - Type: []string{"string"}, - Format: "", - }, - }, - "clusterIPs": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "ClusterIPs is a list of IP addresses assigned to this service, and are usually assigned randomly. If an address is specified manually, is in-range (as per system configuration), and is not in use, it will be allocated to the service; otherwise creation of the service will fail. This field may not be changed through updates unless the type field is also being changed to ExternalName (which requires this field to be empty) or the type field is being changed from ExternalName (in which case this field may optionally be specified, as describe above). Valid values are \"None\", empty string (\"\"), or a valid IP address. Setting this to \"None\" makes a \"headless service\" (no virtual IP), which is useful when direct endpoint connections are preferred and proxying is not required. Only applies to types ClusterIP, NodePort, and LoadBalancer. If this field is specified when creating a Service of type ExternalName, creation will fail. This field will be wiped when updating a Service to type ExternalName. If this field is not specified, it will be initialized from the clusterIP field. If this field is specified, clients must ensure that clusterIPs[0] and clusterIP have the same value.\n\nThis field may hold a maximum of two entries (dual-stack IPs, in either order). These IPs must correspond to the values of the ipFamilies field. Both clusterIPs and ipFamilies are governed by the ipFamilyPolicy field. More info: https://kubernetes.io/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "type": { - SchemaProps: spec.SchemaProps{ - Description: "type determines how the Service is exposed. Defaults to ClusterIP. Valid options are ExternalName, ClusterIP, NodePort, and LoadBalancer. \"ClusterIP\" allocates a cluster-internal IP address for load-balancing to endpoints. Endpoints are determined by the selector or if that is not specified, by manual construction of an Endpoints object or EndpointSlice objects. If clusterIP is \"None\", no virtual IP is allocated and the endpoints are published as a set of endpoints rather than a virtual IP. \"NodePort\" builds on ClusterIP and allocates a port on every node which routes to the same endpoints as the clusterIP. \"LoadBalancer\" builds on NodePort and creates an external load-balancer (if supported in the current cloud) which routes to the same endpoints as the clusterIP. \"ExternalName\" aliases this service to the specified externalName. Several other fields do not apply to ExternalName services. More info: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types\n\nPossible enum values:\n - `\"ClusterIP\"` means a service will only be accessible inside the cluster, via the cluster IP.\n - `\"ExternalName\"` means a service consists of only a reference to an external name that kubedns or equivalent will return as a CNAME record, with no exposing or proxying of any pods involved.\n - `\"LoadBalancer\"` means a service will be exposed via an external load balancer (if the cloud provider supports it), in addition to 'NodePort' type.\n - `\"NodePort\"` means a service will be exposed on one port of every node, in addition to 'ClusterIP' type.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"ClusterIP", "ExternalName", "LoadBalancer", "NodePort"}, - }, - }, - "externalIPs": { - SchemaProps: spec.SchemaProps{ - Description: "externalIPs is a list of IP addresses for which nodes in the cluster will also accept traffic for this service. These IPs are not managed by Kubernetes. The user is responsible for ensuring that traffic arrives at a node with this IP. A common example is external load-balancers that are not part of the Kubernetes system.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "sessionAffinity": { - SchemaProps: spec.SchemaProps{ - Description: "Supports \"ClientIP\" and \"None\". Used to maintain session affinity. Enable client IP based session affinity. Must be ClientIP or None. Defaults to None. More info: https://kubernetes.io/docs/concepts/services-networking/service/#virtual-ips-and-service-proxies\n\nPossible enum values:\n - `\"ClientIP\"` is the Client IP based.\n - `\"None\"` - no session affinity.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"ClientIP", "None"}, - }, - }, - "loadBalancerIP": { - SchemaProps: spec.SchemaProps{ - Description: "Only applies to Service Type: LoadBalancer. This feature depends on whether the underlying cloud-provider supports specifying the loadBalancerIP when a load balancer is created. This field will be ignored if the cloud-provider does not support the feature. Deprecated: This field was under-specified and its meaning varies across implementations. Using it is non-portable and it may not support dual-stack. Users are encouraged to use implementation-specific annotations when available.", - Type: []string{"string"}, - Format: "", - }, - }, - "loadBalancerSourceRanges": { - SchemaProps: spec.SchemaProps{ - Description: "If specified and supported by the platform, this will restrict traffic through the cloud-provider load-balancer will be restricted to the specified client IPs. This field will be ignored if the cloud-provider does not support the feature.\" More info: https://kubernetes.io/docs/tasks/access-application-cluster/create-external-load-balancer/", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "externalName": { - SchemaProps: spec.SchemaProps{ - Description: "externalName is the external reference that discovery mechanisms will return as an alias for this service (e.g. a DNS CNAME record). No proxying will be involved. Must be a lowercase RFC-1123 hostname (https://tools.ietf.org/html/rfc1123) and requires `type` to be \"ExternalName\".", - Type: []string{"string"}, - Format: "", - }, - }, - "externalTrafficPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "externalTrafficPolicy describes how nodes distribute service traffic they receive on one of the Service's \"externally-facing\" addresses (NodePorts, ExternalIPs, and LoadBalancer IPs). If set to \"Local\", the proxy will configure the service in a way that assumes that external load balancers will take care of balancing the service traffic between nodes, and so each node will deliver traffic only to the node-local endpoints of the service, without masquerading the client source IP. (Traffic mistakenly sent to a node with no endpoints will be dropped.) The default value, \"Cluster\", uses the standard behavior of routing to all endpoints evenly (possibly modified by topology and other features). Note that traffic sent to an External IP or LoadBalancer IP from within the cluster will always get \"Cluster\" semantics, but clients sending to a NodePort from within the cluster may need to take traffic policy into account when picking a node.\n\nPossible enum values:\n - `\"Cluster\"`\n - `\"Cluster\"` routes traffic to all endpoints.\n - `\"Local\"`\n - `\"Local\"` preserves the source IP of the traffic by routing only to endpoints on the same node as the traffic was received on (dropping the traffic if there are no local endpoints).", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Cluster", "Cluster", "Local", "Local"}, - }, - }, - "healthCheckNodePort": { - SchemaProps: spec.SchemaProps{ - Description: "healthCheckNodePort specifies the healthcheck nodePort for the service. This only applies when type is set to LoadBalancer and externalTrafficPolicy is set to Local. If a value is specified, is in-range, and is not in use, it will be used. If not specified, a value will be automatically allocated. External systems (e.g. load-balancers) can use this port to determine if a given node holds endpoints for this service or not. If this field is specified when creating a Service which does not need it, creation will fail. This field will be wiped when updating a Service to no longer need it (e.g. changing type). This field cannot be updated once set.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "publishNotReadyAddresses": { - SchemaProps: spec.SchemaProps{ - Description: "publishNotReadyAddresses indicates that any agent which deals with endpoints for this Service should disregard any indications of ready/not-ready. The primary use case for setting this field is for a StatefulSet's Headless Service to propagate SRV DNS records for its Pods for the purpose of peer discovery. The Kubernetes controllers that generate Endpoints and EndpointSlice resources for Services interpret this to mean that all endpoints are considered \"ready\" even if the Pods themselves are not. Agents which consume only Kubernetes generated endpoints through the Endpoints or EndpointSlice resources can safely assume this behavior.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "sessionAffinityConfig": { - SchemaProps: spec.SchemaProps{ - Description: "sessionAffinityConfig contains the configurations of session affinity.", - Ref: ref("k8s.io/api/core/v1.SessionAffinityConfig"), - }, - }, - "ipFamilies": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "IPFamilies is a list of IP families (e.g. IPv4, IPv6) assigned to this service. This field is usually assigned automatically based on cluster configuration and the ipFamilyPolicy field. If this field is specified manually, the requested family is available in the cluster, and ipFamilyPolicy allows it, it will be used; otherwise creation of the service will fail. This field is conditionally mutable: it allows for adding or removing a secondary IP family, but it does not allow changing the primary IP family of the Service. Valid values are \"IPv4\" and \"IPv6\". This field only applies to Services of types ClusterIP, NodePort, and LoadBalancer, and does apply to \"headless\" services. This field will be wiped when updating a Service to type ExternalName.\n\nThis field may hold a maximum of two entries (dual-stack families, in either order). These families must correspond to the values of the clusterIPs field, if specified. Both clusterIPs and ipFamilies are governed by the ipFamilyPolicy field.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "ipFamilyPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "IPFamilyPolicy represents the dual-stack-ness requested or required by this Service. If there is no value provided, then this field will be set to SingleStack. Services can be \"SingleStack\" (a single IP family), \"PreferDualStack\" (two IP families on dual-stack configured clusters or a single IP family on single-stack clusters), or \"RequireDualStack\" (two IP families on dual-stack configured clusters, otherwise fail). The ipFamilies and clusterIPs fields depend on the value of this field. This field will be wiped when updating a service to type ExternalName.\n\nPossible enum values:\n - `\"PreferDualStack\"` indicates that this service prefers dual-stack when the cluster is configured for dual-stack. If the cluster is not configured for dual-stack the service will be assigned a single IPFamily. If the IPFamily is not set in service.spec.ipFamilies then the service will be assigned the default IPFamily configured on the cluster\n - `\"RequireDualStack\"` indicates that this service requires dual-stack. Using IPFamilyPolicyRequireDualStack on a single stack cluster will result in validation errors. The IPFamilies (and their order) assigned to this service is based on service.spec.ipFamilies. If service.spec.ipFamilies was not provided then it will be assigned according to how they are configured on the cluster. If service.spec.ipFamilies has only one entry then the alternative IPFamily will be added by apiserver\n - `\"SingleStack\"` indicates that this service is required to have a single IPFamily. The IPFamily assigned is based on the default IPFamily used by the cluster or as identified by service.spec.ipFamilies field", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"PreferDualStack", "RequireDualStack", "SingleStack"}, - }, - }, - "allocateLoadBalancerNodePorts": { - SchemaProps: spec.SchemaProps{ - Description: "allocateLoadBalancerNodePorts defines if NodePorts will be automatically allocated for services with type LoadBalancer. Default is \"true\". It may be set to \"false\" if the cluster load-balancer does not rely on NodePorts. If the caller requests specific NodePorts (by specifying a value), those requests will be respected, regardless of this field. This field may only be set for services with type LoadBalancer and will be cleared if the type is changed to any other type.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "loadBalancerClass": { - SchemaProps: spec.SchemaProps{ - Description: "loadBalancerClass is the class of the load balancer implementation this Service belongs to. If specified, the value of this field must be a label-style identifier, with an optional prefix, e.g. \"internal-vip\" or \"example.com/internal-vip\". Unprefixed names are reserved for end-users. This field can only be set when the Service type is 'LoadBalancer'. If not set, the default load balancer implementation is used, today this is typically done through the cloud provider integration, but should apply for any default implementation. If set, it is assumed that a load balancer implementation is watching for Services with a matching class. Any default load balancer implementation (e.g. cloud providers) should ignore Services that set this field. This field can only be set when creating or updating a Service to type 'LoadBalancer'. Once set, it can not be changed. This field will be wiped when a service is updated to a non 'LoadBalancer' type.", - Type: []string{"string"}, - Format: "", - }, - }, - "internalTrafficPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "InternalTrafficPolicy describes how nodes distribute service traffic they receive on the ClusterIP. If set to \"Local\", the proxy will assume that pods only want to talk to endpoints of the service on the same node as the pod, dropping the traffic if there are no local endpoints. The default value, \"Cluster\", uses the standard behavior of routing to all endpoints evenly (possibly modified by topology and other features).\n\nPossible enum values:\n - `\"Cluster\"` routes traffic to all endpoints.\n - `\"Local\"` routes traffic only to endpoints on the same node as the client pod (dropping the traffic if there are no local endpoints).", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Cluster", "Local"}, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ServicePort", "k8s.io/api/core/v1.SessionAffinityConfig"}, - } -} - -func schema_k8sio_api_core_v1_ServiceStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ServiceStatus represents the current status of a service.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "loadBalancer": { - SchemaProps: spec.SchemaProps{ - Description: "LoadBalancer contains the current status of the load-balancer, if one is present.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.LoadBalancerStatus"), - }, - }, - "conditions": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "type", - }, - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Current service state", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Condition"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LoadBalancerStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.Condition"}, - } -} - -func schema_k8sio_api_core_v1_SessionAffinityConfig(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "SessionAffinityConfig represents the configurations of session affinity.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "clientIP": { - SchemaProps: spec.SchemaProps{ - Description: "clientIP contains the configurations of Client IP based session affinity.", - Ref: ref("k8s.io/api/core/v1.ClientIPConfig"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ClientIPConfig"}, - } -} - -func schema_k8sio_api_core_v1_SleepAction(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "SleepAction describes a \"sleep\" action.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "seconds": { - SchemaProps: spec.SchemaProps{ - Description: "Seconds is the number of seconds to sleep.", - Default: 0, - Type: []string{"integer"}, - Format: "int64", - }, - }, - }, - Required: []string{"seconds"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_StorageOSPersistentVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a StorageOS persistent volume resource.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "volumeName": { - SchemaProps: spec.SchemaProps{ - Description: "volumeName is the human-readable name of the StorageOS volume. Volume names are only unique within a namespace.", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeNamespace": { - SchemaProps: spec.SchemaProps{ - Description: "volumeNamespace specifies the scope of the volume within StorageOS. If no namespace is specified then the Pod's namespace will be used. This allows the Kubernetes name scoping to be mirrored within StorageOS for tighter integration. Set VolumeName to any name to override the default behaviour. Set to \"default\" if you are not using namespaces within StorageOS. Namespaces that do not pre-exist within StorageOS will be created.", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef specifies the secret to use for obtaining the StorageOS API credentials. If not specified, default values will be attempted.", - Ref: ref("k8s.io/api/core/v1.ObjectReference"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_StorageOSVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a StorageOS persistent volume resource.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "volumeName": { - SchemaProps: spec.SchemaProps{ - Description: "volumeName is the human-readable name of the StorageOS volume. Volume names are only unique within a namespace.", - Type: []string{"string"}, - Format: "", - }, - }, - "volumeNamespace": { - SchemaProps: spec.SchemaProps{ - Description: "volumeNamespace specifies the scope of the volume within StorageOS. If no namespace is specified then the Pod's namespace will be used. This allows the Kubernetes name scoping to be mirrored within StorageOS for tighter integration. Set VolumeName to any name to override the default behaviour. Set to \"default\" if you are not using namespaces within StorageOS. Namespaces that do not pre-exist within StorageOS will be created.", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "secretRef": { - SchemaProps: spec.SchemaProps{ - Description: "secretRef specifies the secret to use for obtaining the StorageOS API credentials. If not specified, default values will be attempted.", - Ref: ref("k8s.io/api/core/v1.LocalObjectReference"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.LocalObjectReference"}, - } -} - -func schema_k8sio_api_core_v1_Sysctl(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Sysctl defines a kernel parameter to be set", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of a property to set", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "value": { - SchemaProps: spec.SchemaProps{ - Description: "Value of a property to set", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name", "value"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_TCPSocketAction(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "TCPSocketAction describes an action based on opening a socket", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "port": { - SchemaProps: spec.SchemaProps{ - Description: "Number or name of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME.", - Ref: ref("k8s.io/apimachinery/pkg/util/intstr.IntOrString"), - }, - }, - "host": { - SchemaProps: spec.SchemaProps{ - Description: "Optional: Host name to connect to, defaults to the pod IP.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"port"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/util/intstr.IntOrString"}, - } -} - -func schema_k8sio_api_core_v1_Taint(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "The node this Taint is attached to has the \"effect\" on any pod that does not tolerate the Taint.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "key": { - SchemaProps: spec.SchemaProps{ - Description: "Required. The taint key to be applied to a node.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "value": { - SchemaProps: spec.SchemaProps{ - Description: "The taint value corresponding to the taint key.", - Type: []string{"string"}, - Format: "", - }, - }, - "effect": { - SchemaProps: spec.SchemaProps{ - Description: "Required. The effect of the taint on pods that do not tolerate the taint. Valid effects are NoSchedule, PreferNoSchedule and NoExecute.\n\nPossible enum values:\n - `\"NoExecute\"` Evict any already-running pods that do not tolerate the taint. Currently enforced by NodeController.\n - `\"NoSchedule\"` Do not allow new pods to schedule onto the node unless they tolerate the taint, but allow all pods submitted to Kubelet without going through the scheduler to start, and allow all already-running pods to continue running. Enforced by the scheduler.\n - `\"PreferNoSchedule\"` Like TaintEffectNoSchedule, but the scheduler tries not to schedule new pods onto the node, rather than prohibiting new pods from scheduling onto the node entirely. Enforced by the scheduler.", - Default: "", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"NoExecute", "NoSchedule", "PreferNoSchedule"}, - }, - }, - "timeAdded": { - SchemaProps: spec.SchemaProps{ - Description: "TimeAdded represents the time at which the taint was added. It is only written for NoExecute taints.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - }, - Required: []string{"key", "effect"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_k8sio_api_core_v1_Toleration(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "The pod this Toleration is attached to tolerates any taint that matches the triple using the matching operator .", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "key": { - SchemaProps: spec.SchemaProps{ - Description: "Key is the taint key that the toleration applies to. Empty means match all taint keys. If the key is empty, operator must be Exists; this combination means to match all values and all keys.", - Type: []string{"string"}, - Format: "", - }, - }, - "operator": { - SchemaProps: spec.SchemaProps{ - Description: "Operator represents a key's relationship to the value. Valid operators are Exists and Equal. Defaults to Equal. Exists is equivalent to wildcard for value, so that a pod can tolerate all taints of a particular category.\n\nPossible enum values:\n - `\"Equal\"`\n - `\"Exists\"`", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Equal", "Exists"}, - }, - }, - "value": { - SchemaProps: spec.SchemaProps{ - Description: "Value is the taint value the toleration matches to. If the operator is Exists, the value should be empty, otherwise just a regular string.", - Type: []string{"string"}, - Format: "", - }, - }, - "effect": { - SchemaProps: spec.SchemaProps{ - Description: "Effect indicates the taint effect to match. Empty means match all taint effects. When specified, allowed values are NoSchedule, PreferNoSchedule and NoExecute.\n\nPossible enum values:\n - `\"NoExecute\"` Evict any already-running pods that do not tolerate the taint. Currently enforced by NodeController.\n - `\"NoSchedule\"` Do not allow new pods to schedule onto the node unless they tolerate the taint, but allow all pods submitted to Kubelet without going through the scheduler to start, and allow all already-running pods to continue running. Enforced by the scheduler.\n - `\"PreferNoSchedule\"` Like TaintEffectNoSchedule, but the scheduler tries not to schedule new pods onto the node, rather than prohibiting new pods from scheduling onto the node entirely. Enforced by the scheduler.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"NoExecute", "NoSchedule", "PreferNoSchedule"}, - }, - }, - "tolerationSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "TolerationSeconds represents the period of time the toleration (which must be of effect NoExecute, otherwise this field is ignored) tolerates the taint. By default, it is not set, which means tolerate the taint forever (do not evict). Zero and negative values will be treated as 0 (evict immediately) by the system.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_TopologySelectorLabelRequirement(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A topology selector requirement is a selector that matches given label. This is an alpha feature and may change in the future.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "key": { - SchemaProps: spec.SchemaProps{ - Description: "The label key that the selector applies to.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "values": { - SchemaProps: spec.SchemaProps{ - Description: "An array of string values. One value must match the label to be selected. Each entry in Values is ORed.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"key", "values"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_TopologySelectorTerm(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A topology selector term represents the result of label queries. A null or empty topology selector term matches no objects. The requirements of them are ANDed. It provides a subset of functionality as NodeSelectorTerm. This is an alpha feature and may change in the future.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "matchLabelExpressions": { - SchemaProps: spec.SchemaProps{ - Description: "A list of topology selector requirements by labels.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.TopologySelectorLabelRequirement"), - }, - }, - }, - }, - }, - }, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.TopologySelectorLabelRequirement"}, - } -} - -func schema_k8sio_api_core_v1_TopologySpreadConstraint(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "TopologySpreadConstraint specifies how to spread matching pods among the given topology.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "maxSkew": { - SchemaProps: spec.SchemaProps{ - Description: "MaxSkew describes the degree to which pods may be unevenly distributed. When `whenUnsatisfiable=DoNotSchedule`, it is the maximum permitted difference between the number of matching pods in the target topology and the global minimum. The global minimum is the minimum number of matching pods in an eligible domain or zero if the number of eligible domains is less than MinDomains. For example, in a 3-zone cluster, MaxSkew is set to 1, and pods with the same labelSelector spread as 2/2/1: In this case, the global minimum is 1. | zone1 | zone2 | zone3 | | P P | P P | P | - if MaxSkew is 1, incoming pod can only be scheduled to zone3 to become 2/2/2; scheduling it onto zone1(zone2) would make the ActualSkew(3-1) on zone1(zone2) violate MaxSkew(1). - if MaxSkew is 2, incoming pod can be scheduled onto any zone. When `whenUnsatisfiable=ScheduleAnyway`, it is used to give higher precedence to topologies that satisfy it. It's a required field. Default value is 1 and 0 is not allowed.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "topologyKey": { - SchemaProps: spec.SchemaProps{ - Description: "TopologyKey is the key of node labels. Nodes that have a label with this key and identical values are considered to be in the same topology. We consider each as a \"bucket\", and try to put balanced number of pods into each bucket. We define a domain as a particular instance of a topology. Also, we define an eligible domain as a domain whose nodes meet the requirements of nodeAffinityPolicy and nodeTaintsPolicy. e.g. If TopologyKey is \"kubernetes.io/hostname\", each Node is a domain of that topology. And, if TopologyKey is \"topology.kubernetes.io/zone\", each zone is a domain of that topology. It's a required field.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "whenUnsatisfiable": { - SchemaProps: spec.SchemaProps{ - Description: "WhenUnsatisfiable indicates how to deal with a pod if it doesn't satisfy the spread constraint. - DoNotSchedule (default) tells the scheduler not to schedule it. - ScheduleAnyway tells the scheduler to schedule the pod in any location,\n but giving higher precedence to topologies that would help reduce the\n skew.\nA constraint is considered \"Unsatisfiable\" for an incoming pod if and only if every possible node assignment for that pod would violate \"MaxSkew\" on some topology. For example, in a 3-zone cluster, MaxSkew is set to 1, and pods with the same labelSelector spread as 3/1/1: | zone1 | zone2 | zone3 | | P P P | P | P | If WhenUnsatisfiable is set to DoNotSchedule, incoming pod can only be scheduled to zone2(zone3) to become 3/2/1(3/1/2) as ActualSkew(2-1) on zone2(zone3) satisfies MaxSkew(1). In other words, the cluster can still be imbalanced, but scheduler won't make it *more* imbalanced. It's a required field.\n\nPossible enum values:\n - `\"DoNotSchedule\"` instructs the scheduler not to schedule the pod when constraints are not satisfied.\n - `\"ScheduleAnyway\"` instructs the scheduler to schedule the pod even if constraints are not satisfied.", - Default: "", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"DoNotSchedule", "ScheduleAnyway"}, - }, - }, - "labelSelector": { - SchemaProps: spec.SchemaProps{ - Description: "LabelSelector is used to find matching pods. Pods that match this label selector are counted to determine the number of pods in their corresponding topology domain.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), - }, - }, - "minDomains": { - SchemaProps: spec.SchemaProps{ - Description: "MinDomains indicates a minimum number of eligible domains. When the number of eligible domains with matching topology keys is less than minDomains, Pod Topology Spread treats \"global minimum\" as 0, and then the calculation of Skew is performed. And when the number of eligible domains with matching topology keys equals or greater than minDomains, this value has no effect on scheduling. As a result, when the number of eligible domains is less than minDomains, scheduler won't schedule more than maxSkew Pods to those domains. If value is nil, the constraint behaves as if MinDomains is equal to 1. Valid values are integers greater than 0. When value is not nil, WhenUnsatisfiable must be DoNotSchedule.\n\nFor example, in a 3-zone cluster, MaxSkew is set to 2, MinDomains is set to 5 and pods with the same labelSelector spread as 2/2/2: | zone1 | zone2 | zone3 | | P P | P P | P P | The number of domains is less than 5(MinDomains), so \"global minimum\" is treated as 0. In this situation, new pod with the same labelSelector cannot be scheduled, because computed skew will be 3(3 - 0) if new Pod is scheduled to any of the three zones, it will violate MaxSkew.\n\nThis is a beta field and requires the MinDomainsInPodTopologySpread feature gate to be enabled (enabled by default).", - Type: []string{"integer"}, - Format: "int32", - }, - }, - "nodeAffinityPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "NodeAffinityPolicy indicates how we will treat Pod's nodeAffinity/nodeSelector when calculating pod topology spread skew. Options are: - Honor: only nodes matching nodeAffinity/nodeSelector are included in the calculations. - Ignore: nodeAffinity/nodeSelector are ignored. All nodes are included in the calculations.\n\nIf this value is nil, the behavior is equivalent to the Honor policy. This is a beta-level feature default enabled by the NodeInclusionPolicyInPodTopologySpread feature flag.\n\nPossible enum values:\n - `\"Honor\"` means use this scheduling directive when calculating pod topology spread skew.\n - `\"Ignore\"` means ignore this scheduling directive when calculating pod topology spread skew.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Honor", "Ignore"}, - }, - }, - "nodeTaintsPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "NodeTaintsPolicy indicates how we will treat node taints when calculating pod topology spread skew. Options are: - Honor: nodes without taints, along with tainted nodes for which the incoming pod has a toleration, are included. - Ignore: node taints are ignored. All nodes are included.\n\nIf this value is nil, the behavior is equivalent to the Ignore policy. This is a beta-level feature default enabled by the NodeInclusionPolicyInPodTopologySpread feature flag.\n\nPossible enum values:\n - `\"Honor\"` means use this scheduling directive when calculating pod topology spread skew.\n - `\"Ignore\"` means ignore this scheduling directive when calculating pod topology spread skew.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Honor", "Ignore"}, - }, - }, - "matchLabelKeys": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-type": "atomic", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "MatchLabelKeys is a set of pod label keys to select the pods over which spreading will be calculated. The keys are used to lookup values from the incoming pod labels, those key-value labels are ANDed with labelSelector to select the group of existing pods over which spreading will be calculated for the incoming pod. The same key is forbidden to exist in both MatchLabelKeys and LabelSelector. MatchLabelKeys cannot be set when LabelSelector isn't set. Keys that don't exist in the incoming pod labels will be ignored. A null or empty list means only match against labelSelector.\n\nThis is a beta field and requires the MatchLabelKeysInPodTopologySpread feature gate to be enabled (enabled by default).", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"maxSkew", "topologyKey", "whenUnsatisfiable"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"}, - } -} - -func schema_k8sio_api_core_v1_TypedLocalObjectReference(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "TypedLocalObjectReference contains enough information to let you locate the typed referenced object inside the same namespace.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "apiGroup": { - SchemaProps: spec.SchemaProps{ - Description: "APIGroup is the group for the resource being referenced. If APIGroup is not specified, the specified Kind must be in the core API group. For any other third-party types, APIGroup is required.", - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is the type of resource being referenced", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name is the name of resource being referenced", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"kind", "name"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - } -} - -func schema_k8sio_api_core_v1_TypedObjectReference(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "apiGroup": { - SchemaProps: spec.SchemaProps{ - Description: "APIGroup is the group for the resource being referenced. If APIGroup is not specified, the specified Kind must be in the core API group. For any other third-party types, APIGroup is required.", - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is the type of resource being referenced", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name is the name of resource being referenced", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "namespace": { - SchemaProps: spec.SchemaProps{ - Description: "Namespace is the namespace of resource being referenced Note that when a namespace is specified, a gateway.networking.k8s.io/ReferenceGrant object is required in the referent namespace to allow that namespace's owner to accept the reference. See the ReferenceGrant documentation for details. (Alpha) This field requires the CrossNamespaceVolumeDataSource feature gate to be enabled.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"kind", "name"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_Volume(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Volume represents a named volume in a pod that may be accessed by any container in the pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "name of the volume. Must be a DNS_LABEL and unique within the pod. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "hostPath": { - SchemaProps: spec.SchemaProps{ - Description: "hostPath represents a pre-existing file or directory on the host machine that is directly exposed to the container. This is generally used for system agents or other privileged things that are allowed to see the host machine. Most containers will NOT need this. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath", - Ref: ref("k8s.io/api/core/v1.HostPathVolumeSource"), - }, - }, - "emptyDir": { - SchemaProps: spec.SchemaProps{ - Description: "emptyDir represents a temporary directory that shares a pod's lifetime. More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir", - Ref: ref("k8s.io/api/core/v1.EmptyDirVolumeSource"), - }, - }, - "gcePersistentDisk": { - SchemaProps: spec.SchemaProps{ - Description: "gcePersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", - Ref: ref("k8s.io/api/core/v1.GCEPersistentDiskVolumeSource"), - }, - }, - "awsElasticBlockStore": { - SchemaProps: spec.SchemaProps{ - Description: "awsElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore", - Ref: ref("k8s.io/api/core/v1.AWSElasticBlockStoreVolumeSource"), - }, - }, - "gitRepo": { - SchemaProps: spec.SchemaProps{ - Description: "gitRepo represents a git repository at a particular revision. DEPRECATED: GitRepo is deprecated. To provision a container with a git repo, mount an EmptyDir into an InitContainer that clones the repo using git, then mount the EmptyDir into the Pod's container.", - Ref: ref("k8s.io/api/core/v1.GitRepoVolumeSource"), - }, - }, - "secret": { - SchemaProps: spec.SchemaProps{ - Description: "secret represents a secret that should populate this volume. More info: https://kubernetes.io/docs/concepts/storage/volumes#secret", - Ref: ref("k8s.io/api/core/v1.SecretVolumeSource"), - }, - }, - "nfs": { - SchemaProps: spec.SchemaProps{ - Description: "nfs represents an NFS mount on the host that shares a pod's lifetime More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs", - Ref: ref("k8s.io/api/core/v1.NFSVolumeSource"), - }, - }, - "iscsi": { - SchemaProps: spec.SchemaProps{ - Description: "iscsi represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://examples.k8s.io/volumes/iscsi/README.md", - Ref: ref("k8s.io/api/core/v1.ISCSIVolumeSource"), - }, - }, - "glusterfs": { - SchemaProps: spec.SchemaProps{ - Description: "glusterfs represents a Glusterfs mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/glusterfs/README.md", - Ref: ref("k8s.io/api/core/v1.GlusterfsVolumeSource"), - }, - }, - "persistentVolumeClaim": { - SchemaProps: spec.SchemaProps{ - Description: "persistentVolumeClaimVolumeSource represents a reference to a PersistentVolumeClaim in the same namespace. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims", - Ref: ref("k8s.io/api/core/v1.PersistentVolumeClaimVolumeSource"), - }, - }, - "rbd": { - SchemaProps: spec.SchemaProps{ - Description: "rbd represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/rbd/README.md", - Ref: ref("k8s.io/api/core/v1.RBDVolumeSource"), - }, - }, - "flexVolume": { - SchemaProps: spec.SchemaProps{ - Description: "flexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin.", - Ref: ref("k8s.io/api/core/v1.FlexVolumeSource"), - }, - }, - "cinder": { - SchemaProps: spec.SchemaProps{ - Description: "cinder represents a cinder volume attached and mounted on kubelets host machine. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - Ref: ref("k8s.io/api/core/v1.CinderVolumeSource"), - }, - }, - "cephfs": { - SchemaProps: spec.SchemaProps{ - Description: "cephFS represents a Ceph FS mount on the host that shares a pod's lifetime", - Ref: ref("k8s.io/api/core/v1.CephFSVolumeSource"), - }, - }, - "flocker": { - SchemaProps: spec.SchemaProps{ - Description: "flocker represents a Flocker volume attached to a kubelet's host machine. This depends on the Flocker control service being running", - Ref: ref("k8s.io/api/core/v1.FlockerVolumeSource"), - }, - }, - "downwardAPI": { - SchemaProps: spec.SchemaProps{ - Description: "downwardAPI represents downward API about the pod that should populate this volume", - Ref: ref("k8s.io/api/core/v1.DownwardAPIVolumeSource"), - }, - }, - "fc": { - SchemaProps: spec.SchemaProps{ - Description: "fc represents a Fibre Channel resource that is attached to a kubelet's host machine and then exposed to the pod.", - Ref: ref("k8s.io/api/core/v1.FCVolumeSource"), - }, - }, - "azureFile": { - SchemaProps: spec.SchemaProps{ - Description: "azureFile represents an Azure File Service mount on the host and bind mount to the pod.", - Ref: ref("k8s.io/api/core/v1.AzureFileVolumeSource"), - }, - }, - "configMap": { - SchemaProps: spec.SchemaProps{ - Description: "configMap represents a configMap that should populate this volume", - Ref: ref("k8s.io/api/core/v1.ConfigMapVolumeSource"), - }, - }, - "vsphereVolume": { - SchemaProps: spec.SchemaProps{ - Description: "vsphereVolume represents a vSphere volume attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.VsphereVirtualDiskVolumeSource"), - }, - }, - "quobyte": { - SchemaProps: spec.SchemaProps{ - Description: "quobyte represents a Quobyte mount on the host that shares a pod's lifetime", - Ref: ref("k8s.io/api/core/v1.QuobyteVolumeSource"), - }, - }, - "azureDisk": { - SchemaProps: spec.SchemaProps{ - Description: "azureDisk represents an Azure Data Disk mount on the host and bind mount to the pod.", - Ref: ref("k8s.io/api/core/v1.AzureDiskVolumeSource"), - }, - }, - "photonPersistentDisk": { - SchemaProps: spec.SchemaProps{ - Description: "photonPersistentDisk represents a PhotonController persistent disk attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.PhotonPersistentDiskVolumeSource"), - }, - }, - "projected": { - SchemaProps: spec.SchemaProps{ - Description: "projected items for all in one resources secrets, configmaps, and downward API", - Ref: ref("k8s.io/api/core/v1.ProjectedVolumeSource"), - }, - }, - "portworxVolume": { - SchemaProps: spec.SchemaProps{ - Description: "portworxVolume represents a portworx volume attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.PortworxVolumeSource"), - }, - }, - "scaleIO": { - SchemaProps: spec.SchemaProps{ - Description: "scaleIO represents a ScaleIO persistent volume attached and mounted on Kubernetes nodes.", - Ref: ref("k8s.io/api/core/v1.ScaleIOVolumeSource"), - }, - }, - "storageos": { - SchemaProps: spec.SchemaProps{ - Description: "storageOS represents a StorageOS volume attached and mounted on Kubernetes nodes.", - Ref: ref("k8s.io/api/core/v1.StorageOSVolumeSource"), - }, - }, - "csi": { - SchemaProps: spec.SchemaProps{ - Description: "csi (Container Storage Interface) represents ephemeral storage that is handled by certain external CSI drivers (Beta feature).", - Ref: ref("k8s.io/api/core/v1.CSIVolumeSource"), - }, - }, - "ephemeral": { - SchemaProps: spec.SchemaProps{ - Description: "ephemeral represents a volume that is handled by a cluster storage driver. The volume's lifecycle is tied to the pod that defines it - it will be created before the pod starts, and deleted when the pod is removed.\n\nUse this if: a) the volume is only needed while the pod runs, b) features of normal volumes like restoring from snapshot or capacity\n tracking are needed,\nc) the storage driver is specified through a storage class, and d) the storage driver supports dynamic volume provisioning through\n a PersistentVolumeClaim (see EphemeralVolumeSource for more\n information on the connection between this volume type\n and PersistentVolumeClaim).\n\nUse PersistentVolumeClaim or one of the vendor-specific APIs for volumes that persist for longer than the lifecycle of an individual pod.\n\nUse CSI for light-weight local ephemeral volumes if the CSI driver is meant to be used that way - see the documentation of the driver for more information.\n\nA pod can use both types of ephemeral volumes and persistent volumes at the same time.", - Ref: ref("k8s.io/api/core/v1.EphemeralVolumeSource"), - }, - }, - }, - Required: []string{"name"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.AWSElasticBlockStoreVolumeSource", "k8s.io/api/core/v1.AzureDiskVolumeSource", "k8s.io/api/core/v1.AzureFileVolumeSource", "k8s.io/api/core/v1.CSIVolumeSource", "k8s.io/api/core/v1.CephFSVolumeSource", "k8s.io/api/core/v1.CinderVolumeSource", "k8s.io/api/core/v1.ConfigMapVolumeSource", "k8s.io/api/core/v1.DownwardAPIVolumeSource", "k8s.io/api/core/v1.EmptyDirVolumeSource", "k8s.io/api/core/v1.EphemeralVolumeSource", "k8s.io/api/core/v1.FCVolumeSource", "k8s.io/api/core/v1.FlexVolumeSource", "k8s.io/api/core/v1.FlockerVolumeSource", "k8s.io/api/core/v1.GCEPersistentDiskVolumeSource", "k8s.io/api/core/v1.GitRepoVolumeSource", "k8s.io/api/core/v1.GlusterfsVolumeSource", "k8s.io/api/core/v1.HostPathVolumeSource", "k8s.io/api/core/v1.ISCSIVolumeSource", "k8s.io/api/core/v1.NFSVolumeSource", "k8s.io/api/core/v1.PersistentVolumeClaimVolumeSource", "k8s.io/api/core/v1.PhotonPersistentDiskVolumeSource", "k8s.io/api/core/v1.PortworxVolumeSource", "k8s.io/api/core/v1.ProjectedVolumeSource", "k8s.io/api/core/v1.QuobyteVolumeSource", "k8s.io/api/core/v1.RBDVolumeSource", "k8s.io/api/core/v1.ScaleIOVolumeSource", "k8s.io/api/core/v1.SecretVolumeSource", "k8s.io/api/core/v1.StorageOSVolumeSource", "k8s.io/api/core/v1.VsphereVirtualDiskVolumeSource"}, - } -} - -func schema_k8sio_api_core_v1_VolumeDevice(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "volumeDevice describes a mapping of a raw block device within a container.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "name must match the name of a persistentVolumeClaim in the pod", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "devicePath": { - SchemaProps: spec.SchemaProps{ - Description: "devicePath is the path inside of the container that the device will be mapped to.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name", "devicePath"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_VolumeMount(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "VolumeMount describes a mounting of a Volume within a container.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "This must match the Name of a Volume.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "readOnly": { - SchemaProps: spec.SchemaProps{ - Description: "Mounted read-only if true, read-write otherwise (false or unspecified). Defaults to false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "mountPath": { - SchemaProps: spec.SchemaProps{ - Description: "Path within the container at which the volume should be mounted. Must not contain ':'.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "subPath": { - SchemaProps: spec.SchemaProps{ - Description: "Path within the volume from which the container's volume should be mounted. Defaults to \"\" (volume's root).", - Type: []string{"string"}, - Format: "", - }, - }, - "mountPropagation": { - SchemaProps: spec.SchemaProps{ - Description: "mountPropagation determines how mounts are propagated from the host to container and the other way around. When not set, MountPropagationNone is used. This field is beta in 1.10.\n\nPossible enum values:\n - `\"Bidirectional\"` means that the volume in a container will receive new mounts from the host or other containers, and its own mounts will be propagated from the container to the host or other containers. Note that this mode is recursively applied to all mounts in the volume (\"rshared\" in Linux terminology).\n - `\"HostToContainer\"` means that the volume in a container will receive new mounts from the host or other containers, but filesystems mounted inside the container won't be propagated to the host or other containers. Note that this mode is recursively applied to all mounts in the volume (\"rslave\" in Linux terminology).\n - `\"None\"` means that the volume in a container will not receive new mounts from the host or other containers, and filesystems mounted inside the container won't be propagated to the host or other containers. Note that this mode corresponds to \"private\" in Linux terminology.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Bidirectional", "HostToContainer", "None"}, - }, - }, - "subPathExpr": { - SchemaProps: spec.SchemaProps{ - Description: "Expanded path within the volume from which the container's volume should be mounted. Behaves similarly to SubPath but environment variable references $(VAR_NAME) are expanded using the container's environment. Defaults to \"\" (volume's root). SubPathExpr and SubPath are mutually exclusive.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name", "mountPath"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_VolumeNodeAffinity(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "VolumeNodeAffinity defines constraints that limit what nodes this volume can be accessed from.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "required": { - SchemaProps: spec.SchemaProps{ - Description: "required specifies hard node constraints that must be met.", - Ref: ref("k8s.io/api/core/v1.NodeSelector"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.NodeSelector"}, - } -} - -func schema_k8sio_api_core_v1_VolumeProjection(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Projection that may be projected along with other supported volume types", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "secret": { - SchemaProps: spec.SchemaProps{ - Description: "secret information about the secret data to project", - Ref: ref("k8s.io/api/core/v1.SecretProjection"), - }, - }, - "downwardAPI": { - SchemaProps: spec.SchemaProps{ - Description: "downwardAPI information about the downwardAPI data to project", - Ref: ref("k8s.io/api/core/v1.DownwardAPIProjection"), - }, - }, - "configMap": { - SchemaProps: spec.SchemaProps{ - Description: "configMap information about the configMap data to project", - Ref: ref("k8s.io/api/core/v1.ConfigMapProjection"), - }, - }, - "serviceAccountToken": { - SchemaProps: spec.SchemaProps{ - Description: "serviceAccountToken is information about the serviceAccountToken data to project", - Ref: ref("k8s.io/api/core/v1.ServiceAccountTokenProjection"), - }, - }, - "clusterTrustBundle": { - SchemaProps: spec.SchemaProps{ - Description: "ClusterTrustBundle allows a pod to access the `.spec.trustBundle` field of ClusterTrustBundle objects in an auto-updating file.\n\nAlpha, gated by the ClusterTrustBundleProjection feature gate.\n\nClusterTrustBundle objects can either be selected by name, or by the combination of signer name and a label selector.\n\nKubelet performs aggressive normalization of the PEM contents written into the pod filesystem. Esoteric PEM features such as inter-block comments and block headers are stripped. Certificates are deduplicated. The ordering of certificates within the file is arbitrary, and Kubelet may change the order over time.", - Ref: ref("k8s.io/api/core/v1.ClusterTrustBundleProjection"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ClusterTrustBundleProjection", "k8s.io/api/core/v1.ConfigMapProjection", "k8s.io/api/core/v1.DownwardAPIProjection", "k8s.io/api/core/v1.SecretProjection", "k8s.io/api/core/v1.ServiceAccountTokenProjection"}, - } -} - -func schema_k8sio_api_core_v1_VolumeResourceRequirements(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "VolumeResourceRequirements describes the storage resource requirements for a volume.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "limits": { - SchemaProps: spec.SchemaProps{ - Description: "Limits describes the maximum amount of compute resources allowed. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "requests": { - SchemaProps: spec.SchemaProps{ - Description: "Requests describes the minimum amount of compute resources required. If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value. Requests cannot exceed Limits. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_k8sio_api_core_v1_VolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents the source of a volume to mount. Only one of its members may be specified.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "hostPath": { - SchemaProps: spec.SchemaProps{ - Description: "hostPath represents a pre-existing file or directory on the host machine that is directly exposed to the container. This is generally used for system agents or other privileged things that are allowed to see the host machine. Most containers will NOT need this. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath", - Ref: ref("k8s.io/api/core/v1.HostPathVolumeSource"), - }, - }, - "emptyDir": { - SchemaProps: spec.SchemaProps{ - Description: "emptyDir represents a temporary directory that shares a pod's lifetime. More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir", - Ref: ref("k8s.io/api/core/v1.EmptyDirVolumeSource"), - }, - }, - "gcePersistentDisk": { - SchemaProps: spec.SchemaProps{ - Description: "gcePersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", - Ref: ref("k8s.io/api/core/v1.GCEPersistentDiskVolumeSource"), - }, - }, - "awsElasticBlockStore": { - SchemaProps: spec.SchemaProps{ - Description: "awsElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore", - Ref: ref("k8s.io/api/core/v1.AWSElasticBlockStoreVolumeSource"), - }, - }, - "gitRepo": { - SchemaProps: spec.SchemaProps{ - Description: "gitRepo represents a git repository at a particular revision. DEPRECATED: GitRepo is deprecated. To provision a container with a git repo, mount an EmptyDir into an InitContainer that clones the repo using git, then mount the EmptyDir into the Pod's container.", - Ref: ref("k8s.io/api/core/v1.GitRepoVolumeSource"), - }, - }, - "secret": { - SchemaProps: spec.SchemaProps{ - Description: "secret represents a secret that should populate this volume. More info: https://kubernetes.io/docs/concepts/storage/volumes#secret", - Ref: ref("k8s.io/api/core/v1.SecretVolumeSource"), - }, - }, - "nfs": { - SchemaProps: spec.SchemaProps{ - Description: "nfs represents an NFS mount on the host that shares a pod's lifetime More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs", - Ref: ref("k8s.io/api/core/v1.NFSVolumeSource"), - }, - }, - "iscsi": { - SchemaProps: spec.SchemaProps{ - Description: "iscsi represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://examples.k8s.io/volumes/iscsi/README.md", - Ref: ref("k8s.io/api/core/v1.ISCSIVolumeSource"), - }, - }, - "glusterfs": { - SchemaProps: spec.SchemaProps{ - Description: "glusterfs represents a Glusterfs mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/glusterfs/README.md", - Ref: ref("k8s.io/api/core/v1.GlusterfsVolumeSource"), - }, - }, - "persistentVolumeClaim": { - SchemaProps: spec.SchemaProps{ - Description: "persistentVolumeClaimVolumeSource represents a reference to a PersistentVolumeClaim in the same namespace. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims", - Ref: ref("k8s.io/api/core/v1.PersistentVolumeClaimVolumeSource"), - }, - }, - "rbd": { - SchemaProps: spec.SchemaProps{ - Description: "rbd represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/rbd/README.md", - Ref: ref("k8s.io/api/core/v1.RBDVolumeSource"), - }, - }, - "flexVolume": { - SchemaProps: spec.SchemaProps{ - Description: "flexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin.", - Ref: ref("k8s.io/api/core/v1.FlexVolumeSource"), - }, - }, - "cinder": { - SchemaProps: spec.SchemaProps{ - Description: "cinder represents a cinder volume attached and mounted on kubelets host machine. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - Ref: ref("k8s.io/api/core/v1.CinderVolumeSource"), - }, - }, - "cephfs": { - SchemaProps: spec.SchemaProps{ - Description: "cephFS represents a Ceph FS mount on the host that shares a pod's lifetime", - Ref: ref("k8s.io/api/core/v1.CephFSVolumeSource"), - }, - }, - "flocker": { - SchemaProps: spec.SchemaProps{ - Description: "flocker represents a Flocker volume attached to a kubelet's host machine. This depends on the Flocker control service being running", - Ref: ref("k8s.io/api/core/v1.FlockerVolumeSource"), - }, - }, - "downwardAPI": { - SchemaProps: spec.SchemaProps{ - Description: "downwardAPI represents downward API about the pod that should populate this volume", - Ref: ref("k8s.io/api/core/v1.DownwardAPIVolumeSource"), - }, - }, - "fc": { - SchemaProps: spec.SchemaProps{ - Description: "fc represents a Fibre Channel resource that is attached to a kubelet's host machine and then exposed to the pod.", - Ref: ref("k8s.io/api/core/v1.FCVolumeSource"), - }, - }, - "azureFile": { - SchemaProps: spec.SchemaProps{ - Description: "azureFile represents an Azure File Service mount on the host and bind mount to the pod.", - Ref: ref("k8s.io/api/core/v1.AzureFileVolumeSource"), - }, - }, - "configMap": { - SchemaProps: spec.SchemaProps{ - Description: "configMap represents a configMap that should populate this volume", - Ref: ref("k8s.io/api/core/v1.ConfigMapVolumeSource"), - }, - }, - "vsphereVolume": { - SchemaProps: spec.SchemaProps{ - Description: "vsphereVolume represents a vSphere volume attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.VsphereVirtualDiskVolumeSource"), - }, - }, - "quobyte": { - SchemaProps: spec.SchemaProps{ - Description: "quobyte represents a Quobyte mount on the host that shares a pod's lifetime", - Ref: ref("k8s.io/api/core/v1.QuobyteVolumeSource"), - }, - }, - "azureDisk": { - SchemaProps: spec.SchemaProps{ - Description: "azureDisk represents an Azure Data Disk mount on the host and bind mount to the pod.", - Ref: ref("k8s.io/api/core/v1.AzureDiskVolumeSource"), - }, - }, - "photonPersistentDisk": { - SchemaProps: spec.SchemaProps{ - Description: "photonPersistentDisk represents a PhotonController persistent disk attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.PhotonPersistentDiskVolumeSource"), - }, - }, - "projected": { - SchemaProps: spec.SchemaProps{ - Description: "projected items for all in one resources secrets, configmaps, and downward API", - Ref: ref("k8s.io/api/core/v1.ProjectedVolumeSource"), - }, - }, - "portworxVolume": { - SchemaProps: spec.SchemaProps{ - Description: "portworxVolume represents a portworx volume attached and mounted on kubelets host machine", - Ref: ref("k8s.io/api/core/v1.PortworxVolumeSource"), - }, - }, - "scaleIO": { - SchemaProps: spec.SchemaProps{ - Description: "scaleIO represents a ScaleIO persistent volume attached and mounted on Kubernetes nodes.", - Ref: ref("k8s.io/api/core/v1.ScaleIOVolumeSource"), - }, - }, - "storageos": { - SchemaProps: spec.SchemaProps{ - Description: "storageOS represents a StorageOS volume attached and mounted on Kubernetes nodes.", - Ref: ref("k8s.io/api/core/v1.StorageOSVolumeSource"), - }, - }, - "csi": { - SchemaProps: spec.SchemaProps{ - Description: "csi (Container Storage Interface) represents ephemeral storage that is handled by certain external CSI drivers (Beta feature).", - Ref: ref("k8s.io/api/core/v1.CSIVolumeSource"), - }, - }, - "ephemeral": { - SchemaProps: spec.SchemaProps{ - Description: "ephemeral represents a volume that is handled by a cluster storage driver. The volume's lifecycle is tied to the pod that defines it - it will be created before the pod starts, and deleted when the pod is removed.\n\nUse this if: a) the volume is only needed while the pod runs, b) features of normal volumes like restoring from snapshot or capacity\n tracking are needed,\nc) the storage driver is specified through a storage class, and d) the storage driver supports dynamic volume provisioning through\n a PersistentVolumeClaim (see EphemeralVolumeSource for more\n information on the connection between this volume type\n and PersistentVolumeClaim).\n\nUse PersistentVolumeClaim or one of the vendor-specific APIs for volumes that persist for longer than the lifecycle of an individual pod.\n\nUse CSI for light-weight local ephemeral volumes if the CSI driver is meant to be used that way - see the documentation of the driver for more information.\n\nA pod can use both types of ephemeral volumes and persistent volumes at the same time.", - Ref: ref("k8s.io/api/core/v1.EphemeralVolumeSource"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.AWSElasticBlockStoreVolumeSource", "k8s.io/api/core/v1.AzureDiskVolumeSource", "k8s.io/api/core/v1.AzureFileVolumeSource", "k8s.io/api/core/v1.CSIVolumeSource", "k8s.io/api/core/v1.CephFSVolumeSource", "k8s.io/api/core/v1.CinderVolumeSource", "k8s.io/api/core/v1.ConfigMapVolumeSource", "k8s.io/api/core/v1.DownwardAPIVolumeSource", "k8s.io/api/core/v1.EmptyDirVolumeSource", "k8s.io/api/core/v1.EphemeralVolumeSource", "k8s.io/api/core/v1.FCVolumeSource", "k8s.io/api/core/v1.FlexVolumeSource", "k8s.io/api/core/v1.FlockerVolumeSource", "k8s.io/api/core/v1.GCEPersistentDiskVolumeSource", "k8s.io/api/core/v1.GitRepoVolumeSource", "k8s.io/api/core/v1.GlusterfsVolumeSource", "k8s.io/api/core/v1.HostPathVolumeSource", "k8s.io/api/core/v1.ISCSIVolumeSource", "k8s.io/api/core/v1.NFSVolumeSource", "k8s.io/api/core/v1.PersistentVolumeClaimVolumeSource", "k8s.io/api/core/v1.PhotonPersistentDiskVolumeSource", "k8s.io/api/core/v1.PortworxVolumeSource", "k8s.io/api/core/v1.ProjectedVolumeSource", "k8s.io/api/core/v1.QuobyteVolumeSource", "k8s.io/api/core/v1.RBDVolumeSource", "k8s.io/api/core/v1.ScaleIOVolumeSource", "k8s.io/api/core/v1.SecretVolumeSource", "k8s.io/api/core/v1.StorageOSVolumeSource", "k8s.io/api/core/v1.VsphereVirtualDiskVolumeSource"}, - } -} - -func schema_k8sio_api_core_v1_VsphereVirtualDiskVolumeSource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Represents a vSphere volume resource.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "volumePath": { - SchemaProps: spec.SchemaProps{ - Description: "volumePath is the path that identifies vSphere volume vmdk", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "fsType": { - SchemaProps: spec.SchemaProps{ - Description: "fsType is filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - Type: []string{"string"}, - Format: "", - }, - }, - "storagePolicyName": { - SchemaProps: spec.SchemaProps{ - Description: "storagePolicyName is the storage Policy Based Management (SPBM) profile name.", - Type: []string{"string"}, - Format: "", - }, - }, - "storagePolicyID": { - SchemaProps: spec.SchemaProps{ - Description: "storagePolicyID is the storage Policy Based Management (SPBM) profile ID associated with the StoragePolicyName.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"volumePath"}, - }, - }, - } -} - -func schema_k8sio_api_core_v1_WeightedPodAffinityTerm(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "The weights of all of the matched WeightedPodAffinityTerm fields are added per-node to find the most preferred node(s)", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "weight": { - SchemaProps: spec.SchemaProps{ - Description: "weight associated with matching the corresponding podAffinityTerm, in the range 1-100.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - "podAffinityTerm": { - SchemaProps: spec.SchemaProps{ - Description: "Required. A pod affinity term, associated with the corresponding weight.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodAffinityTerm"), - }, - }, - }, - Required: []string{"weight", "podAffinityTerm"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodAffinityTerm"}, - } -} - -func schema_k8sio_api_core_v1_WindowsSecurityContextOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "WindowsSecurityContextOptions contain Windows-specific options and credentials.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "gmsaCredentialSpecName": { - SchemaProps: spec.SchemaProps{ - Description: "GMSACredentialSpecName is the name of the GMSA credential spec to use.", - Type: []string{"string"}, - Format: "", - }, - }, - "gmsaCredentialSpec": { - SchemaProps: spec.SchemaProps{ - Description: "GMSACredentialSpec is where the GMSA admission webhook (https://github.com/kubernetes-sigs/windows-gmsa) inlines the contents of the GMSA credential spec named by the GMSACredentialSpecName field.", - Type: []string{"string"}, - Format: "", - }, - }, - "runAsUserName": { - SchemaProps: spec.SchemaProps{ - Description: "The UserName in Windows to run the entrypoint of the container process. Defaults to the user specified in image metadata if unspecified. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.", - Type: []string{"string"}, - Format: "", - }, - }, - "hostProcess": { - SchemaProps: spec.SchemaProps{ - Description: "HostProcess determines if a container should be run as a 'Host Process' container. All of a Pod's containers must have the same effective HostProcess value (it is not allowed to have a mix of HostProcess containers and non-HostProcess containers). In addition, if HostProcess is true then HostNetwork must also be set to true.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_apimachinery_pkg_api_resource_Quantity(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.EmbedOpenAPIDefinitionIntoV2Extension(common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Quantity is a fixed-point representation of a number. It provides convenient marshaling/unmarshaling in JSON and YAML, in addition to String() and AsInt64() accessors.\n\nThe serialization format is:\n\n``` ::= \n\n\t(Note that may be empty, from the \"\" case in .)\n\n ::= 0 | 1 | ... | 9 ::= | ::= | . | . | . ::= \"+\" | \"-\" ::= | ::= | | ::= Ki | Mi | Gi | Ti | Pi | Ei\n\n\t(International System of units; See: http://physics.nist.gov/cuu/Units/binary.html)\n\n ::= m | \"\" | k | M | G | T | P | E\n\n\t(Note that 1024 = 1Ki but 1000 = 1k; I didn't choose the capitalization.)\n\n ::= \"e\" | \"E\" ```\n\nNo matter which of the three exponent forms is used, no quantity may represent a number greater than 2^63-1 in magnitude, nor may it have more than 3 decimal places. Numbers larger or more precise will be capped or rounded up. (E.g.: 0.1m will rounded up to 1m.) This may be extended in the future if we require larger or smaller quantities.\n\nWhen a Quantity is parsed from a string, it will remember the type of suffix it had, and will use the same type again when it is serialized.\n\nBefore serializing, Quantity will be put in \"canonical form\". This means that Exponent/suffix will be adjusted up or down (with a corresponding increase or decrease in Mantissa) such that:\n\n- No precision is lost - No fractional digits will be emitted - The exponent (or suffix) is as large as possible.\n\nThe sign will be omitted unless the number is negative.\n\nExamples:\n\n- 1.5 will be serialized as \"1500m\" - 1.5Gi will be serialized as \"1536Mi\"\n\nNote that the quantity will NEVER be internally represented by a floating point number. That is the whole point of this exercise.\n\nNon-canonical values will still parse as long as they are well formed, but will be re-emitted in their canonical form. (So always use canonical form, or don't diff.)\n\nThis format is intended to make it difficult to use these numbers without writing some sort of special handling code in the hopes that that will cause implementors to also use a fixed point implementation.", - OneOf: common.GenerateOpenAPIV3OneOfSchema(resource.Quantity{}.OpenAPIV3OneOfTypes()), - Format: resource.Quantity{}.OpenAPISchemaFormat(), - }, - }, - }, common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Quantity is a fixed-point representation of a number. It provides convenient marshaling/unmarshaling in JSON and YAML, in addition to String() and AsInt64() accessors.\n\nThe serialization format is:\n\n``` ::= \n\n\t(Note that may be empty, from the \"\" case in .)\n\n ::= 0 | 1 | ... | 9 ::= | ::= | . | . | . ::= \"+\" | \"-\" ::= | ::= | | ::= Ki | Mi | Gi | Ti | Pi | Ei\n\n\t(International System of units; See: http://physics.nist.gov/cuu/Units/binary.html)\n\n ::= m | \"\" | k | M | G | T | P | E\n\n\t(Note that 1024 = 1Ki but 1000 = 1k; I didn't choose the capitalization.)\n\n ::= \"e\" | \"E\" ```\n\nNo matter which of the three exponent forms is used, no quantity may represent a number greater than 2^63-1 in magnitude, nor may it have more than 3 decimal places. Numbers larger or more precise will be capped or rounded up. (E.g.: 0.1m will rounded up to 1m.) This may be extended in the future if we require larger or smaller quantities.\n\nWhen a Quantity is parsed from a string, it will remember the type of suffix it had, and will use the same type again when it is serialized.\n\nBefore serializing, Quantity will be put in \"canonical form\". This means that Exponent/suffix will be adjusted up or down (with a corresponding increase or decrease in Mantissa) such that:\n\n- No precision is lost - No fractional digits will be emitted - The exponent (or suffix) is as large as possible.\n\nThe sign will be omitted unless the number is negative.\n\nExamples:\n\n- 1.5 will be serialized as \"1500m\" - 1.5Gi will be serialized as \"1536Mi\"\n\nNote that the quantity will NEVER be internally represented by a floating point number. That is the whole point of this exercise.\n\nNon-canonical values will still parse as long as they are well formed, but will be re-emitted in their canonical form. (So always use canonical form, or don't diff.)\n\nThis format is intended to make it difficult to use these numbers without writing some sort of special handling code in the hopes that that will cause implementors to also use a fixed point implementation.", - Type: resource.Quantity{}.OpenAPISchemaType(), - Format: resource.Quantity{}.OpenAPISchemaFormat(), - }, - }, - }) -} - -func schema_apimachinery_pkg_api_resource_int64Amount(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "int64Amount represents a fixed precision numerator and arbitrary scale exponent. It is faster than operations on inf.Dec for values that can be represented as int64.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "value": { - SchemaProps: spec.SchemaProps{ - Default: 0, - Type: []string{"integer"}, - Format: "int64", - }, - }, - "scale": { - SchemaProps: spec.SchemaProps{ - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - Required: []string{"value", "scale"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_APIGroup(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "APIGroup contains the name, the supported versions, and the preferred version of a group.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Description: "name is the name of the group.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "versions": { - SchemaProps: spec.SchemaProps{ - Description: "versions are the versions supported in this group.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.GroupVersionForDiscovery"), - }, - }, - }, - }, - }, - "preferredVersion": { - SchemaProps: spec.SchemaProps{ - Description: "preferredVersion is the version preferred by the API server, which probably is the storage version.", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.GroupVersionForDiscovery"), - }, - }, - "serverAddressByClientCIDRs": { - SchemaProps: spec.SchemaProps{ - Description: "a map of client CIDR to server address that is serving this group. This is to help clients reach servers in the most network-efficient way possible. Clients can use the appropriate server address as per the CIDR that they match. In case of multiple matches, clients should use the longest matching CIDR. The server returns only those CIDRs that it thinks that the client can match. For example: the master will return an internal IP CIDR only, if the client reaches the server using an internal IP. Server looks at X-Forwarded-For header or X-Real-Ip header or request.RemoteAddr (in that order) to get the client IP.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ServerAddressByClientCIDR"), - }, - }, - }, - }, - }, - }, - Required: []string{"name", "versions"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.GroupVersionForDiscovery", "k8s.io/apimachinery/pkg/apis/meta/v1.ServerAddressByClientCIDR"}, - } -} - -func schema_pkg_apis_meta_v1_APIGroupList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "APIGroupList is a list of APIGroup, to allow clients to discover the API at /apis.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "groups": { - SchemaProps: spec.SchemaProps{ - Description: "groups is a list of APIGroup.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.APIGroup"), - }, - }, - }, - }, - }, - }, - Required: []string{"groups"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.APIGroup"}, - } -} - -func schema_pkg_apis_meta_v1_APIResource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "APIResource specifies the name of a resource and whether it is namespaced.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "name is the plural name of the resource.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "singularName": { - SchemaProps: spec.SchemaProps{ - Description: "singularName is the singular name of the resource. This allows clients to handle plural and singular opaquely. The singularName is more correct for reporting status on a single item and both singular and plural are allowed from the kubectl CLI interface.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "namespaced": { - SchemaProps: spec.SchemaProps{ - Description: "namespaced indicates if a resource is namespaced or not.", - Default: false, - Type: []string{"boolean"}, - Format: "", - }, - }, - "group": { - SchemaProps: spec.SchemaProps{ - Description: "group is the preferred group of the resource. Empty implies the group of the containing resource list. For subresources, this may have a different value, for example: Scale\".", - Type: []string{"string"}, - Format: "", - }, - }, - "version": { - SchemaProps: spec.SchemaProps{ - Description: "version is the preferred version of the resource. Empty implies the version of the containing resource list For subresources, this may have a different value, for example: v1 (while inside a v1beta1 version of the core resource's group)\".", - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "kind is the kind for the resource (e.g. 'Foo' is the kind for a resource 'foo')", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "verbs": { - SchemaProps: spec.SchemaProps{ - Description: "verbs is a list of supported kube verbs (this includes get, list, watch, create, update, patch, delete, deletecollection, and proxy)", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "shortNames": { - SchemaProps: spec.SchemaProps{ - Description: "shortNames is a list of suggested short names of the resource.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "categories": { - SchemaProps: spec.SchemaProps{ - Description: "categories is a list of the grouped resources this resource belongs to (e.g. 'all')", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "storageVersionHash": { - SchemaProps: spec.SchemaProps{ - Description: "The hash value of the storage version, the version this resource is converted to when written to the data store. Value must be treated as opaque by clients. Only equality comparison on the value is valid. This is an alpha feature and may change or be removed in the future. The field is populated by the apiserver only if the StorageVersionHash feature gate is enabled. This field will remain optional even if it graduates.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name", "singularName", "namespaced", "kind", "verbs"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_APIResourceList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "APIResourceList is a list of APIResource, it is used to expose the name of the resources supported in a specific group and version, and if the resource is namespaced.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "groupVersion": { - SchemaProps: spec.SchemaProps{ - Description: "groupVersion is the group and version this APIResourceList is for.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "resources": { - SchemaProps: spec.SchemaProps{ - Description: "resources contains the name of the resources and if they are namespaced.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.APIResource"), - }, - }, - }, - }, - }, - }, - Required: []string{"groupVersion", "resources"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.APIResource"}, - } -} - -func schema_pkg_apis_meta_v1_APIVersions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "APIVersions lists the versions that are available, to allow clients to discover the API at /api, which is the root path of the legacy v1 API.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "versions": { - SchemaProps: spec.SchemaProps{ - Description: "versions are the api versions that are available.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "serverAddressByClientCIDRs": { - SchemaProps: spec.SchemaProps{ - Description: "a map of client CIDR to server address that is serving this group. This is to help clients reach servers in the most network-efficient way possible. Clients can use the appropriate server address as per the CIDR that they match. In case of multiple matches, clients should use the longest matching CIDR. The server returns only those CIDRs that it thinks that the client can match. For example: the master will return an internal IP CIDR only, if the client reaches the server using an internal IP. Server looks at X-Forwarded-For header or X-Real-Ip header or request.RemoteAddr (in that order) to get the client IP.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ServerAddressByClientCIDR"), - }, - }, - }, - }, - }, - }, - Required: []string{"versions", "serverAddressByClientCIDRs"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ServerAddressByClientCIDR"}, - } -} - -func schema_pkg_apis_meta_v1_ApplyOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ApplyOptions may be provided when applying an API object. FieldManager is required for apply requests. ApplyOptions is equivalent to PatchOptions. It is provided as a convenience with documentation that speaks specifically to how the options fields relate to apply.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "dryRun": { - SchemaProps: spec.SchemaProps{ - Description: "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "force": { - SchemaProps: spec.SchemaProps{ - Description: "Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people.", - Default: false, - Type: []string{"boolean"}, - Format: "", - }, - }, - "fieldManager": { - SchemaProps: spec.SchemaProps{ - Description: "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"force", "fieldManager"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_Condition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Condition contains details for one aspect of the current state of this API Resource.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "type of condition in CamelCase or in foo.example.com/CamelCase.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "status of the condition, one of True, False, Unknown.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "observedGeneration": { - SchemaProps: spec.SchemaProps{ - Description: "observedGeneration represents the .metadata.generation that the condition was set based upon. For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date with respect to the current state of the instance.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "lastTransitionTime": { - SchemaProps: spec.SchemaProps{ - Description: "lastTransitionTime is the last time the condition transitioned from one status to another. This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "reason contains a programmatic identifier indicating the reason for the condition's last transition. Producers of specific condition types may define expected values and meanings for this field, and whether the values are considered a guaranteed API. The value should be a CamelCase string. This field may not be empty.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "message is a human readable message indicating details about the transition. This may be an empty string.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status", "lastTransitionTime", "reason", "message"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_pkg_apis_meta_v1_CreateOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "CreateOptions may be provided when creating an API object.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "dryRun": { - SchemaProps: spec.SchemaProps{ - Description: "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "fieldManager": { - SchemaProps: spec.SchemaProps{ - Description: "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.", - Type: []string{"string"}, - Format: "", - }, - }, - "fieldValidation": { - SchemaProps: spec.SchemaProps{ - Description: "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_DeleteOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "DeleteOptions may be provided when deleting an API object.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "gracePeriodSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "preconditions": { - SchemaProps: spec.SchemaProps{ - Description: "Must be fulfilled before a deletion is carried out. If not possible, a 409 Conflict status will be returned.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Preconditions"), - }, - }, - "orphanDependents": { - SchemaProps: spec.SchemaProps{ - Description: "Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "propagationPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.", - Type: []string{"string"}, - Format: "", - }, - }, - "dryRun": { - SchemaProps: spec.SchemaProps{ - Description: "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Preconditions"}, - } -} - -func schema_pkg_apis_meta_v1_Duration(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Duration is a wrapper around time.Duration which supports correct marshaling to YAML and JSON. In particular, it marshals into strings, which can be used as map keys in json.", - Type: v1.Duration{}.OpenAPISchemaType(), - Format: v1.Duration{}.OpenAPISchemaFormat(), - }, - }, - } -} - -func schema_pkg_apis_meta_v1_FieldsV1(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "FieldsV1 stores a set of fields in a data structure like a Trie, in JSON format.\n\nEach key is either a '.' representing the field itself, and will always map to an empty set, or a string representing a sub-field or item. The string will follow one of these four formats: 'f:', where is the name of a field in a struct, or key in a map 'v:', where is the exact json formatted value of a list item 'i:', where is position of a item in a list 'k:', where is a map of a list item's key fields to their unique values If a key maps to an empty Fields value, the field that key represents is part of the set.\n\nThe exact format is defined in sigs.k8s.io/structured-merge-diff", - Type: []string{"object"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_GetOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "GetOptions is the standard query options to the standard REST get call.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "resourceVersion": { - SchemaProps: spec.SchemaProps{ - Description: "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 details.\n\nDefaults to unset", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_GroupKind(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "GroupKind specifies a Group and a Kind, but does not force a version. This is useful for identifying concepts during lookup stages without having partially valid types", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "group": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"group", "kind"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_GroupResource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "GroupResource specifies a Group and a Resource, but does not force a version. This is useful for identifying concepts during lookup stages without having partially valid types", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "group": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "resource": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"group", "resource"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_GroupVersion(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "GroupVersion contains the \"group\" and the \"version\", which uniquely identifies the API.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "group": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "version": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"group", "version"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_GroupVersionForDiscovery(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "GroupVersion contains the \"group/version\" and \"version\" string of a version. It is made a struct to keep extensibility.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "groupVersion": { - SchemaProps: spec.SchemaProps{ - Description: "groupVersion specifies the API group and version in the form \"group/version\"", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "version": { - SchemaProps: spec.SchemaProps{ - Description: "version specifies the version in the form of \"version\". This is to save the clients the trouble of splitting the GroupVersion.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"groupVersion", "version"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_GroupVersionKind(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "GroupVersionKind unambiguously identifies a kind. It doesn't anonymously include GroupVersion to avoid automatic coercion. It doesn't use a GroupVersion to avoid custom marshalling", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "group": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "version": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"group", "version", "kind"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_GroupVersionResource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "GroupVersionResource unambiguously identifies a resource. It doesn't anonymously include GroupVersion to avoid automatic coercion. It doesn't use a GroupVersion to avoid custom marshalling", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "group": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "version": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "resource": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"group", "version", "resource"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_InternalEvent(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "InternalEvent makes watch.Event versioned", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "Type": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "Object": { - SchemaProps: spec.SchemaProps{ - Description: "Object is:\n * If Type is Added or Modified: the new state of the object.\n * If Type is Deleted: the state of the object immediately before deletion.\n * If Type is Bookmark: the object (instance of a type being watched) where\n only ResourceVersion field is set. On successful restart of watch from a\n bookmark resourceVersion, client is guaranteed to not get repeat event\n nor miss any events.\n * If Type is Error: *api.Status is recommended; other types may make sense\n depending on context.", - Ref: ref("k8s.io/apimachinery/pkg/runtime.Object"), - }, - }, - }, - Required: []string{"Type", "Object"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/runtime.Object"}, - } -} - -func schema_pkg_apis_meta_v1_LabelSelector(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A label selector is a label query over a set of resources. The result of matchLabels and matchExpressions are ANDed. An empty label selector matches all objects. A null label selector matches no objects.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "matchLabels": { - SchemaProps: spec.SchemaProps{ - Description: "matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "matchExpressions": { - SchemaProps: spec.SchemaProps{ - Description: "matchExpressions is a list of label selector requirements. The requirements are ANDed.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelectorRequirement"), - }, - }, - }, - }, - }, - }, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelectorRequirement"}, - } -} - -func schema_pkg_apis_meta_v1_LabelSelectorRequirement(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "key": { - SchemaProps: spec.SchemaProps{ - Description: "key is the label key that the selector applies to.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "operator": { - SchemaProps: spec.SchemaProps{ - Description: "operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "values": { - SchemaProps: spec.SchemaProps{ - Description: "values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"key", "operator"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_List(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "List holds a list of objects, which may not be known by the server.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "List of objects", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/runtime.RawExtension"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "k8s.io/apimachinery/pkg/runtime.RawExtension"}, - } -} - -func schema_pkg_apis_meta_v1_ListMeta(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "selfLink": { - SchemaProps: spec.SchemaProps{ - Description: "Deprecated: selfLink is a legacy read-only field that is no longer populated by the system.", - Type: []string{"string"}, - Format: "", - }, - }, - "resourceVersion": { - SchemaProps: spec.SchemaProps{ - Description: "String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency", - Type: []string{"string"}, - Format: "", - }, - }, - "continue": { - SchemaProps: spec.SchemaProps{ - Description: "continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.", - Type: []string{"string"}, - Format: "", - }, - }, - "remainingItemCount": { - SchemaProps: spec.SchemaProps{ - Description: "remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_ListOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ListOptions is the query options to a standard REST list call.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "labelSelector": { - SchemaProps: spec.SchemaProps{ - Description: "A selector to restrict the list of returned objects by their labels. Defaults to everything.", - Type: []string{"string"}, - Format: "", - }, - }, - "fieldSelector": { - SchemaProps: spec.SchemaProps{ - Description: "A selector to restrict the list of returned objects by their fields. Defaults to everything.", - Type: []string{"string"}, - Format: "", - }, - }, - "watch": { - SchemaProps: spec.SchemaProps{ - Description: "Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "allowWatchBookmarks": { - SchemaProps: spec.SchemaProps{ - Description: "allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not 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.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "resourceVersion": { - SchemaProps: spec.SchemaProps{ - Description: "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 details.\n\nDefaults to unset", - Type: []string{"string"}, - Format: "", - }, - }, - "resourceVersionMatch": { - SchemaProps: spec.SchemaProps{ - Description: "resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset", - Type: []string{"string"}, - Format: "", - }, - }, - "timeoutSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "limit": { - SchemaProps: spec.SchemaProps{ - Description: "limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.\n\nThe server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "continue": { - SchemaProps: spec.SchemaProps{ - Description: "The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\".\n\nThis field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.", - Type: []string{"string"}, - Format: "", - }, - }, - "sendInitialEvents": { - SchemaProps: spec.SchemaProps{ - Description: "`sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched.\n\nWhen `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan\n is interpreted as \"data at least as new as the provided `resourceVersion`\"\n and the bookmark event is send when the state is synced\n to a `resourceVersion` at least as fresh as the one provided by the ListOptions.\n If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the\n bookmark event is send when the state is synced at least to the moment\n when request started being processed.\n- `resourceVersionMatch` set to any other value or unset\n Invalid error is returned.\n\nDefaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_ManagedFieldsEntry(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ManagedFieldsEntry is a workflow-id, a FieldSet and the group version of the resource that the fieldset applies to.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "manager": { - SchemaProps: spec.SchemaProps{ - Description: "Manager is an identifier of the workflow managing these fields.", - Type: []string{"string"}, - Format: "", - }, - }, - "operation": { - SchemaProps: spec.SchemaProps{ - Description: "Operation is the type of operation which lead to this ManagedFieldsEntry being created. The only valid values for this field are 'Apply' and 'Update'.", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the version of this resource that this field set applies to. The format is \"group/version\" just like the top-level APIVersion field. It is necessary to track the version of a field set because it cannot be automatically converted.", - Type: []string{"string"}, - Format: "", - }, - }, - "time": { - SchemaProps: spec.SchemaProps{ - Description: "Time is the timestamp of when the ManagedFields entry was added. The timestamp will also be updated if a field is added, the manager changes any of the owned fields value or removes a field. The timestamp does not update when a field is removed from the entry because another manager took it over.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "fieldsType": { - SchemaProps: spec.SchemaProps{ - Description: "FieldsType is the discriminator for the different fields format and version. There is currently only one possible value: \"FieldsV1\"", - Type: []string{"string"}, - Format: "", - }, - }, - "fieldsV1": { - SchemaProps: spec.SchemaProps{ - Description: "FieldsV1 holds the first JSON version format as described in the \"FieldsV1\" type.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.FieldsV1"), - }, - }, - "subresource": { - SchemaProps: spec.SchemaProps{ - Description: "Subresource is the name of the subresource used to update that object, or empty string if the object was updated through the main resource. The value of this field is used to distinguish between managers, even if they share the same name. For example, a status update will be distinct from a regular update using the same manager name. Note that the APIVersion field is not related to the Subresource field and it always corresponds to the version of the main resource.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.FieldsV1", "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_pkg_apis_meta_v1_MicroTime(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "MicroTime is version of Time with microsecond level precision.", - Type: v1.MicroTime{}.OpenAPISchemaType(), - Format: v1.MicroTime{}.OpenAPISchemaFormat(), - }, - }, - } -} - -func schema_pkg_apis_meta_v1_ObjectMeta(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ObjectMeta is metadata that all persisted resources must have, which includes all objects users must create.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names", - Type: []string{"string"}, - Format: "", - }, - }, - "generateName": { - SchemaProps: spec.SchemaProps{ - Description: "GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server.\n\nIf this field is specified and the generated name exists, the server will return a 409.\n\nApplied only if Name is not specified. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency", - Type: []string{"string"}, - Format: "", - }, - }, - "namespace": { - SchemaProps: spec.SchemaProps{ - Description: "Namespace defines the space within which each name must be unique. An empty namespace is equivalent to the \"default\" namespace, but \"default\" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty.\n\nMust be a DNS_LABEL. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces", - Type: []string{"string"}, - Format: "", - }, - }, - "selfLink": { - SchemaProps: spec.SchemaProps{ - Description: "Deprecated: selfLink is a legacy read-only field that is no longer populated by the system.", - Type: []string{"string"}, - Format: "", - }, - }, - "uid": { - SchemaProps: spec.SchemaProps{ - Description: "UID is the unique in time and space value for this object. It is typically generated by the server on successful creation of a resource and is not allowed to change on PUT operations.\n\nPopulated by the system. Read-only. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids", - Type: []string{"string"}, - Format: "", - }, - }, - "resourceVersion": { - SchemaProps: spec.SchemaProps{ - Description: "An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. Clients must treat these values as opaque and passed unmodified back to the server. They may only be valid for a particular resource or set of resources.\n\nPopulated by the system. Read-only. Value must be treated as opaque by clients and . More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency", - Type: []string{"string"}, - Format: "", - }, - }, - "generation": { - SchemaProps: spec.SchemaProps{ - Description: "A sequence number representing a specific generation of the desired state. Populated by the system. Read-only.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "creationTimestamp": { - SchemaProps: spec.SchemaProps{ - Description: "CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC.\n\nPopulated by the system. Read-only. Null for lists. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "deletionTimestamp": { - SchemaProps: spec.SchemaProps{ - Description: "DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This field is set by the server when a graceful deletion is requested by the user, and is not directly settable by a client. The resource is expected to be deleted (no longer visible from resource lists, and not reachable by name) after the time in this field, once the finalizers list is empty. As long as the finalizers list contains items, deletion is blocked. Once the deletionTimestamp is set, this value may not be unset or be set further into the future, although it may be shortened or the resource may be deleted prior to this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react by sending a graceful termination signal to the containers in the pod. After that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup, remove the pod from the API. In the presence of network partitions, this object may still exist after this timestamp, until an administrator or automated process can determine the resource is fully terminated. If not set, graceful deletion of the object has not been requested.\n\nPopulated by the system when a graceful deletion is requested. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "deletionGracePeriodSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "Number of seconds allowed for this object to gracefully terminate before it will be removed from the system. Only set when deletionTimestamp is also set. May only be shortened. Read-only.", - Type: []string{"integer"}, - Format: "int64", - }, - }, - "labels": { - SchemaProps: spec.SchemaProps{ - Description: "Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "annotations": { - SchemaProps: spec.SchemaProps{ - Description: "Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "ownerReferences": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "uid", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.OwnerReference"), - }, - }, - }, - }, - }, - "finalizers": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Must be empty before the object is deleted from the registry. Each entry is an identifier for the responsible component that will remove the entry from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only be removed. Finalizers may be processed and removed in any order. Order is NOT enforced because it introduces significant risk of stuck finalizers. finalizers is a shared field, any actor with permission can reorder it. If the finalizer list is processed in order, then this can lead to a situation in which the component responsible for the first finalizer in the list is waiting for a signal (field value, external system, or other) produced by a component responsible for a finalizer later in the list, resulting in a deadlock. Without enforced ordering finalizers are free to order amongst themselves and are not vulnerable to ordering changes in the list.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "managedFields": { - SchemaProps: spec.SchemaProps{ - Description: "ManagedFields maps workflow-id and version to the set of fields that are managed by that workflow. This is mostly for internal housekeeping, and users typically shouldn't need to set or understand this field. A workflow can be the user's name, a controller's name, or the name of a specific apply path like \"ci-cd\". The set of fields is always in the version that the workflow used when modifying the object.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ManagedFieldsEntry"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ManagedFieldsEntry", "k8s.io/apimachinery/pkg/apis/meta/v1.OwnerReference", "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_pkg_apis_meta_v1_OwnerReference(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "OwnerReference contains enough information to let you identify an owning object. An owning object must be in the same namespace as the dependent, or be cluster-scoped, so there is no namespace field.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "API version of the referent.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "uid": { - SchemaProps: spec.SchemaProps{ - Description: "UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "controller": { - SchemaProps: spec.SchemaProps{ - Description: "If true, this reference points to the managing controller.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "blockOwnerDeletion": { - SchemaProps: spec.SchemaProps{ - Description: "If true, AND if the owner has the \"foregroundDeletion\" finalizer, then the owner cannot be deleted from the key-value store until this reference is removed. See https://kubernetes.io/docs/concepts/architecture/garbage-collection/#foreground-deletion for how the garbage collector interacts with this field and enforces the foreground deletion. Defaults to false. To set this field, a user needs \"delete\" permission of the owner, otherwise 422 (Unprocessable Entity) will be returned.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"apiVersion", "kind", "name", "uid"}, - }, - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-map-type": "atomic", - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_PartialObjectMetadata(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PartialObjectMetadata is a generic representation of any object with ObjectMeta. It allows clients to get access to a particular ObjectMeta schema without knowing the details of the version.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, - } -} - -func schema_pkg_apis_meta_v1_PartialObjectMetadataList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PartialObjectMetadataList contains a list of objects containing only their metadata", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Description: "items contains each of the included items.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.PartialObjectMetadata"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "k8s.io/apimachinery/pkg/apis/meta/v1.PartialObjectMetadata"}, - } -} - -func schema_pkg_apis_meta_v1_Patch(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Patch is provided to give a concrete name and type to the Kubernetes PATCH request body.", - Type: []string{"object"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_PatchOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PatchOptions may be provided when patching an API object. PatchOptions is meant to be a superset of UpdateOptions.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "dryRun": { - SchemaProps: spec.SchemaProps{ - Description: "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "force": { - SchemaProps: spec.SchemaProps{ - Description: "Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "fieldManager": { - SchemaProps: spec.SchemaProps{ - Description: "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).", - Type: []string{"string"}, - Format: "", - }, - }, - "fieldValidation": { - SchemaProps: spec.SchemaProps{ - Description: "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_Preconditions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Preconditions must be fulfilled before an operation (update, delete, etc.) is carried out.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "uid": { - SchemaProps: spec.SchemaProps{ - Description: "Specifies the target UID.", - Type: []string{"string"}, - Format: "", - }, - }, - "resourceVersion": { - SchemaProps: spec.SchemaProps{ - Description: "Specifies the target ResourceVersion", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_RootPaths(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "RootPaths lists the paths available at root. For example: \"/healthz\", \"/apis\".", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "paths": { - SchemaProps: spec.SchemaProps{ - Description: "paths are the paths available at root.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"paths"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_ServerAddressByClientCIDR(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ServerAddressByClientCIDR helps the client to determine the server address that they should use, depending on the clientCIDR that they match.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "clientCIDR": { - SchemaProps: spec.SchemaProps{ - Description: "The CIDR with which clients can match their IP to figure out the server address that they should use.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "serverAddress": { - SchemaProps: spec.SchemaProps{ - Description: "Address of this server, suitable for a client that matches the above CIDR. This can be a hostname, hostname:port, IP or IP:port.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"clientCIDR", "serverAddress"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_Status(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Status is a return value for calls that don't return other objects.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status of the operation. One of: \"Success\" or \"Failure\". More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "A human-readable description of the status of this operation.", - Type: []string{"string"}, - Format: "", - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "A machine-readable description of why this operation is in the \"Failure\" status. If this value is empty there is no information available. A Reason clarifies an HTTP status code but does not override it.", - Type: []string{"string"}, - Format: "", - }, - }, - "details": { - SchemaProps: spec.SchemaProps{ - Description: "Extended data associated with the reason. Each reason may define its own extended details. This field is optional and the data returned is not guaranteed to conform to any schema except that defined by the reason type.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.StatusDetails"), - }, - }, - "code": { - SchemaProps: spec.SchemaProps{ - Description: "Suggested HTTP return code for this status, 0 if not set.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "k8s.io/apimachinery/pkg/apis/meta/v1.StatusDetails"}, - } -} - -func schema_pkg_apis_meta_v1_StatusCause(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "StatusCause provides more information about an api.Status failure, including cases when multiple errors are encountered.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "A machine-readable description of the cause of the error. If this value is empty there is no information available.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "A human-readable description of the cause of the error. This field may be presented as-is to a reader.", - Type: []string{"string"}, - Format: "", - }, - }, - "field": { - SchemaProps: spec.SchemaProps{ - Description: "The field of the resource that has caused this error, as named by its JSON serialization. May include dot and postfix notation for nested attributes. Arrays are zero-indexed. Fields may appear more than once in an array of causes due to fields having multiple errors. Optional.\n\nExamples:\n \"name\" - the field \"name\" on the current resource\n \"items[0].name\" - the field \"name\" on the first array entry in \"items\"", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_StatusDetails(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "StatusDetails is a set of additional properties that MAY be set by the server to provide additional information about a response. The Reason field of a Status object defines what attributes will be set. Clients must ignore fields that do not match the defined type of each attribute, and should assume that any attribute may be empty, invalid, or under defined.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "The name attribute of the resource associated with the status StatusReason (when there is a single name which can be described).", - Type: []string{"string"}, - Format: "", - }, - }, - "group": { - SchemaProps: spec.SchemaProps{ - Description: "The group attribute of the resource associated with the status StatusReason.", - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "The kind attribute of the resource associated with the status StatusReason. On some operations may differ from the requested resource Kind. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "uid": { - SchemaProps: spec.SchemaProps{ - Description: "UID of the resource. (when there is a single resource which can be described). More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids", - Type: []string{"string"}, - Format: "", - }, - }, - "causes": { - SchemaProps: spec.SchemaProps{ - Description: "The Causes array includes more details associated with the StatusReason failure. Not all StatusReasons may provide detailed causes.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.StatusCause"), - }, - }, - }, - }, - }, - "retryAfterSeconds": { - SchemaProps: spec.SchemaProps{ - Description: "If specified, the time in seconds before the operation should be retried. Some errors may indicate the client must take an alternate action - for those errors this field may indicate how long to wait before taking the alternate action.", - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.StatusCause"}, - } -} - -func schema_pkg_apis_meta_v1_Table(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Table is a tabular representation of a set of API resources. The server transforms the object into a set of preferred columns for quickly reviewing the objects.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "columnDefinitions": { - SchemaProps: spec.SchemaProps{ - Description: "columnDefinitions describes each column in the returned items array. The number of cells per row will always match the number of column definitions.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.TableColumnDefinition"), - }, - }, - }, - }, - }, - "rows": { - SchemaProps: spec.SchemaProps{ - Description: "rows is the list of items in the table.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.TableRow"), - }, - }, - }, - }, - }, - }, - Required: []string{"columnDefinitions", "rows"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "k8s.io/apimachinery/pkg/apis/meta/v1.TableColumnDefinition", "k8s.io/apimachinery/pkg/apis/meta/v1.TableRow"}, - } -} - -func schema_pkg_apis_meta_v1_TableColumnDefinition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "TableColumnDefinition contains information about a column returned in the Table.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "name is a human readable name for the column.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "type": { - SchemaProps: spec.SchemaProps{ - Description: "type is an OpenAPI type definition for this column, such as number, integer, string, or array. See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for more.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "format": { - SchemaProps: spec.SchemaProps{ - Description: "format is an optional OpenAPI type modifier for this column. A format modifies the type and imposes additional rules, like date or time formatting for a string. The 'name' format is applied to the primary identifier column which has type 'string' to assist in clients identifying column is the resource name. See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for more.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "description": { - SchemaProps: spec.SchemaProps{ - Description: "description is a human readable description of this column.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "priority": { - SchemaProps: spec.SchemaProps{ - Description: "priority is an integer defining the relative importance of this column compared to others. Lower numbers are considered higher priority. Columns that may be omitted in limited space scenarios should be given a higher priority.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - Required: []string{"name", "type", "format", "description", "priority"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_TableOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "TableOptions are used when a Table is requested by the caller.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "includeObject": { - SchemaProps: spec.SchemaProps{ - Description: "includeObject decides whether to include each object along with its columnar information. Specifying \"None\" will return no object, specifying \"Object\" will return the full object contents, and specifying \"Metadata\" (the default) will return the object's metadata in the PartialObjectMetadata kind in version v1beta1 of the meta.k8s.io API group.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_TableRow(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "TableRow is an individual row in a table.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "cells": { - SchemaProps: spec.SchemaProps{ - Description: "cells will be as wide as the column definitions array and may contain strings, numbers (float64 or int64), booleans, simple maps, lists, or null. See the type field of the column definition for a more detailed description.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Format: "", - }, - }, - }, - }, - }, - "conditions": { - SchemaProps: spec.SchemaProps{ - Description: "conditions describe additional status of a row that are relevant for a human user. These conditions apply to the row, not to the object, and will be specific to table output. The only defined condition type is 'Completed', for a row that indicates a resource that has run to completion and can be given less visual priority.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.TableRowCondition"), - }, - }, - }, - }, - }, - "object": { - SchemaProps: spec.SchemaProps{ - Description: "This field contains the requested additional information about each object based on the includeObject policy when requesting the Table. If \"None\", this field is empty, if \"Object\" this will be the default serialization of the object for the current API version, and if \"Metadata\" (the default) will contain the object metadata. Check the returned kind and apiVersion of the object before parsing. The media type of the object will always match the enclosing list - if this as a JSON table, these will be JSON encoded objects.", - Ref: ref("k8s.io/apimachinery/pkg/runtime.RawExtension"), - }, - }, - }, - Required: []string{"cells"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.TableRowCondition", "k8s.io/apimachinery/pkg/runtime.RawExtension"}, - } -} - -func schema_pkg_apis_meta_v1_TableRowCondition(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "TableRowCondition allows a row to be marked with additional information.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of row condition. The only defined value is 'Completed' indicating that the object this row represents has reached a completed state and may be given less visual priority than other rows. Clients are not required to honor any conditions but should be consistent where possible about handling the conditions.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status of the condition, one of True, False, Unknown.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "reason": { - SchemaProps: spec.SchemaProps{ - Description: "(brief) machine readable reason for the condition's last transition.", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "Human readable message indicating details about last transition.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type", "status"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_Time(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Time is a wrapper around time.Time which supports correct marshaling to YAML and JSON. Wrappers are provided for many of the factory methods that the time package offers.", - Type: v1.Time{}.OpenAPISchemaType(), - Format: v1.Time{}.OpenAPISchemaFormat(), - }, - }, - } -} - -func schema_pkg_apis_meta_v1_Timestamp(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Timestamp is a struct that is equivalent to Time, but intended for protobuf marshalling/unmarshalling. It is generated into a serialization that matches Time. Do not use in Go structs.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "seconds": { - SchemaProps: spec.SchemaProps{ - Description: "Represents seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.", - Default: 0, - Type: []string{"integer"}, - Format: "int64", - }, - }, - "nanos": { - SchemaProps: spec.SchemaProps{ - Description: "Non-negative fractions of a second at nanosecond resolution. Negative second values with fractions must still have non-negative nanos values that count forward in time. Must be from 0 to 999,999,999 inclusive. This field may be limited in precision depending on context.", - Default: 0, - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - Required: []string{"seconds", "nanos"}, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_TypeMeta(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "TypeMeta describes an individual object in an API response or request with strings representing the type of the object and its API schema version. Structures that are versioned or persisted should inline TypeMeta.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_UpdateOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "UpdateOptions may be provided when updating an API object. All fields in UpdateOptions should also be present in PatchOptions.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "dryRun": { - SchemaProps: spec.SchemaProps{ - Description: "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "fieldManager": { - SchemaProps: spec.SchemaProps{ - Description: "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.", - Type: []string{"string"}, - Format: "", - }, - }, - "fieldValidation": { - SchemaProps: spec.SchemaProps{ - Description: "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_pkg_apis_meta_v1_WatchEvent(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Event represents a single event to a watched resource.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "object": { - SchemaProps: spec.SchemaProps{ - Description: "Object is:\n * If Type is Added or Modified: the new state of the object.\n * If Type is Deleted: the state of the object immediately before deletion.\n * If Type is Error: *Status is recommended; other types may make sense\n depending on context.", - Ref: ref("k8s.io/apimachinery/pkg/runtime.RawExtension"), - }, - }, - }, - Required: []string{"type", "object"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/runtime.RawExtension"}, - } -} - -func schema_k8sio_apimachinery_pkg_runtime_RawExtension(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "RawExtension is used to hold extensions in external versions.\n\nTo use this, make a field which has RawExtension as its type in your external, versioned struct, and Object in your internal struct. You also need to register your various plugin types.\n\n// Internal package:\n\n\ttype MyAPIObject struct {\n\t\truntime.TypeMeta `json:\",inline\"`\n\t\tMyPlugin runtime.Object `json:\"myPlugin\"`\n\t}\n\n\ttype PluginA struct {\n\t\tAOption string `json:\"aOption\"`\n\t}\n\n// External package:\n\n\ttype MyAPIObject struct {\n\t\truntime.TypeMeta `json:\",inline\"`\n\t\tMyPlugin runtime.RawExtension `json:\"myPlugin\"`\n\t}\n\n\ttype PluginA struct {\n\t\tAOption string `json:\"aOption\"`\n\t}\n\n// On the wire, the JSON will look something like this:\n\n\t{\n\t\t\"kind\":\"MyAPIObject\",\n\t\t\"apiVersion\":\"v1\",\n\t\t\"myPlugin\": {\n\t\t\t\"kind\":\"PluginA\",\n\t\t\t\"aOption\":\"foo\",\n\t\t},\n\t}\n\nSo what happens? Decode first uses json or yaml to unmarshal the serialized data into your external MyAPIObject. That causes the raw JSON to be stored, but not unpacked. The next step is to copy (using pkg/conversion) into the internal struct. The runtime package's DefaultScheme has conversion functions installed which will unpack the JSON stored in RawExtension, turning it into the correct object type, and storing it in the Object. (TODO: In the case where the object is of an unknown type, a runtime.Unknown object will be created and stored.)", - Type: []string{"object"}, - }, - }, - } -} - -func schema_k8sio_apimachinery_pkg_runtime_TypeMeta(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "TypeMeta is shared by all top level objects. The proper way to use it is to inline it in your type, like this:\n\n\ttype MyAwesomeAPIObject struct {\n\t runtime.TypeMeta `json:\",inline\"`\n\t ... // other fields\n\t}\n\nfunc (obj *MyAwesomeAPIObject) SetGroupVersionKind(gvk *metav1.GroupVersionKind) { metav1.UpdateTypeMeta(obj,gvk) }; GroupVersionKind() *GroupVersionKind\n\nTypeMeta is provided here for convenience. You may use it directly from this package or define your own with the same fields.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_k8sio_apimachinery_pkg_runtime_Unknown(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Unknown allows api objects with unknown types to be passed-through. This can be used to deal with the API objects from a plug-in. Unknown objects still have functioning TypeMeta features-- kind, version, etc. metadata and field mutatation.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "kind": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "ContentEncoding": { - SchemaProps: spec.SchemaProps{ - Description: "ContentEncoding is encoding used to encode 'Raw' data. Unspecified means no encoding.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "ContentType": { - SchemaProps: spec.SchemaProps{ - Description: "ContentType is serialization method used to serialize 'Raw'. Unspecified means ContentTypeJSON.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"ContentEncoding", "ContentType"}, - }, - }, - } -} - -func schema_apimachinery_pkg_util_intstr_IntOrString(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.EmbedOpenAPIDefinitionIntoV2Extension(common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "IntOrString is a type that can hold an int32 or a string. When used in JSON or YAML marshalling and unmarshalling, it produces or consumes the inner type. This allows you to have, for example, a JSON field that can accept a name or number.", - OneOf: common.GenerateOpenAPIV3OneOfSchema(intstr.IntOrString{}.OpenAPIV3OneOfTypes()), - Format: intstr.IntOrString{}.OpenAPISchemaFormat(), - }, - }, - }, common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "IntOrString is a type that can hold an int32 or a string. When used in JSON or YAML marshalling and unmarshalling, it produces or consumes the inner type. This allows you to have, for example, a JSON field that can accept a name or number.", - Type: intstr.IntOrString{}.OpenAPISchemaType(), - Format: intstr.IntOrString{}.OpenAPISchemaFormat(), - }, - }, - }) -} - -func schema_k8sio_apimachinery_pkg_version_Info(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Info contains versioning information. how we'll want to distribute that information.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "major": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "minor": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "gitVersion": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "gitCommit": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "gitTreeState": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "buildDate": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "goVersion": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "compiler": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "platform": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"major", "minor", "gitVersion", "gitCommit", "gitTreeState", "buildDate", "goVersion", "compiler", "platform"}, - }, - }, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_ContainerView(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "A single application container that you want to run within a pod.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Description: "Name of the container specified as a DNS_LABEL. Each container in a pod must have a unique name (DNS_LABEL). Cannot be updated.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "image": { - SchemaProps: spec.SchemaProps{ - Description: "Docker image name. More info: https://kubernetes.io/docs/concepts/containers/images This field is optional to allow higher level config management to default or override container images in workload controllers like Deployments and StatefulSets.", - Type: []string{"string"}, - Format: "", - }, - }, - "command": { - SchemaProps: spec.SchemaProps{ - Description: "Entrypoint array. Not executed within a shell. The docker image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "args": { - SchemaProps: spec.SchemaProps{ - Description: "Arguments to the entrypoint. The docker image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "workingDir": { - SchemaProps: spec.SchemaProps{ - Description: "Container's working directory. If not specified, the container runtime's default will be used, which might be configured in the container image. Cannot be updated.", - Type: []string{"string"}, - Format: "", - }, - }, - "ports": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-list-map-keys": []interface{}{ - "containerPort", - "protocol", - }, - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "containerPort", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of ports to expose from the container. Exposing a port here gives the system additional information about the network connections a container uses, but is primarily informational. Not specifying a port here DOES NOT prevent that port from being exposed. Any port which is listening on the default \"0.0.0.0\" address inside a container will be accessible from the network. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ContainerPort"), - }, - }, - }, - }, - }, - "envFrom": { - SchemaProps: spec.SchemaProps{ - Description: "List of sources to populate environment variables in the container. The keys defined within a source must be a C_IDENTIFIER. All invalid keys will be reported as an event when the container is starting. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EnvFromSource"), - }, - }, - }, - }, - }, - "env": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "List of environment variables to set in the container. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.EnvVar"), - }, - }, - }, - }, - }, - "resources": { - SchemaProps: spec.SchemaProps{ - Description: "Compute Resources required by this container. Cannot be updated. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/", - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.ResourceView"), - }, - }, - "volumeMounts": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "mountPath", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "Pod volumes to mount into the container's filesystem. Cannot be updated.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.VolumeMount"), - }, - }, - }, - }, - }, - "volumeDevices": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-patch-merge-key": "devicePath", - "x-kubernetes-patch-strategy": "merge", - }, - }, - SchemaProps: spec.SchemaProps{ - Description: "volumeDevices is the list of block devices to be used by the container.", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.VolumeDevice"), - }, - }, - }, - }, - }, - "livenessProbe": { - SchemaProps: spec.SchemaProps{ - Description: "Periodic probe of container liveness. Container will be restarted if the probe fails. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "readinessProbe": { - SchemaProps: spec.SchemaProps{ - Description: "Periodic probe of container service readiness. Container will be removed from service endpoints if the probe fails. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "startupProbe": { - SchemaProps: spec.SchemaProps{ - Description: "StartupProbe indicates that the Pod has successfully initialized. If specified, no other probes are executed until this completes successfully. If this probe fails, the Pod will be restarted, just as if the livenessProbe failed. This can be used to provide different probe parameters at the beginning of a Pod's lifecycle, when it might take a long time to load data or warm a cache, than during steady-state operation. This cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", - Ref: ref("k8s.io/api/core/v1.Probe"), - }, - }, - "lifecycle": { - SchemaProps: spec.SchemaProps{ - Description: "Actions that the management system should take in response to container lifecycle events. Cannot be updated.", - Ref: ref("k8s.io/api/core/v1.Lifecycle"), - }, - }, - "terminationMessagePath": { - SchemaProps: spec.SchemaProps{ - Description: "Optional: Path at which the file to which the container's termination message will be written is mounted into the container's filesystem. Message written is intended to be brief final status, such as an assertion failure message. Will be truncated by the node if greater than 4096 bytes. The total message length across all containers will be limited to 12kb. Defaults to /dev/termination-log. Cannot be updated.", - Type: []string{"string"}, - Format: "", - }, - }, - "terminationMessagePolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Indicate how the termination message should be populated. File will use the contents of terminationMessagePath to populate the container status message on both success and failure. FallbackToLogsOnError will use the last chunk of container log output if the termination message file is empty and the container exited with an error. The log output is limited to 2048 bytes or 80 lines, whichever is smaller. Defaults to File. Cannot be updated.\n\nPossible enum values:\n - `\"FallbackToLogsOnError\"` will read the most recent contents of the container logs for the container status message when the container exits with an error and the terminationMessagePath has no contents.\n - `\"File\"` is the default behavior and will set the container status message to the contents of the container's terminationMessagePath when the container exits.", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"FallbackToLogsOnError", "File"}, - }, - }, - "imagePullPolicy": { - SchemaProps: spec.SchemaProps{ - Description: "Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More info: https://kubernetes.io/docs/concepts/containers/images#updating-images\n\nPossible enum values:\n - `\"Always\"` means that kubelet always attempts to pull the latest image. Container will fail If the pull fails.\n - `\"IfNotPresent\"` means that kubelet pulls if the image isn't present on disk. Container will fail if the image isn't present and the pull fails.\n - `\"Never\"` means that kubelet never pulls an image, but only uses a local image. Container will fail if the image isn't present", - Type: []string{"string"}, - Format: "", - Enum: []interface{}{"Always", "IfNotPresent", "Never"}, - }, - }, - "securityContext": { - SchemaProps: spec.SchemaProps{ - Description: "Security options the pod should run with. More info: https://kubernetes.io/docs/concepts/policy/security-context/ More info: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/", - Ref: ref("k8s.io/api/core/v1.SecurityContext"), - }, - }, - "stdin": { - SchemaProps: spec.SchemaProps{ - Description: "Whether this container should allocate a buffer for stdin in the container runtime. If this is not set, reads from stdin in the container will always result in EOF. Default is false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - "stdinOnce": { - SchemaProps: spec.SchemaProps{ - Description: "Whether the container runtime should close the stdin channel after it has been opened by a single attach. When stdin is true the stdin stream will remain open across multiple attach sessions. If stdinOnce is set to true, stdin is opened on container start, is empty until the first client attaches to stdin, and then remains open and accepts data until the client disconnects, at which time stdin is closed and remains closed until the container is restarted. If this flag is false, a container processes that reads from stdin will never receive an EOF. Default is false", - Type: []string{"boolean"}, - Format: "", - }, - }, - "tty": { - SchemaProps: spec.SchemaProps{ - Description: "Whether this container should allocate a TTY for itself, also requires 'stdin' to be true. Default is false.", - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"name"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ContainerPort", "k8s.io/api/core/v1.EnvFromSource", "k8s.io/api/core/v1.EnvVar", "k8s.io/api/core/v1.Lifecycle", "k8s.io/api/core/v1.Probe", "k8s.io/api/core/v1.SecurityContext", "k8s.io/api/core/v1.VolumeDevice", "k8s.io/api/core/v1.VolumeMount", "kmodules.xyz/resource-metadata/apis/core/v1alpha1.ResourceView"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_ControlPlaneInfo(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "https://github.com/kmodules/client-go/blob/kubernetes-1.16.3/tools/analytics/analytics.go#L66", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "dnsNames": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "emailAddresses": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "ipAddresses": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "uris": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "notBefore": { - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - "notAfter": { - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Time"), - }, - }, - }, - Required: []string{"notBefore", "notAfter"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Time"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_ExecServiceFacilitator(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "alias": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "resource": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "ref": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/client-go/api/v1.ObjectReference"), - }, - }, - "container": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "command": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "kubectlCommand": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "help": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"alias", "resource", "ref", "container", "command"}, - }, - }, - Dependencies: []string{ - "kmodules.xyz/client-go/api/v1.ObjectReference"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_GenericResource(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/runtime.RawExtension"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "k8s.io/apimachinery/pkg/runtime.RawExtension", "kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceSpec"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_GenericResourceList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResource"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResource"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_GenericResourceService(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceServiceSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/runtime.RawExtension"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "k8s.io/apimachinery/pkg/runtime.RawExtension", "kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceServiceSpec"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_GenericResourceServiceFacilitator(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "usage": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "resource": { - SchemaProps: spec.SchemaProps{ - Ref: ref("kmodules.xyz/client-go/api/v1.ResourceID"), - }, - }, - "refs": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/client-go/api/v1.ObjectReference"), - }, - }, - }, - }, - }, - }, - Required: []string{"usage"}, - }, - }, - Dependencies: []string{ - "kmodules.xyz/client-go/api/v1.ObjectReference", "kmodules.xyz/client-go/api/v1.ResourceID"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_GenericResourceServiceFacilities(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "exposed": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceServiceFacilitator"), - }, - }, - "tls": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceServiceFacilitator"), - }, - }, - "backup": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceServiceFacilitator"), - }, - }, - "monitoring": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceServiceFacilitator"), - }, - }, - "exec": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.ExecServiceFacilitator"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.ExecServiceFacilitator", "kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceServiceFacilitator"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_GenericResourceServiceList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceService"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceService"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_GenericResourceServiceSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "cluster": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/client-go/api/v1.ClusterMetadata"), - }, - }, - "apiType": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/client-go/api/v1.ResourceID"), - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "facilities": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceServiceFacilities"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceServiceStatus"), - }, - }, - }, - Required: []string{"apiType", "status"}, - }, - }, - Dependencies: []string{ - "kmodules.xyz/client-go/api/v1.ClusterMetadata", "kmodules.xyz/client-go/api/v1.ResourceID", "kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceServiceFacilities", "kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceServiceStatus"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_GenericResourceServiceStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "Message", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_GenericResourceSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "cluster": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/client-go/api/v1.ClusterMetadata"), - }, - }, - "apiType": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/client-go/api/v1.ResourceID"), - }, - }, - "name": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "uid": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "version": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "replicas": { - SchemaProps: spec.SchemaProps{ - Type: []string{"integer"}, - Format: "int64", - }, - }, - "roleReplicas": { - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: 0, - Type: []string{"integer"}, - Format: "int64", - }, - }, - }, - }, - }, - "mode": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "totalResource": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ResourceRequirements"), - }, - }, - "appResource": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ResourceRequirements"), - }, - }, - "roleResourceLimits": { - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - }, - }, - }, - "roleResourceRequests": { - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - }, - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceStatus"), - }, - }, - }, - Required: []string{"apiType", "name", "status"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ResourceRequirements", "k8s.io/apimachinery/pkg/api/resource.Quantity", "kmodules.xyz/client-go/api/v1.ClusterMetadata", "kmodules.xyz/client-go/api/v1.ResourceID", "kmodules.xyz/resource-metadata/apis/core/v1alpha1.GenericResourceStatus"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_GenericResourceStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "status": { - SchemaProps: spec.SchemaProps{ - Description: "Status", - Type: []string{"string"}, - Format: "", - }, - }, - "message": { - SchemaProps: spec.SchemaProps{ - Description: "Message", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_KubernetesInfo(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "clusterName": { - SchemaProps: spec.SchemaProps{ - Description: "https://github.com/kmodules/client-go/blob/master/tools/clusterid/lib.go", - Type: []string{"string"}, - Format: "", - }, - }, - "clusterUID": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "version": { - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/version.Info"), - }, - }, - "controlPlane": { - SchemaProps: spec.SchemaProps{ - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.ControlPlaneInfo"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/version.Info", "kmodules.xyz/resource-metadata/apis/core/v1alpha1.ControlPlaneInfo"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_PodView(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.PodViewSpec"), - }, - }, - "status": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.PodStatus"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.PodStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "kmodules.xyz/resource-metadata/apis/core/v1alpha1.PodViewSpec"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_PodViewList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.PodView"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "kmodules.xyz/resource-metadata/apis/core/v1alpha1.PodView"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_PodViewSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "PodViewSpec defines the desired state of PodView", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "resources": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.ResourceView"), - }, - }, - "containers": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.ContainerView"), - }, - }, - }, - }, - }, - }, - Required: []string{"resources", "containers"}, - }, - }, - Dependencies: []string{ - "kmodules.xyz/resource-metadata/apis/core/v1alpha1.ContainerView", "kmodules.xyz/resource-metadata/apis/core/v1alpha1.ResourceView"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_Project(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "Project is the Schema for the projects API", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.ProjectSpec"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "kmodules.xyz/resource-metadata/apis/core/v1alpha1.ProjectSpec"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_ProjectList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ProjectList contains a list of Project", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.Project"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "kmodules.xyz/resource-metadata/apis/core/v1alpha1.Project"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_ProjectMonitoring(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "prometheusURL": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "grafanaURL": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "alertmanagerURL": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "prometheusRef": { - SchemaProps: spec.SchemaProps{ - Ref: ref("kmodules.xyz/client-go/api/v1.ObjectReference"), - }, - }, - "alertmanagerRef": { - SchemaProps: spec.SchemaProps{ - Ref: ref("kmodules.xyz/client-go/api/v1.ObjectReference"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "kmodules.xyz/client-go/api/v1.ObjectReference"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_ProjectSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ProjectSpec defines the desired state of Project", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "namespaces": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "namespaceSelector": { - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"), - }, - }, - "monitoring": { - SchemaProps: spec.SchemaProps{ - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.ProjectMonitoring"), - }, - }, - "presets": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.SourceLocator"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector", "kmodules.xyz/resource-metadata/apis/core/v1alpha1.ProjectMonitoring", "kmodules.xyz/resource-metadata/apis/shared.SourceLocator"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_ResourceSummary(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), - }, - }, - "spec": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.ResourceSummarySpec"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta", "kmodules.xyz/resource-metadata/apis/core/v1alpha1.ResourceSummarySpec"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_ResourceSummaryList(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "kind": { - SchemaProps: spec.SchemaProps{ - Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - Type: []string{"string"}, - Format: "", - }, - }, - "apiVersion": { - SchemaProps: spec.SchemaProps{ - Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - Type: []string{"string"}, - Format: "", - }, - }, - "metadata": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/core/v1alpha1.ResourceSummary"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", "kmodules.xyz/resource-metadata/apis/core/v1alpha1.ResourceSummary"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_ResourceSummarySpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "cluster": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/client-go/api/v1.ClusterMetadata"), - }, - }, - "apiType": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/client-go/api/v1.ResourceID"), - }, - }, - "totalResource": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ResourceRequirements"), - }, - }, - "appResource": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/api/core/v1.ResourceRequirements"), - }, - }, - "count": { - SchemaProps: spec.SchemaProps{ - Type: []string{"integer"}, - Format: "int32", - }, - }, - }, - Required: []string{"apiType"}, - }, - }, - Dependencies: []string{ - "k8s.io/api/core/v1.ResourceRequirements", "kmodules.xyz/client-go/api/v1.ClusterMetadata", "kmodules.xyz/client-go/api/v1.ResourceID"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_ResourceView(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Description: "ResourceView describes the compute resource requirements.", - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "limits": { - SchemaProps: spec.SchemaProps{ - Description: "Limits describes the maximum amount of compute resources allowed. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "requests": { - SchemaProps: spec.SchemaProps{ - Description: "Requests describes the minimum amount of compute resources required. If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - "usage": { - SchemaProps: spec.SchemaProps{ - Description: "Limits describes the maximum amount of compute resources allowed. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/api/resource.Quantity"), - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/api/resource.Quantity"}, - } -} - -func schema_resource_metadata_apis_core_v1alpha1_Service(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "ref": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.GroupKind"), - }, - }, - "query": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.ResourceQuery"), - }, - }, - }, - Required: []string{"name", "ref", "query"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.GroupKind", "kmodules.xyz/resource-metadata/apis/shared.ResourceQuery"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_Action(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "description": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "icons": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("x-helm.dev/apimachinery/apis/shared.ImageSpec"), - }, - }, - }, - }, - }, - "operationId": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "flow": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "disabled": { - SchemaProps: spec.SchemaProps{ - Default: false, - Type: []string{"boolean"}, - Format: "", - }, - }, - "editor": { - SchemaProps: spec.SchemaProps{ - Ref: ref("x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef"), - }, - }, - }, - Required: []string{"operationId", "flow", "disabled"}, - }, - }, - Dependencies: []string{ - "x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef", "x-helm.dev/apimachinery/apis/shared.ImageSpec"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_ActionGroup(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "description": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.Action"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "kmodules.xyz/resource-metadata/apis/shared.Action"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_ActionInfo(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "description": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_ActionTemplate(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "description": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "icons": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("x-helm.dev/apimachinery/apis/shared.ImageSpec"), - }, - }, - }, - }, - }, - "operationId": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "flow": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "disabledTemplate": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "editor": { - SchemaProps: spec.SchemaProps{ - Ref: ref("x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef"), - }, - }, - "enforceQuota": { - SchemaProps: spec.SchemaProps{ - Default: false, - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"operationId", "flow", "enforceQuota"}, - }, - }, - Dependencies: []string{ - "x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef", "x-helm.dev/apimachinery/apis/shared.ImageSpec"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_ActionTemplateGroup(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "description": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.ActionTemplate"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "kmodules.xyz/resource-metadata/apis/shared.ActionTemplate"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_BootstrapPresets(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "offlineInstaller": { - SchemaProps: spec.SchemaProps{ - Default: false, - Type: []string{"boolean"}, - Format: "", - }, - }, - "image": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.ImageRegistrySpec"), - }, - }, - "registry": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.RegistryInfo"), - }, - }, - "helm": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.HelmInfo"), - }, - }, - }, - Required: []string{"image", "registry", "helm"}, - }, - }, - Dependencies: []string{ - "kmodules.xyz/resource-metadata/apis/shared.HelmInfo", "kmodules.xyz/resource-metadata/apis/shared.ImageRegistrySpec", "kmodules.xyz/resource-metadata/apis/shared.RegistryInfo"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_Dashboard(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "title": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "vars": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.DashboardVar"), - }, - }, - }, - }, - }, - "panels": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "if": { - SchemaProps: spec.SchemaProps{ - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.If"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "kmodules.xyz/resource-metadata/apis/shared.DashboardVar", "kmodules.xyz/resource-metadata/apis/shared.If"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_DashboardVar(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "value": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "type": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name", "value"}, - }, - }, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_DeploymentParameters(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "productID": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "planID": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "chart": { - SchemaProps: spec.SchemaProps{ - Ref: ref("x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_HelmInfo(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "repositories": { - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.HelmRepository"), - }, - }, - }, - }, - }, - "releases": { - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.HelmRelease"), - }, - }, - }, - }, - }, - }, - Required: []string{"repositories", "releases"}, - }, - }, - Dependencies: []string{ - "kmodules.xyz/resource-metadata/apis/shared.HelmRelease", "kmodules.xyz/resource-metadata/apis/shared.HelmRepository"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_HelmRelease(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "enabled": { - SchemaProps: spec.SchemaProps{ - Default: false, - Type: []string{"boolean"}, - Format: "", - }, - }, - "version": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "values": { - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/runtime.RawExtension"), - }, - }, - }, - Required: []string{"enabled", "version"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/runtime.RawExtension"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_HelmRepository(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "url": { - SchemaProps: spec.SchemaProps{ - Description: "URL of the Helm repository, a valid URL contains at least a protocol and host.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "secretName": { - SchemaProps: spec.SchemaProps{ - Description: "SecretRef specifies the Secret containing authentication credentials for the HelmRepository. For HTTP/S basic auth the secret must contain 'username' and 'password' fields. For TLS the secret must contain a 'certFile' and 'keyFile', and/or 'caFile' fields.", - Type: []string{"string"}, - Format: "", - }, - }, - "interval": { - SchemaProps: spec.SchemaProps{ - Description: "Interval at which to check the URL for updates.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Duration"), - }, - }, - "timeout": { - SchemaProps: spec.SchemaProps{ - Description: "The timeout of index downloading, defaults to 60s.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Duration"), - }, - }, - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of the HelmRepository. When this field is set to \"oci\", the URL field value must be prefixed with \"oci://\".", - Type: []string{"string"}, - Format: "", - }, - }, - "provider": { - SchemaProps: spec.SchemaProps{ - Description: "Provider used for authentication, can be 'aws', 'azure', 'gcp' or 'generic'. This field is optional, and only taken into account if the .spec.type field is set to 'oci'. When not specified, defaults to 'generic'.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"url"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Duration"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_If(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "condition": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "connected": { - SchemaProps: spec.SchemaProps{ - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.ResourceLocator"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "kmodules.xyz/resource-metadata/apis/shared.ResourceLocator"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_ImageRegistrySpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "proxies": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.RegistryProxies"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "kmodules.xyz/resource-metadata/apis/shared.RegistryProxies"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_RegistryInfo(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "credentials": { - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - }, - }, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_RegistryProxies(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "dockerHub": { - SchemaProps: spec.SchemaProps{ - Description: "company/bin:1.23", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "dockerLibrary": { - SchemaProps: spec.SchemaProps{ - Description: "alpine, nginx etc.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "ghcr": { - SchemaProps: spec.SchemaProps{ - Description: "ghcr.io", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "quay": { - SchemaProps: spec.SchemaProps{ - Description: "quay.io", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "kubernetes": { - SchemaProps: spec.SchemaProps{ - Description: "registry.k8s.io", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "appscode": { - SchemaProps: spec.SchemaProps{ - Description: "r.appscode.com", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_ResourceLocator(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "ref": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.GroupKind"), - }, - }, - "query": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.ResourceQuery"), - }, - }, - }, - Required: []string{"ref", "query"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.GroupKind", "kmodules.xyz/resource-metadata/apis/shared.ResourceQuery"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_ResourceQuery(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "byLabel": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "raw": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type"}, - }, - }, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_SourceLocator(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "resource": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/client-go/api/v1.ResourceID"), - }, - }, - "ref": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/client-go/api/v1.ObjectReference"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "kmodules.xyz/client-go/api/v1.ObjectReference", "kmodules.xyz/client-go/api/v1.ResourceID"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_UIParameterTemplate(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "options": { - SchemaProps: spec.SchemaProps{ - Ref: ref("x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef"), - }, - }, - "editor": { - SchemaProps: spec.SchemaProps{ - Ref: ref("x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef"), - }, - }, - "enforceQuota": { - SchemaProps: spec.SchemaProps{ - Default: false, - Type: []string{"boolean"}, - Format: "", - }, - }, - "actions": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.ActionTemplateGroup"), - }, - }, - }, - }, - }, - "instanceLabelPaths": { - SchemaProps: spec.SchemaProps{ - Description: "app.kubernetes.io/instance label must be updated at these paths when refilling metadata", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"enforceQuota"}, - }, - }, - Dependencies: []string{ - "kmodules.xyz/resource-metadata/apis/shared.ActionTemplateGroup", "x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_UIParameters(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "options": { - SchemaProps: spec.SchemaProps{ - Ref: ref("x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef"), - }, - }, - "editor": { - SchemaProps: spec.SchemaProps{ - Ref: ref("x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef"), - }, - }, - "actions": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.ActionGroup"), - }, - }, - }, - }, - }, - "instanceLabelPaths": { - SchemaProps: spec.SchemaProps{ - Description: "app.kubernetes.io/instance label must be updated at these paths when refilling metadata", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "kmodules.xyz/resource-metadata/apis/shared.ActionGroup", "x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef"}, - } -} diff --git a/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/podview_types.go b/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/podview_types.go deleted file mode 100644 index ac46a4342..000000000 --- a/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/podview_types.go +++ /dev/null @@ -1,239 +0,0 @@ -/* -Copyright 2021. - -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 v1alpha1 - -import ( - core "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -const ( - ResourceKindPodView = "PodView" - ResourcePodView = "podview" - ResourcePodViews = "podviews" -) - -// PodViewSpec defines the desired state of PodView -type PodViewSpec struct { - Resources ResourceView `json:"resources"` - Containers []ContainerView `json:"containers"` -} - -// A single application container that you want to run within a pod. -type ContainerView struct { - // Name of the container specified as a DNS_LABEL. - // Each container in a pod must have a unique name (DNS_LABEL). - // Cannot be updated. - Name string `json:"name" protobuf:"bytes,1,opt,name=name"` - // Docker image name. - // More info: https://kubernetes.io/docs/concepts/containers/images - // This field is optional to allow higher level config management to default or override - // container images in workload controllers like Deployments and StatefulSets. - // +optional - Image string `json:"image,omitempty" protobuf:"bytes,2,opt,name=image"` - // Entrypoint array. Not executed within a shell. - // The docker image's ENTRYPOINT is used if this is not provided. - // Variable references $(VAR_NAME) are expanded using the container's environment. If a variable - // cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax - // can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, - // regardless of whether the variable exists or not. - // Cannot be updated. - // More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell - // +optional - Command []string `json:"command,omitempty" protobuf:"bytes,3,rep,name=command"` - // Arguments to the entrypoint. - // The docker image's CMD is used if this is not provided. - // Variable references $(VAR_NAME) are expanded using the container's environment. If a variable - // cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax - // can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, - // regardless of whether the variable exists or not. - // Cannot be updated. - // More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell - // +optional - Args []string `json:"args,omitempty" protobuf:"bytes,4,rep,name=args"` - // Container's working directory. - // If not specified, the container runtime's default will be used, which - // might be configured in the container image. - // Cannot be updated. - // +optional - WorkingDir string `json:"workingDir,omitempty" protobuf:"bytes,5,opt,name=workingDir"` - // List of ports to expose from the container. Exposing a port here gives - // the system additional information about the network connections a - // container uses, but is primarily informational. Not specifying a port here - // DOES NOT prevent that port from being exposed. Any port which is - // listening on the default "0.0.0.0" address inside a container will be - // accessible from the network. - // Cannot be updated. - // +optional - // +patchMergeKey=containerPort - // +patchStrategy=merge - // +listType=map - // +listMapKey=containerPort - // +listMapKey=protocol - Ports []core.ContainerPort `json:"ports,omitempty" patchStrategy:"merge" patchMergeKey:"containerPort" protobuf:"bytes,6,rep,name=ports"` - // List of sources to populate environment variables in the container. - // The keys defined within a source must be a C_IDENTIFIER. All invalid keys - // will be reported as an event when the container is starting. When a key exists in multiple - // sources, the value associated with the last source will take precedence. - // Values defined by an Env with a duplicate key will take precedence. - // Cannot be updated. - // +optional - EnvFrom []core.EnvFromSource `json:"envFrom,omitempty" protobuf:"bytes,19,rep,name=envFrom"` - // List of environment variables to set in the container. - // Cannot be updated. - // +optional - // +patchMergeKey=name - // +patchStrategy=merge - Env []core.EnvVar `json:"env,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,7,rep,name=env"` - // Compute Resources required by this container. - // Cannot be updated. - // More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ - // +optional - Resources ResourceView `json:"resources,omitempty" protobuf:"bytes,8,opt,name=resources"` - // Pod volumes to mount into the container's filesystem. - // Cannot be updated. - // +optional - // +patchMergeKey=mountPath - // +patchStrategy=merge - VolumeMounts []core.VolumeMount `json:"volumeMounts,omitempty" patchStrategy:"merge" patchMergeKey:"mountPath" protobuf:"bytes,9,rep,name=volumeMounts"` - // volumeDevices is the list of block devices to be used by the container. - // +patchMergeKey=devicePath - // +patchStrategy=merge - // +optional - VolumeDevices []core.VolumeDevice `json:"volumeDevices,omitempty" patchStrategy:"merge" patchMergeKey:"devicePath" protobuf:"bytes,21,rep,name=volumeDevices"` - // Periodic probe of container liveness. - // Container will be restarted if the probe fails. - // Cannot be updated. - // More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes - // +optional - LivenessProbe *core.Probe `json:"livenessProbe,omitempty" protobuf:"bytes,10,opt,name=livenessProbe"` - // Periodic probe of container service readiness. - // Container will be removed from service endpoints if the probe fails. - // Cannot be updated. - // More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes - // +optional - ReadinessProbe *core.Probe `json:"readinessProbe,omitempty" protobuf:"bytes,11,opt,name=readinessProbe"` - // StartupProbe indicates that the Pod has successfully initialized. - // If specified, no other probes are executed until this completes successfully. - // If this probe fails, the Pod will be restarted, just as if the livenessProbe failed. - // This can be used to provide different probe parameters at the beginning of a Pod's lifecycle, - // when it might take a long time to load data or warm a cache, than during steady-state operation. - // This cannot be updated. - // More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes - // +optional - StartupProbe *core.Probe `json:"startupProbe,omitempty" protobuf:"bytes,22,opt,name=startupProbe"` - // Actions that the management system should take in response to container lifecycle events. - // Cannot be updated. - // +optional - Lifecycle *core.Lifecycle `json:"lifecycle,omitempty" protobuf:"bytes,12,opt,name=lifecycle"` - // Optional: Path at which the file to which the container's termination message - // will be written is mounted into the container's filesystem. - // Message written is intended to be brief final status, such as an assertion failure message. - // Will be truncated by the node if greater than 4096 bytes. The total message length across - // all containers will be limited to 12kb. - // Defaults to /dev/termination-log. - // Cannot be updated. - // +optional - TerminationMessagePath string `json:"terminationMessagePath,omitempty" protobuf:"bytes,13,opt,name=terminationMessagePath"` - // Indicate how the termination message should be populated. File will use the contents of - // terminationMessagePath to populate the container status message on both success and failure. - // FallbackToLogsOnError will use the last chunk of container log output if the termination - // message file is empty and the container exited with an error. - // The log output is limited to 2048 bytes or 80 lines, whichever is smaller. - // Defaults to File. - // Cannot be updated. - // +optional - TerminationMessagePolicy core.TerminationMessagePolicy `json:"terminationMessagePolicy,omitempty" protobuf:"bytes,20,opt,name=terminationMessagePolicy,casttype=TerminationMessagePolicy"` - // Image pull policy. - // One of Always, Never, IfNotPresent. - // Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. - // Cannot be updated. - // More info: https://kubernetes.io/docs/concepts/containers/images#updating-images - // +optional - ImagePullPolicy core.PullPolicy `json:"imagePullPolicy,omitempty" protobuf:"bytes,14,opt,name=imagePullPolicy,casttype=PullPolicy"` - // Security options the pod should run with. - // More info: https://kubernetes.io/docs/concepts/policy/security-context/ - // More info: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/ - // +optional - SecurityContext *core.SecurityContext `json:"securityContext,omitempty" protobuf:"bytes,15,opt,name=securityContext"` - - // Variables for interactive containers, these have very specialized use-cases (e.g. debugging) - // and shouldn't be used for general purpose containers. - - // Whether this container should allocate a buffer for stdin in the container runtime. If this - // is not set, reads from stdin in the container will always result in EOF. - // Default is false. - // +optional - Stdin bool `json:"stdin,omitempty" protobuf:"varint,16,opt,name=stdin"` - // Whether the container runtime should close the stdin channel after it has been opened by - // a single attach. When stdin is true the stdin stream will remain open across multiple attach - // sessions. If stdinOnce is set to true, stdin is opened on container start, is empty until the - // first client attaches to stdin, and then remains open and accepts data until the client disconnects, - // at which time stdin is closed and remains closed until the container is restarted. If this - // flag is false, a container processes that reads from stdin will never receive an EOF. - // Default is false - // +optional - StdinOnce bool `json:"stdinOnce,omitempty" protobuf:"varint,17,opt,name=stdinOnce"` - // Whether this container should allocate a TTY for itself, also requires 'stdin' to be true. - // Default is false. - // +optional - TTY bool `json:"tty,omitempty" protobuf:"varint,18,opt,name=tty"` -} - -// ResourceView describes the compute resource requirements. -type ResourceView struct { - // Limits describes the maximum amount of compute resources allowed. - // More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ - // +optional - Limits core.ResourceList `json:"limits,omitempty"` - // Requests describes the minimum amount of compute resources required. - // If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, - // otherwise to an implementation-defined value. - // More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ - // +optional - Requests core.ResourceList `json:"requests,omitempty"` - // Limits describes the maximum amount of compute resources allowed. - // More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ - // +optional - Usage core.ResourceList `json:"usage,omitempty"` -} - -// PodView is the Schema for the podviews API - -// +genclient -// +genclient:onlyVerbs=get,list -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type PodView struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec PodViewSpec `json:"spec,omitempty"` - Status core.PodStatus `json:"status,omitempty"` -} - -// PodViewList contains a list of PodView - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type PodViewList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []PodView `json:"items"` -} - -func init() { - SchemeBuilder.Register(&PodView{}, &PodViewList{}) -} diff --git a/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/project_types.go b/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/project_types.go deleted file mode 100644 index 949768848..000000000 --- a/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/project_types.go +++ /dev/null @@ -1,86 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import ( - kmapi "kmodules.xyz/client-go/api/v1" - "kmodules.xyz/resource-metadata/apis/shared" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -const ( - ResourceKindProject = "Project" - ResourceProject = "project" - ResourceProjects = "projects" -) - -// ProjectSpec defines the desired state of Project -type ProjectSpec struct { - // +kubebuilder:default=User - Type ProjectType `json:"type,omitempty"` - Namespaces []string `json:"namespaces,omitempty"` - NamespaceSelector *metav1.LabelSelector `json:"namespaceSelector,omitempty"` - Monitoring *ProjectMonitoring `json:"monitoring,omitempty"` - Presets []shared.SourceLocator `json:"presets,omitempty"` -} - -type ProjectMonitoring struct { - PrometheusURL string `json:"prometheusURL,omitempty"` - GrafanaURL string `json:"grafanaURL,omitempty"` - AlertmanagerURL string `json:"alertmanagerURL,omitempty"` - PrometheusRef *kmapi.ObjectReference `json:"prometheusRef,omitempty"` - AlertmanagerRef *kmapi.ObjectReference `json:"alertmanagerRef,omitempty"` -} - -// +kubebuilder:validation:Enum=Default;System;User -type ProjectType string - -const ( - ProjectDefault ProjectType = "Default" - ProjectSystem ProjectType = "System" - ProjectUser ProjectType = "User" -) - -// +genclient -// +genclient:nonNamespaced -// +genclient:onlyVerbs=get,list -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -//+kubebuilder:object:root=true -//+kubebuilder:resource:scope=Cluster - -// Project is the Schema for the projects API -type Project struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec ProjectSpec `json:"spec,omitempty"` -} - -//+kubebuilder:object:root=true -//+k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// ProjectList contains a list of Project -type ProjectList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []Project `json:"items"` -} - -func init() { - SchemeBuilder.Register(&Project{}, &ProjectList{}) -} diff --git a/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/zz_generated.deepcopy.go b/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/zz_generated.deepcopy.go deleted file mode 100644 index c6672a102..000000000 --- a/vendor/kmodules.xyz/resource-metadata/apis/core/v1alpha1/zz_generated.deepcopy.go +++ /dev/null @@ -1,841 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright AppsCode Inc. and Contributors - -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. -*/ - -// Code generated by deepcopy-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - apiv1 "kmodules.xyz/client-go/api/v1" - shared "kmodules.xyz/resource-metadata/apis/shared" - api "kmodules.xyz/resource-metrics/api" - - v1 "k8s.io/api/core/v1" - resource "k8s.io/apimachinery/pkg/api/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - version "k8s.io/apimachinery/pkg/version" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ContainerView) DeepCopyInto(out *ContainerView) { - *out = *in - if in.Command != nil { - in, out := &in.Command, &out.Command - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Args != nil { - in, out := &in.Args, &out.Args - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Ports != nil { - in, out := &in.Ports, &out.Ports - *out = make([]v1.ContainerPort, len(*in)) - copy(*out, *in) - } - if in.EnvFrom != nil { - in, out := &in.EnvFrom, &out.EnvFrom - *out = make([]v1.EnvFromSource, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Env != nil { - in, out := &in.Env, &out.Env - *out = make([]v1.EnvVar, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - in.Resources.DeepCopyInto(&out.Resources) - if in.VolumeMounts != nil { - in, out := &in.VolumeMounts, &out.VolumeMounts - *out = make([]v1.VolumeMount, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.VolumeDevices != nil { - in, out := &in.VolumeDevices, &out.VolumeDevices - *out = make([]v1.VolumeDevice, len(*in)) - copy(*out, *in) - } - if in.LivenessProbe != nil { - in, out := &in.LivenessProbe, &out.LivenessProbe - *out = new(v1.Probe) - (*in).DeepCopyInto(*out) - } - if in.ReadinessProbe != nil { - in, out := &in.ReadinessProbe, &out.ReadinessProbe - *out = new(v1.Probe) - (*in).DeepCopyInto(*out) - } - if in.StartupProbe != nil { - in, out := &in.StartupProbe, &out.StartupProbe - *out = new(v1.Probe) - (*in).DeepCopyInto(*out) - } - if in.Lifecycle != nil { - in, out := &in.Lifecycle, &out.Lifecycle - *out = new(v1.Lifecycle) - (*in).DeepCopyInto(*out) - } - if in.SecurityContext != nil { - in, out := &in.SecurityContext, &out.SecurityContext - *out = new(v1.SecurityContext) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContainerView. -func (in *ContainerView) DeepCopy() *ContainerView { - if in == nil { - return nil - } - out := new(ContainerView) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ControlPlaneInfo) DeepCopyInto(out *ControlPlaneInfo) { - *out = *in - if in.DNSNames != nil { - in, out := &in.DNSNames, &out.DNSNames - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.EmailAddresses != nil { - in, out := &in.EmailAddresses, &out.EmailAddresses - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.IPAddresses != nil { - in, out := &in.IPAddresses, &out.IPAddresses - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.URIs != nil { - in, out := &in.URIs, &out.URIs - *out = make([]string, len(*in)) - copy(*out, *in) - } - in.NotBefore.DeepCopyInto(&out.NotBefore) - in.NotAfter.DeepCopyInto(&out.NotAfter) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControlPlaneInfo. -func (in *ControlPlaneInfo) DeepCopy() *ControlPlaneInfo { - if in == nil { - return nil - } - out := new(ControlPlaneInfo) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ExecServiceFacilitator) DeepCopyInto(out *ExecServiceFacilitator) { - *out = *in - out.Ref = in.Ref - if in.Command != nil { - in, out := &in.Command, &out.Command - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExecServiceFacilitator. -func (in *ExecServiceFacilitator) DeepCopy() *ExecServiceFacilitator { - if in == nil { - return nil - } - out := new(ExecServiceFacilitator) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *GenericResource) DeepCopyInto(out *GenericResource) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - if in.Status != nil { - in, out := &in.Status, &out.Status - *out = new(runtime.RawExtension) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GenericResource. -func (in *GenericResource) DeepCopy() *GenericResource { - if in == nil { - return nil - } - out := new(GenericResource) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *GenericResource) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *GenericResourceList) DeepCopyInto(out *GenericResourceList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]GenericResource, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GenericResourceList. -func (in *GenericResourceList) DeepCopy() *GenericResourceList { - if in == nil { - return nil - } - out := new(GenericResourceList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *GenericResourceList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *GenericResourceService) DeepCopyInto(out *GenericResourceService) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - if in.Status != nil { - in, out := &in.Status, &out.Status - *out = new(runtime.RawExtension) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GenericResourceService. -func (in *GenericResourceService) DeepCopy() *GenericResourceService { - if in == nil { - return nil - } - out := new(GenericResourceService) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *GenericResourceService) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *GenericResourceServiceFacilitator) DeepCopyInto(out *GenericResourceServiceFacilitator) { - *out = *in - if in.Resource != nil { - in, out := &in.Resource, &out.Resource - *out = new(apiv1.ResourceID) - **out = **in - } - if in.Refs != nil { - in, out := &in.Refs, &out.Refs - *out = make([]apiv1.ObjectReference, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GenericResourceServiceFacilitator. -func (in *GenericResourceServiceFacilitator) DeepCopy() *GenericResourceServiceFacilitator { - if in == nil { - return nil - } - out := new(GenericResourceServiceFacilitator) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *GenericResourceServiceFacilities) DeepCopyInto(out *GenericResourceServiceFacilities) { - *out = *in - in.Exposed.DeepCopyInto(&out.Exposed) - in.TLS.DeepCopyInto(&out.TLS) - in.Backup.DeepCopyInto(&out.Backup) - in.Monitoring.DeepCopyInto(&out.Monitoring) - if in.Exec != nil { - in, out := &in.Exec, &out.Exec - *out = make([]ExecServiceFacilitator, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GenericResourceServiceFacilities. -func (in *GenericResourceServiceFacilities) DeepCopy() *GenericResourceServiceFacilities { - if in == nil { - return nil - } - out := new(GenericResourceServiceFacilities) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *GenericResourceServiceList) DeepCopyInto(out *GenericResourceServiceList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]GenericResourceService, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GenericResourceServiceList. -func (in *GenericResourceServiceList) DeepCopy() *GenericResourceServiceList { - if in == nil { - return nil - } - out := new(GenericResourceServiceList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *GenericResourceServiceList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *GenericResourceServiceSpec) DeepCopyInto(out *GenericResourceServiceSpec) { - *out = *in - out.Cluster = in.Cluster - out.APIType = in.APIType - in.Facilities.DeepCopyInto(&out.Facilities) - out.Status = in.Status - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GenericResourceServiceSpec. -func (in *GenericResourceServiceSpec) DeepCopy() *GenericResourceServiceSpec { - if in == nil { - return nil - } - out := new(GenericResourceServiceSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *GenericResourceServiceStatus) DeepCopyInto(out *GenericResourceServiceStatus) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GenericResourceServiceStatus. -func (in *GenericResourceServiceStatus) DeepCopy() *GenericResourceServiceStatus { - if in == nil { - return nil - } - out := new(GenericResourceServiceStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *GenericResourceSpec) DeepCopyInto(out *GenericResourceSpec) { - *out = *in - out.Cluster = in.Cluster - out.APIType = in.APIType - if in.RoleReplicas != nil { - in, out := &in.RoleReplicas, &out.RoleReplicas - *out = make(api.ReplicaList, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - in.TotalResource.DeepCopyInto(&out.TotalResource) - in.AppResource.DeepCopyInto(&out.AppResource) - if in.RoleResourceLimits != nil { - in, out := &in.RoleResourceLimits, &out.RoleResourceLimits - *out = make(map[api.PodRole]v1.ResourceList, len(*in)) - for key, val := range *in { - var outVal map[v1.ResourceName]resource.Quantity - if val == nil { - (*out)[key] = nil - } else { - in, out := &val, &outVal - *out = make(v1.ResourceList, len(*in)) - for key, val := range *in { - (*out)[key] = val.DeepCopy() - } - } - (*out)[key] = outVal - } - } - if in.RoleResourceRequests != nil { - in, out := &in.RoleResourceRequests, &out.RoleResourceRequests - *out = make(map[api.PodRole]v1.ResourceList, len(*in)) - for key, val := range *in { - var outVal map[v1.ResourceName]resource.Quantity - if val == nil { - (*out)[key] = nil - } else { - in, out := &val, &outVal - *out = make(v1.ResourceList, len(*in)) - for key, val := range *in { - (*out)[key] = val.DeepCopy() - } - } - (*out)[key] = outVal - } - } - out.Status = in.Status - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GenericResourceSpec. -func (in *GenericResourceSpec) DeepCopy() *GenericResourceSpec { - if in == nil { - return nil - } - out := new(GenericResourceSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *GenericResourceStatus) DeepCopyInto(out *GenericResourceStatus) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GenericResourceStatus. -func (in *GenericResourceStatus) DeepCopy() *GenericResourceStatus { - if in == nil { - return nil - } - out := new(GenericResourceStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *KubernetesInfo) DeepCopyInto(out *KubernetesInfo) { - *out = *in - if in.Version != nil { - in, out := &in.Version, &out.Version - *out = new(version.Info) - **out = **in - } - if in.ControlPlane != nil { - in, out := &in.ControlPlane, &out.ControlPlane - *out = new(ControlPlaneInfo) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KubernetesInfo. -func (in *KubernetesInfo) DeepCopy() *KubernetesInfo { - if in == nil { - return nil - } - out := new(KubernetesInfo) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PodView) DeepCopyInto(out *PodView) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodView. -func (in *PodView) DeepCopy() *PodView { - if in == nil { - return nil - } - out := new(PodView) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *PodView) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PodViewList) DeepCopyInto(out *PodViewList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]PodView, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodViewList. -func (in *PodViewList) DeepCopy() *PodViewList { - if in == nil { - return nil - } - out := new(PodViewList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *PodViewList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PodViewSpec) DeepCopyInto(out *PodViewSpec) { - *out = *in - in.Resources.DeepCopyInto(&out.Resources) - if in.Containers != nil { - in, out := &in.Containers, &out.Containers - *out = make([]ContainerView, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodViewSpec. -func (in *PodViewSpec) DeepCopy() *PodViewSpec { - if in == nil { - return nil - } - out := new(PodViewSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Project) DeepCopyInto(out *Project) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Project. -func (in *Project) DeepCopy() *Project { - if in == nil { - return nil - } - out := new(Project) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Project) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ProjectList) DeepCopyInto(out *ProjectList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Project, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProjectList. -func (in *ProjectList) DeepCopy() *ProjectList { - if in == nil { - return nil - } - out := new(ProjectList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ProjectList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ProjectMonitoring) DeepCopyInto(out *ProjectMonitoring) { - *out = *in - if in.PrometheusRef != nil { - in, out := &in.PrometheusRef, &out.PrometheusRef - *out = new(apiv1.ObjectReference) - **out = **in - } - if in.AlertmanagerRef != nil { - in, out := &in.AlertmanagerRef, &out.AlertmanagerRef - *out = new(apiv1.ObjectReference) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProjectMonitoring. -func (in *ProjectMonitoring) DeepCopy() *ProjectMonitoring { - if in == nil { - return nil - } - out := new(ProjectMonitoring) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ProjectSpec) DeepCopyInto(out *ProjectSpec) { - *out = *in - if in.Namespaces != nil { - in, out := &in.Namespaces, &out.Namespaces - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.NamespaceSelector != nil { - in, out := &in.NamespaceSelector, &out.NamespaceSelector - *out = new(metav1.LabelSelector) - (*in).DeepCopyInto(*out) - } - if in.Monitoring != nil { - in, out := &in.Monitoring, &out.Monitoring - *out = new(ProjectMonitoring) - (*in).DeepCopyInto(*out) - } - if in.Presets != nil { - in, out := &in.Presets, &out.Presets - *out = make([]shared.SourceLocator, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProjectSpec. -func (in *ProjectSpec) DeepCopy() *ProjectSpec { - if in == nil { - return nil - } - out := new(ProjectSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ResourceSummary) DeepCopyInto(out *ResourceSummary) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResourceSummary. -func (in *ResourceSummary) DeepCopy() *ResourceSummary { - if in == nil { - return nil - } - out := new(ResourceSummary) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ResourceSummary) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ResourceSummaryList) DeepCopyInto(out *ResourceSummaryList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]ResourceSummary, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResourceSummaryList. -func (in *ResourceSummaryList) DeepCopy() *ResourceSummaryList { - if in == nil { - return nil - } - out := new(ResourceSummaryList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ResourceSummaryList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ResourceSummarySpec) DeepCopyInto(out *ResourceSummarySpec) { - *out = *in - out.Cluster = in.Cluster - out.APIType = in.APIType - in.TotalResource.DeepCopyInto(&out.TotalResource) - in.AppResource.DeepCopyInto(&out.AppResource) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResourceSummarySpec. -func (in *ResourceSummarySpec) DeepCopy() *ResourceSummarySpec { - if in == nil { - return nil - } - out := new(ResourceSummarySpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ResourceView) DeepCopyInto(out *ResourceView) { - *out = *in - if in.Limits != nil { - in, out := &in.Limits, &out.Limits - *out = make(v1.ResourceList, len(*in)) - for key, val := range *in { - (*out)[key] = val.DeepCopy() - } - } - if in.Requests != nil { - in, out := &in.Requests, &out.Requests - *out = make(v1.ResourceList, len(*in)) - for key, val := range *in { - (*out)[key] = val.DeepCopy() - } - } - if in.Usage != nil { - in, out := &in.Usage, &out.Usage - *out = make(v1.ResourceList, len(*in)) - for key, val := range *in { - (*out)[key] = val.DeepCopy() - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResourceView. -func (in *ResourceView) DeepCopy() *ResourceView { - if in == nil { - return nil - } - out := new(ResourceView) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Service) DeepCopyInto(out *Service) { - *out = *in - out.ResourceLocator = in.ResourceLocator - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Service. -func (in *Service) DeepCopy() *Service { - if in == nil { - return nil - } - out := new(Service) - in.DeepCopyInto(out) - return out -} diff --git a/vendor/kmodules.xyz/resource-metadata/apis/shared/doc.go b/vendor/kmodules.xyz/resource-metadata/apis/shared/doc.go deleted file mode 100644 index 9f088e3b3..000000000 --- a/vendor/kmodules.xyz/resource-metadata/apis/shared/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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. -*/ - -// +k8s:deepcopy-gen=package -// +k8s:openapi-gen=true -// +gencrdrefdocs:force=true -package shared // import "kmodules.xyz/resource-metadata/apis/shared" diff --git a/vendor/kmodules.xyz/resource-metadata/apis/shared/helm.go b/vendor/kmodules.xyz/resource-metadata/apis/shared/helm.go deleted file mode 100644 index e24be4b73..000000000 --- a/vendor/kmodules.xyz/resource-metadata/apis/shared/helm.go +++ /dev/null @@ -1,112 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 shared - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" -) - -type BootstrapPresets struct { - // +optional - OfflineInstaller bool `json:"offlineInstaller"` - Image ImageRegistrySpec `json:"image"` - Registry RegistryInfo `json:"registry"` - Helm HelmInfo `json:"helm"` -} - -type ImageRegistrySpec struct { - //+optional - Proxies RegistryProxies `json:"proxies"` -} - -type RegistryProxies struct { - // company/bin:1.23 - //+optional - DockerHub string `json:"dockerHub"` - // alpine, nginx etc. - //+optional - DockerLibrary string `json:"dockerLibrary"` - // ghcr.io - //+optional - GHCR string `json:"ghcr"` - // quay.io - //+optional - Quay string `json:"quay"` - // registry.k8s.io - //+optional - Kubernetes string `json:"kubernetes"` - // r.appscode.com - //+optional - AppsCode string `json:"appscode"` -} - -type RegistryInfo struct { - //+optional - Credentials map[string]string `json:"credentials"` -} - -type HelmInfo struct { - Repositories map[string]*HelmRepository `json:"repositories"` - Releases map[string]*HelmRelease `json:"releases"` -} - -type HelmRepository struct { - // URL of the Helm repository, a valid URL contains at least a protocol and - // host. - // +required - URL string `json:"url"` - - // SecretRef specifies the Secret containing authentication credentials - // for the HelmRepository. - // For HTTP/S basic auth the secret must contain 'username' and 'password' - // fields. - // For TLS the secret must contain a 'certFile' and 'keyFile', and/or - // 'caFile' fields. - // +optional - SecretName string `json:"secretName,omitempty"` - - // Interval at which to check the URL for updates. - // +kubebuilder:validation:Type=string - // +kubebuilder:validation:Pattern="^([0-9]+(\\.[0-9]+)?(ms|s|m|h))+$" - // +optional - Interval *metav1.Duration `json:"interval,omitempty"` - - // The timeout of index downloading, defaults to 60s. - // +optional - Timeout *metav1.Duration `json:"timeout,omitempty"` - - // Type of the HelmRepository. - // When this field is set to "oci", the URL field value must be prefixed with "oci://". - // +kubebuilder:validation:Enum=default;oci - // +optional - Type string `json:"type,omitempty"` - - // Provider used for authentication, can be 'aws', 'azure', 'gcp' or 'generic'. - // This field is optional, and only taken into account if the .spec.type field is set to 'oci'. - // When not specified, defaults to 'generic'. - // +kubebuilder:validation:Enum=generic;aws;azure;gcp - // +kubebuilder:default:=generic - // +optional - Provider string `json:"provider,omitempty"` -} - -type HelmRelease struct { - Enabled bool `json:"enabled"` - Version string `json:"version"` - Values *runtime.RawExtension `json:"values,omitempty"` -} diff --git a/vendor/kmodules.xyz/resource-metadata/apis/shared/helpers.go b/vendor/kmodules.xyz/resource-metadata/apis/shared/helpers.go deleted file mode 100644 index 6a8475b56..000000000 --- a/vendor/kmodules.xyz/resource-metadata/apis/shared/helpers.go +++ /dev/null @@ -1,207 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 shared - -import ( - "bytes" - "fmt" - "strings" - "sync" - "text/template" - - kmapi "kmodules.xyz/client-go/api/v1" - "kmodules.xyz/go-containerregistry/name" - - "github.com/Masterminds/sprig/v3" - "github.com/pkg/errors" -) - -const ( - GraphQueryVarSource = "src" - GraphQueryVarTargetGroup = "targetGroup" - GraphQueryVarTargetKind = "targetKind" -) - -var pool = sync.Pool{ - New: func() interface{} { - return new(bytes.Buffer) - }, -} - -func (r ResourceLocator) GraphQuery(oid kmapi.OID) (string, map[string]interface{}, error) { - if r.Query.Type == GraphQLQuery { - vars := map[string]interface{}{ - GraphQueryVarSource: string(oid), - GraphQueryVarTargetGroup: r.Ref.Group, - GraphQueryVarTargetKind: r.Ref.Kind, - } - - if r.Query.Raw != "" { - return r.Query.Raw, vars, nil - } - return fmt.Sprintf(`query Find($src: String!, $targetGroup: String!, $targetKind: String!) { - find(oid: $src) { - refs: %s(group: $targetGroup, kind: $targetKind) { - namespace - name - } - } -}`, r.Query.ByLabel), vars, nil - } else if r.Query.Type == RESTQuery { - if r.Query.Raw == "" || !strings.Contains(r.Query.Raw, "{{") { - return r.Query.Raw, nil, nil - } - - tpl, err := template.New("").Funcs(sprig.TxtFuncMap()).Parse(r.Query.Raw) - if err != nil { - return "", nil, errors.Wrap(err, "failed to parse raw query") - } - // Do nothing and continue execution. - // If printed, the result of the index operation is the string "". - // We mitigate that later. - tpl.Option("missingkey=default") - - objID, err := kmapi.ObjectIDMap(oid) - if err != nil { - return "", nil, errors.Wrapf(err, "failed to parse oid=%s", oid) - } - - buf := pool.Get().(*bytes.Buffer) - defer pool.Put(buf) - buf.Reset() - - err = tpl.Execute(buf, objID) - if err != nil { - return "", nil, errors.Wrap(err, "failed to resolve template") - } - return buf.String(), nil, nil - } - return "", nil, fmt.Errorf("unknown query type %+v, oid %s", r, oid) -} - -func (r ImageRegistrySpec) DockerHubProxy() string { - addr := r.Proxies.DockerHub - addr = strings.TrimSpace(addr) - addr = strings.TrimSuffix(addr, "/") - return addr -} - -func (r ImageRegistrySpec) DockerLibraryProxy() string { - addr := r.Proxies.DockerLibrary - if addr == "" { - addr = r.Proxies.DockerHub - } - addr = strings.TrimSpace(addr) - addr = strings.TrimSuffix(addr, "/") - return addr -} - -func (r ImageRegistrySpec) GHCRProxy() string { - addr := r.Proxies.GHCR - addr = strings.TrimSpace(addr) - addr = strings.TrimSuffix(addr, "/") - return addr -} - -func (r ImageRegistrySpec) QuayProxy() string { - addr := r.Proxies.Quay - addr = strings.TrimSpace(addr) - addr = strings.TrimSuffix(addr, "/") - return addr -} - -func (r ImageRegistrySpec) KubernetesRegistryProxy() string { - addr := r.Proxies.Kubernetes - addr = strings.TrimSpace(addr) - addr = strings.TrimSuffix(addr, "/") - return addr -} - -func (r ImageRegistrySpec) AppsCodeRegistryProxy() string { - addr := r.Proxies.AppsCode - addr = strings.TrimSpace(addr) - addr = strings.TrimSuffix(addr, "/") - return addr -} - -const defaultTag = "latest" - -func NewRef(spec ImageRegistrySpec, img string) (string, error) { - ref, err := name.ParseReference(img) - if err != nil { - return "", err - } - - // https://github.com/kmodules/go-containerregistry/blob/master/name/lib_test.go - switch ref.Registry { - case "index.docker.io": - var result string - _, bin, found := strings.Cut(ref.Repository, "library/") - if found { - addr := spec.DockerLibraryProxy() - if addr != "" { - result = addr + "/" + bin - } else { - result = bin - } - } else { - addr := spec.DockerHubProxy() - if addr != "" { - result = addr + "/" + ref.Repository - } else { - result = ref.Repository - } - } - if ref.Tag != "" && ref.Tag != defaultTag { - result += ":" + ref.Tag - } - return result, nil - case "ghcr.io": - result := spec.GHCRProxy() + "/" + ref.Repository - if ref.Tag != "" && ref.Tag != defaultTag { - result += ":" + ref.Tag - } - return result, nil - case "quay.io": - result := spec.QuayProxy() + "/" + ref.Repository - if ref.Tag != "" && ref.Tag != defaultTag { - result += ":" + ref.Tag - } - return result, nil - case "registry.k8s.io": - result := spec.KubernetesRegistryProxy() + "/" + ref.Repository - if ref.Tag != "" && ref.Tag != defaultTag { - result += ":" + ref.Tag - } - return result, nil - case "r.appscode.com": - result := spec.AppsCodeRegistryProxy() + "/" + ref.Repository - if ref.Tag != "" && ref.Tag != defaultTag { - result += ":" + ref.Tag - } - return result, nil - } - return "", fmt.Errorf("registry not support for image %s", img) -} - -func MustNewRef(spec ImageRegistrySpec, img string) string { - out, err := NewRef(spec, img) - if err != nil { - panic(err) - } - return out -} diff --git a/vendor/kmodules.xyz/resource-metadata/apis/shared/openapi_generated.go b/vendor/kmodules.xyz/resource-metadata/apis/shared/openapi_generated.go deleted file mode 100644 index 447487287..000000000 --- a/vendor/kmodules.xyz/resource-metadata/apis/shared/openapi_generated.go +++ /dev/null @@ -1,911 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright AppsCode Inc. and Contributors - -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. -*/ - -// Code generated by openapi-gen. DO NOT EDIT. - -// This file was autogenerated by openapi-gen. Do not edit it manually! - -package shared - -import ( - common "k8s.io/kube-openapi/pkg/common" - spec "k8s.io/kube-openapi/pkg/validation/spec" -) - -func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenAPIDefinition { - return map[string]common.OpenAPIDefinition{ - "kmodules.xyz/resource-metadata/apis/shared.Action": schema_kmodulesxyz_resource_metadata_apis_shared_Action(ref), - "kmodules.xyz/resource-metadata/apis/shared.ActionGroup": schema_kmodulesxyz_resource_metadata_apis_shared_ActionGroup(ref), - "kmodules.xyz/resource-metadata/apis/shared.ActionInfo": schema_kmodulesxyz_resource_metadata_apis_shared_ActionInfo(ref), - "kmodules.xyz/resource-metadata/apis/shared.ActionTemplate": schema_kmodulesxyz_resource_metadata_apis_shared_ActionTemplate(ref), - "kmodules.xyz/resource-metadata/apis/shared.ActionTemplateGroup": schema_kmodulesxyz_resource_metadata_apis_shared_ActionTemplateGroup(ref), - "kmodules.xyz/resource-metadata/apis/shared.BootstrapPresets": schema_kmodulesxyz_resource_metadata_apis_shared_BootstrapPresets(ref), - "kmodules.xyz/resource-metadata/apis/shared.Dashboard": schema_kmodulesxyz_resource_metadata_apis_shared_Dashboard(ref), - "kmodules.xyz/resource-metadata/apis/shared.DashboardVar": schema_kmodulesxyz_resource_metadata_apis_shared_DashboardVar(ref), - "kmodules.xyz/resource-metadata/apis/shared.DeploymentParameters": schema_kmodulesxyz_resource_metadata_apis_shared_DeploymentParameters(ref), - "kmodules.xyz/resource-metadata/apis/shared.HelmInfo": schema_kmodulesxyz_resource_metadata_apis_shared_HelmInfo(ref), - "kmodules.xyz/resource-metadata/apis/shared.HelmRelease": schema_kmodulesxyz_resource_metadata_apis_shared_HelmRelease(ref), - "kmodules.xyz/resource-metadata/apis/shared.HelmRepository": schema_kmodulesxyz_resource_metadata_apis_shared_HelmRepository(ref), - "kmodules.xyz/resource-metadata/apis/shared.If": schema_kmodulesxyz_resource_metadata_apis_shared_If(ref), - "kmodules.xyz/resource-metadata/apis/shared.ImageRegistrySpec": schema_kmodulesxyz_resource_metadata_apis_shared_ImageRegistrySpec(ref), - "kmodules.xyz/resource-metadata/apis/shared.RegistryInfo": schema_kmodulesxyz_resource_metadata_apis_shared_RegistryInfo(ref), - "kmodules.xyz/resource-metadata/apis/shared.RegistryProxies": schema_kmodulesxyz_resource_metadata_apis_shared_RegistryProxies(ref), - "kmodules.xyz/resource-metadata/apis/shared.ResourceLocator": schema_kmodulesxyz_resource_metadata_apis_shared_ResourceLocator(ref), - "kmodules.xyz/resource-metadata/apis/shared.ResourceQuery": schema_kmodulesxyz_resource_metadata_apis_shared_ResourceQuery(ref), - "kmodules.xyz/resource-metadata/apis/shared.SourceLocator": schema_kmodulesxyz_resource_metadata_apis_shared_SourceLocator(ref), - "kmodules.xyz/resource-metadata/apis/shared.UIParameterTemplate": schema_kmodulesxyz_resource_metadata_apis_shared_UIParameterTemplate(ref), - "kmodules.xyz/resource-metadata/apis/shared.UIParameters": schema_kmodulesxyz_resource_metadata_apis_shared_UIParameters(ref), - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_Action(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "description": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "icons": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("x-helm.dev/apimachinery/apis/shared.ImageSpec"), - }, - }, - }, - }, - }, - "operationId": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "flow": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "disabled": { - SchemaProps: spec.SchemaProps{ - Default: false, - Type: []string{"boolean"}, - Format: "", - }, - }, - "editor": { - SchemaProps: spec.SchemaProps{ - Ref: ref("x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef"), - }, - }, - }, - Required: []string{"operationId", "flow", "disabled"}, - }, - }, - Dependencies: []string{ - "x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef", "x-helm.dev/apimachinery/apis/shared.ImageSpec"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_ActionGroup(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "description": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.Action"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "kmodules.xyz/resource-metadata/apis/shared.Action"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_ActionInfo(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "description": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_ActionTemplate(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "description": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "icons": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("x-helm.dev/apimachinery/apis/shared.ImageSpec"), - }, - }, - }, - }, - }, - "operationId": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "flow": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "disabledTemplate": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "editor": { - SchemaProps: spec.SchemaProps{ - Ref: ref("x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef"), - }, - }, - "enforceQuota": { - SchemaProps: spec.SchemaProps{ - Default: false, - Type: []string{"boolean"}, - Format: "", - }, - }, - }, - Required: []string{"operationId", "flow", "enforceQuota"}, - }, - }, - Dependencies: []string{ - "x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef", "x-helm.dev/apimachinery/apis/shared.ImageSpec"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_ActionTemplateGroup(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "description": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "items": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.ActionTemplate"), - }, - }, - }, - }, - }, - }, - Required: []string{"items"}, - }, - }, - Dependencies: []string{ - "kmodules.xyz/resource-metadata/apis/shared.ActionTemplate"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_BootstrapPresets(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "offlineInstaller": { - SchemaProps: spec.SchemaProps{ - Default: false, - Type: []string{"boolean"}, - Format: "", - }, - }, - "image": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.ImageRegistrySpec"), - }, - }, - "registry": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.RegistryInfo"), - }, - }, - "helm": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.HelmInfo"), - }, - }, - }, - Required: []string{"image", "registry", "helm"}, - }, - }, - Dependencies: []string{ - "kmodules.xyz/resource-metadata/apis/shared.HelmInfo", "kmodules.xyz/resource-metadata/apis/shared.ImageRegistrySpec", "kmodules.xyz/resource-metadata/apis/shared.RegistryInfo"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_Dashboard(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "title": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "vars": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.DashboardVar"), - }, - }, - }, - }, - }, - "panels": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - "if": { - SchemaProps: spec.SchemaProps{ - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.If"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "kmodules.xyz/resource-metadata/apis/shared.DashboardVar", "kmodules.xyz/resource-metadata/apis/shared.If"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_DashboardVar(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "name": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "value": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "type": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"name", "value"}, - }, - }, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_DeploymentParameters(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "productID": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "planID": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "chart": { - SchemaProps: spec.SchemaProps{ - Ref: ref("x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_HelmInfo(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "repositories": { - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.HelmRepository"), - }, - }, - }, - }, - }, - "releases": { - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.HelmRelease"), - }, - }, - }, - }, - }, - }, - Required: []string{"repositories", "releases"}, - }, - }, - Dependencies: []string{ - "kmodules.xyz/resource-metadata/apis/shared.HelmRelease", "kmodules.xyz/resource-metadata/apis/shared.HelmRepository"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_HelmRelease(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "enabled": { - SchemaProps: spec.SchemaProps{ - Default: false, - Type: []string{"boolean"}, - Format: "", - }, - }, - "version": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "values": { - SchemaProps: spec.SchemaProps{ - Ref: ref("k8s.io/apimachinery/pkg/runtime.RawExtension"), - }, - }, - }, - Required: []string{"enabled", "version"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/runtime.RawExtension"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_HelmRepository(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "url": { - SchemaProps: spec.SchemaProps{ - Description: "URL of the Helm repository, a valid URL contains at least a protocol and host.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "secretName": { - SchemaProps: spec.SchemaProps{ - Description: "SecretRef specifies the Secret containing authentication credentials for the HelmRepository. For HTTP/S basic auth the secret must contain 'username' and 'password' fields. For TLS the secret must contain a 'certFile' and 'keyFile', and/or 'caFile' fields.", - Type: []string{"string"}, - Format: "", - }, - }, - "interval": { - SchemaProps: spec.SchemaProps{ - Description: "Interval at which to check the URL for updates.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Duration"), - }, - }, - "timeout": { - SchemaProps: spec.SchemaProps{ - Description: "The timeout of index downloading, defaults to 60s.", - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Duration"), - }, - }, - "type": { - SchemaProps: spec.SchemaProps{ - Description: "Type of the HelmRepository. When this field is set to \"oci\", the URL field value must be prefixed with \"oci://\".", - Type: []string{"string"}, - Format: "", - }, - }, - "provider": { - SchemaProps: spec.SchemaProps{ - Description: "Provider used for authentication, can be 'aws', 'azure', 'gcp' or 'generic'. This field is optional, and only taken into account if the .spec.type field is set to 'oci'. When not specified, defaults to 'generic'.", - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"url"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.Duration"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_If(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "condition": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "connected": { - SchemaProps: spec.SchemaProps{ - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.ResourceLocator"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "kmodules.xyz/resource-metadata/apis/shared.ResourceLocator"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_ImageRegistrySpec(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "proxies": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.RegistryProxies"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "kmodules.xyz/resource-metadata/apis/shared.RegistryProxies"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_RegistryInfo(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "credentials": { - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - }, - }, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_RegistryProxies(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "dockerHub": { - SchemaProps: spec.SchemaProps{ - Description: "company/bin:1.23", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "dockerLibrary": { - SchemaProps: spec.SchemaProps{ - Description: "alpine, nginx etc.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "ghcr": { - SchemaProps: spec.SchemaProps{ - Description: "ghcr.io", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "quay": { - SchemaProps: spec.SchemaProps{ - Description: "quay.io", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "kubernetes": { - SchemaProps: spec.SchemaProps{ - Description: "registry.k8s.io", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "appscode": { - SchemaProps: spec.SchemaProps{ - Description: "r.appscode.com", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_ResourceLocator(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "ref": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.GroupKind"), - }, - }, - "query": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.ResourceQuery"), - }, - }, - }, - Required: []string{"ref", "query"}, - }, - }, - Dependencies: []string{ - "k8s.io/apimachinery/pkg/apis/meta/v1.GroupKind", "kmodules.xyz/resource-metadata/apis/shared.ResourceQuery"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_ResourceQuery(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "type": { - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "byLabel": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - "raw": { - SchemaProps: spec.SchemaProps{ - Type: []string{"string"}, - Format: "", - }, - }, - }, - Required: []string{"type"}, - }, - }, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_SourceLocator(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "resource": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/client-go/api/v1.ResourceID"), - }, - }, - "ref": { - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("kmodules.xyz/client-go/api/v1.ObjectReference"), - }, - }, - }, - }, - }, - Dependencies: []string{ - "kmodules.xyz/client-go/api/v1.ObjectReference", "kmodules.xyz/client-go/api/v1.ResourceID"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_UIParameterTemplate(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "options": { - SchemaProps: spec.SchemaProps{ - Ref: ref("x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef"), - }, - }, - "editor": { - SchemaProps: spec.SchemaProps{ - Ref: ref("x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef"), - }, - }, - "enforceQuota": { - SchemaProps: spec.SchemaProps{ - Default: false, - Type: []string{"boolean"}, - Format: "", - }, - }, - "actions": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.ActionTemplateGroup"), - }, - }, - }, - }, - }, - "instanceLabelPaths": { - SchemaProps: spec.SchemaProps{ - Description: "app.kubernetes.io/instance label must be updated at these paths when refilling metadata", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"enforceQuota"}, - }, - }, - Dependencies: []string{ - "kmodules.xyz/resource-metadata/apis/shared.ActionTemplateGroup", "x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef"}, - } -} - -func schema_kmodulesxyz_resource_metadata_apis_shared_UIParameters(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "options": { - SchemaProps: spec.SchemaProps{ - Ref: ref("x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef"), - }, - }, - "editor": { - SchemaProps: spec.SchemaProps{ - Ref: ref("x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef"), - }, - }, - "actions": { - SchemaProps: spec.SchemaProps{ - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Ref: ref("kmodules.xyz/resource-metadata/apis/shared.ActionGroup"), - }, - }, - }, - }, - }, - "instanceLabelPaths": { - SchemaProps: spec.SchemaProps{ - Description: "app.kubernetes.io/instance label must be updated at these paths when refilling metadata", - Type: []string{"array"}, - Items: &spec.SchemaOrArray{ - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - }, - }, - }, - }, - }, - }, - Dependencies: []string{ - "kmodules.xyz/resource-metadata/apis/shared.ActionGroup", "x-helm.dev/apimachinery/apis/releases/v1alpha1.ChartSourceRef"}, - } -} diff --git a/vendor/kmodules.xyz/resource-metadata/apis/shared/types.go b/vendor/kmodules.xyz/resource-metadata/apis/shared/types.go deleted file mode 100644 index 930c6bf4b..000000000 --- a/vendor/kmodules.xyz/resource-metadata/apis/shared/types.go +++ /dev/null @@ -1,146 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 shared - -import ( - kmapi "kmodules.xyz/client-go/api/v1" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - releasesapi "x-helm.dev/apimachinery/apis/releases/v1alpha1" - helmshared "x-helm.dev/apimachinery/apis/shared" -) - -type SourceLocator struct { - // +optional - Resource kmapi.ResourceID `json:"resource"` - // +optional - Ref kmapi.ObjectReference `json:"ref"` -} - -type DeploymentParameters struct { - ProductID string `json:"productID,omitempty"` - PlanID string `json:"planID,omitempty"` - Chart *releasesapi.ChartSourceRef `json:"chart,omitempty"` -} - -type ResourceLocator struct { - Ref metav1.GroupKind `json:"ref"` - Query ResourceQuery `json:"query"` -} - -// +kubebuilder:validation:Enum=REST;GraphQL -type QueryType string - -const ( - RESTQuery QueryType = "REST" - GraphQLQuery QueryType = "GraphQL" -) - -type ResourceQuery struct { - Type QueryType `json:"type"` - ByLabel kmapi.EdgeLabel `json:"byLabel,omitempty"` - Raw string `json:"raw,omitempty"` -} - -type UIParameters struct { - Options *releasesapi.ChartSourceRef `json:"options,omitempty"` - Editor *releasesapi.ChartSourceRef `json:"editor,omitempty"` - // +optional - Actions []*ActionGroup `json:"actions,omitempty"` - // app.kubernetes.io/instance label must be updated at these paths when refilling metadata - // +optional - InstanceLabelPaths []string `json:"instanceLabelPaths,omitempty"` -} - -type UIParameterTemplate struct { - Options *releasesapi.ChartSourceRef `json:"options,omitempty"` - Editor *releasesapi.ChartSourceRef `json:"editor,omitempty"` - EnforceQuota bool `json:"enforceQuota"` - // +optional - Actions []*ActionTemplateGroup `json:"actions,omitempty"` - // app.kubernetes.io/instance label must be updated at these paths when refilling metadata - // +optional - InstanceLabelPaths []string `json:"instanceLabelPaths,omitempty"` -} - -type ActionGroup struct { - ActionInfo `json:",inline,omitempty"` - Items []Action `json:"items"` -} - -type Action struct { - ActionInfo `json:",inline,omitempty"` - // +optional - Icons []helmshared.ImageSpec `json:"icons,omitempty"` - OperationID string `json:"operationId"` - Flow string `json:"flow"` - Disabled bool `json:"disabled"` - Editor *releasesapi.ChartSourceRef `json:"editor,omitempty"` -} - -// +kubebuilder:validation:Enum=Source;Target -type DashboardVarType string - -const ( - DashboardVarTypeSource DashboardVarType = "Source" - DashboardVarTypeTarget DashboardVarType = "Target" -) - -type DashboardVar struct { - Name string `json:"name"` - Value string `json:"value"` - // +optional - // +kubebuilder:default:=Source - Type DashboardVarType `json:"type,omitempty"` -} - -type Dashboard struct { - // +optional - Title string `json:"title,omitempty"` - // +optional - Vars []DashboardVar `json:"vars,omitempty"` - // +optional - Panels []string `json:"panels,omitempty"` - // +optional - If *If `json:"if,omitempty"` -} - -type If struct { - Condition string `json:"condition,omitempty"` - Connected *ResourceLocator `json:"connected,omitempty"` -} - -type ActionTemplateGroup struct { - ActionInfo `json:",inline,omitempty"` - Items []ActionTemplate `json:"items"` -} - -type ActionTemplate struct { - ActionInfo `json:",inline,omitempty"` - // +optional - Icons []helmshared.ImageSpec `json:"icons,omitempty"` - OperationID string `json:"operationId"` - Flow string `json:"flow"` - DisabledTemplate string `json:"disabledTemplate,omitempty"` - Editor *releasesapi.ChartSourceRef `json:"editor,omitempty"` - EnforceQuota bool `json:"enforceQuota"` -} - -type ActionInfo struct { - Name string `json:"name,omitempty"` - Description string `json:"description,omitempty"` -} diff --git a/vendor/kmodules.xyz/resource-metadata/apis/shared/zz_generated.deepcopy.go b/vendor/kmodules.xyz/resource-metadata/apis/shared/zz_generated.deepcopy.go deleted file mode 100644 index 39939a078..000000000 --- a/vendor/kmodules.xyz/resource-metadata/apis/shared/zz_generated.deepcopy.go +++ /dev/null @@ -1,540 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright AppsCode Inc. and Contributors - -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. -*/ - -// Code generated by deepcopy-gen. DO NOT EDIT. - -package shared - -import ( - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - v1alpha1 "x-helm.dev/apimachinery/apis/releases/v1alpha1" - apisshared "x-helm.dev/apimachinery/apis/shared" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Action) DeepCopyInto(out *Action) { - *out = *in - out.ActionInfo = in.ActionInfo - if in.Icons != nil { - in, out := &in.Icons, &out.Icons - *out = make([]apisshared.ImageSpec, len(*in)) - copy(*out, *in) - } - if in.Editor != nil { - in, out := &in.Editor, &out.Editor - *out = new(v1alpha1.ChartSourceRef) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Action. -func (in *Action) DeepCopy() *Action { - if in == nil { - return nil - } - out := new(Action) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ActionGroup) DeepCopyInto(out *ActionGroup) { - *out = *in - out.ActionInfo = in.ActionInfo - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Action, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ActionGroup. -func (in *ActionGroup) DeepCopy() *ActionGroup { - if in == nil { - return nil - } - out := new(ActionGroup) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ActionInfo) DeepCopyInto(out *ActionInfo) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ActionInfo. -func (in *ActionInfo) DeepCopy() *ActionInfo { - if in == nil { - return nil - } - out := new(ActionInfo) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ActionTemplate) DeepCopyInto(out *ActionTemplate) { - *out = *in - out.ActionInfo = in.ActionInfo - if in.Icons != nil { - in, out := &in.Icons, &out.Icons - *out = make([]apisshared.ImageSpec, len(*in)) - copy(*out, *in) - } - if in.Editor != nil { - in, out := &in.Editor, &out.Editor - *out = new(v1alpha1.ChartSourceRef) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ActionTemplate. -func (in *ActionTemplate) DeepCopy() *ActionTemplate { - if in == nil { - return nil - } - out := new(ActionTemplate) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ActionTemplateGroup) DeepCopyInto(out *ActionTemplateGroup) { - *out = *in - out.ActionInfo = in.ActionInfo - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]ActionTemplate, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ActionTemplateGroup. -func (in *ActionTemplateGroup) DeepCopy() *ActionTemplateGroup { - if in == nil { - return nil - } - out := new(ActionTemplateGroup) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BootstrapPresets) DeepCopyInto(out *BootstrapPresets) { - *out = *in - out.Image = in.Image - in.Registry.DeepCopyInto(&out.Registry) - in.Helm.DeepCopyInto(&out.Helm) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BootstrapPresets. -func (in *BootstrapPresets) DeepCopy() *BootstrapPresets { - if in == nil { - return nil - } - out := new(BootstrapPresets) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Dashboard) DeepCopyInto(out *Dashboard) { - *out = *in - if in.Vars != nil { - in, out := &in.Vars, &out.Vars - *out = make([]DashboardVar, len(*in)) - copy(*out, *in) - } - if in.Panels != nil { - in, out := &in.Panels, &out.Panels - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.If != nil { - in, out := &in.If, &out.If - *out = new(If) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Dashboard. -func (in *Dashboard) DeepCopy() *Dashboard { - if in == nil { - return nil - } - out := new(Dashboard) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *DashboardVar) DeepCopyInto(out *DashboardVar) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DashboardVar. -func (in *DashboardVar) DeepCopy() *DashboardVar { - if in == nil { - return nil - } - out := new(DashboardVar) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *DeploymentParameters) DeepCopyInto(out *DeploymentParameters) { - *out = *in - if in.Chart != nil { - in, out := &in.Chart, &out.Chart - *out = new(v1alpha1.ChartSourceRef) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DeploymentParameters. -func (in *DeploymentParameters) DeepCopy() *DeploymentParameters { - if in == nil { - return nil - } - out := new(DeploymentParameters) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *HelmInfo) DeepCopyInto(out *HelmInfo) { - *out = *in - if in.Repositories != nil { - in, out := &in.Repositories, &out.Repositories - *out = make(map[string]*HelmRepository, len(*in)) - for key, val := range *in { - var outVal *HelmRepository - if val == nil { - (*out)[key] = nil - } else { - in, out := &val, &outVal - *out = new(HelmRepository) - (*in).DeepCopyInto(*out) - } - (*out)[key] = outVal - } - } - if in.Releases != nil { - in, out := &in.Releases, &out.Releases - *out = make(map[string]*HelmRelease, len(*in)) - for key, val := range *in { - var outVal *HelmRelease - if val == nil { - (*out)[key] = nil - } else { - in, out := &val, &outVal - *out = new(HelmRelease) - (*in).DeepCopyInto(*out) - } - (*out)[key] = outVal - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HelmInfo. -func (in *HelmInfo) DeepCopy() *HelmInfo { - if in == nil { - return nil - } - out := new(HelmInfo) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *HelmRelease) DeepCopyInto(out *HelmRelease) { - *out = *in - if in.Values != nil { - in, out := &in.Values, &out.Values - *out = new(runtime.RawExtension) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HelmRelease. -func (in *HelmRelease) DeepCopy() *HelmRelease { - if in == nil { - return nil - } - out := new(HelmRelease) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *HelmRepository) DeepCopyInto(out *HelmRepository) { - *out = *in - if in.Interval != nil { - in, out := &in.Interval, &out.Interval - *out = new(v1.Duration) - **out = **in - } - if in.Timeout != nil { - in, out := &in.Timeout, &out.Timeout - *out = new(v1.Duration) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HelmRepository. -func (in *HelmRepository) DeepCopy() *HelmRepository { - if in == nil { - return nil - } - out := new(HelmRepository) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *If) DeepCopyInto(out *If) { - *out = *in - if in.Connected != nil { - in, out := &in.Connected, &out.Connected - *out = new(ResourceLocator) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new If. -func (in *If) DeepCopy() *If { - if in == nil { - return nil - } - out := new(If) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ImageRegistrySpec) DeepCopyInto(out *ImageRegistrySpec) { - *out = *in - out.Proxies = in.Proxies - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImageRegistrySpec. -func (in *ImageRegistrySpec) DeepCopy() *ImageRegistrySpec { - if in == nil { - return nil - } - out := new(ImageRegistrySpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *RegistryInfo) DeepCopyInto(out *RegistryInfo) { - *out = *in - if in.Credentials != nil { - in, out := &in.Credentials, &out.Credentials - *out = make(map[string]string, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RegistryInfo. -func (in *RegistryInfo) DeepCopy() *RegistryInfo { - if in == nil { - return nil - } - out := new(RegistryInfo) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *RegistryProxies) DeepCopyInto(out *RegistryProxies) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RegistryProxies. -func (in *RegistryProxies) DeepCopy() *RegistryProxies { - if in == nil { - return nil - } - out := new(RegistryProxies) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ResourceLocator) DeepCopyInto(out *ResourceLocator) { - *out = *in - out.Ref = in.Ref - out.Query = in.Query - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResourceLocator. -func (in *ResourceLocator) DeepCopy() *ResourceLocator { - if in == nil { - return nil - } - out := new(ResourceLocator) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ResourceQuery) DeepCopyInto(out *ResourceQuery) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResourceQuery. -func (in *ResourceQuery) DeepCopy() *ResourceQuery { - if in == nil { - return nil - } - out := new(ResourceQuery) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SourceLocator) DeepCopyInto(out *SourceLocator) { - *out = *in - out.Resource = in.Resource - out.Ref = in.Ref - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SourceLocator. -func (in *SourceLocator) DeepCopy() *SourceLocator { - if in == nil { - return nil - } - out := new(SourceLocator) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *UIParameterTemplate) DeepCopyInto(out *UIParameterTemplate) { - *out = *in - if in.Options != nil { - in, out := &in.Options, &out.Options - *out = new(v1alpha1.ChartSourceRef) - **out = **in - } - if in.Editor != nil { - in, out := &in.Editor, &out.Editor - *out = new(v1alpha1.ChartSourceRef) - **out = **in - } - if in.Actions != nil { - in, out := &in.Actions, &out.Actions - *out = make([]*ActionTemplateGroup, len(*in)) - for i := range *in { - if (*in)[i] != nil { - in, out := &(*in)[i], &(*out)[i] - *out = new(ActionTemplateGroup) - (*in).DeepCopyInto(*out) - } - } - } - if in.InstanceLabelPaths != nil { - in, out := &in.InstanceLabelPaths, &out.InstanceLabelPaths - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new UIParameterTemplate. -func (in *UIParameterTemplate) DeepCopy() *UIParameterTemplate { - if in == nil { - return nil - } - out := new(UIParameterTemplate) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *UIParameters) DeepCopyInto(out *UIParameters) { - *out = *in - if in.Options != nil { - in, out := &in.Options, &out.Options - *out = new(v1alpha1.ChartSourceRef) - **out = **in - } - if in.Editor != nil { - in, out := &in.Editor, &out.Editor - *out = new(v1alpha1.ChartSourceRef) - **out = **in - } - if in.Actions != nil { - in, out := &in.Actions, &out.Actions - *out = make([]*ActionGroup, len(*in)) - for i := range *in { - if (*in)[i] != nil { - in, out := &(*in)[i], &(*out)[i] - *out = new(ActionGroup) - (*in).DeepCopyInto(*out) - } - } - } - if in.InstanceLabelPaths != nil { - in, out := &in.InstanceLabelPaths, &out.InstanceLabelPaths - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new UIParameters. -func (in *UIParameters) DeepCopy() *UIParameters { - if in == nil { - return nil - } - out := new(UIParameters) - in.DeepCopyInto(out) - return out -} diff --git a/vendor/kmodules.xyz/resource-metrics/.gitignore b/vendor/kmodules.xyz/resource-metrics/.gitignore deleted file mode 100644 index 9aab71958..000000000 --- a/vendor/kmodules.xyz/resource-metrics/.gitignore +++ /dev/null @@ -1,35 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof -.idea/ -dist/ -**/junit.xml -**/.env -.vscode/ -coverage.txt - -/bin -/.go - -apiserver.local.config/** diff --git a/vendor/kmodules.xyz/resource-metrics/CONTRIBUTING.md b/vendor/kmodules.xyz/resource-metrics/CONTRIBUTING.md deleted file mode 100644 index 6254de193..000000000 --- a/vendor/kmodules.xyz/resource-metrics/CONTRIBUTING.md +++ /dev/null @@ -1,37 +0,0 @@ -# How to Contribute - -AppsCode projects are [Apache 2.0 licensed](LICENSE) and accept contributions via -GitHub pull requests. This document outlines some of the conventions on -development workflow, commit message formatting, contact points and other -resources to make it easier to get your contribution accepted. - -## Certificate of Origin - -By contributing to this project you agree to the Developer Certificate of -Origin (DCO). This document was created by the Linux Kernel community and is a -simple statement that you, as a contributor, have the legal right to make the -contribution. See the [DCO](DCO) file for details. - -## Developer Guide -If you find something undocumented or incorrect along the way, -please feel free to send a Pull Request. - -## Getting Help -If you have a question about Kutil or having problem using it, you can contact us on our public Slack channel. Follow [this link](https://slack.appscode.com) to get invitation to our Slack channel. - -## Bugs/Feature request -If you have found a bug with Kutil or want to request for new features, please [file an issue](https://github.com/kmodules/resource-metrics/issues/new). - -## Contribution Flow -If you fix a bug or developed a new feature, feel free to submit a PR. In either case, please file a [Github issue]((https://github.com/kmodules/resource-metrics/issues/new)) first, so that we can have a discussion on it. This is a rough outline of what a contributor's workflow looks like: - -- Create a topic branch from where you want to base your work (usually master). -- Make commits of logical units. -- Push your changes to a topic branch in your fork of the repository. -- Make sure the tests pass, and add any new tests as appropriate. -- Submit a pull request to the original repository. - -Thanks for your contributions! - -## Spread the word -If you have written blog post or tutorial on Kutil, please share it with us on [Twitter](https://twitter.com/AppsCodeHQ) or [Slack](https://slack.appscode.com). diff --git a/vendor/kmodules.xyz/resource-metrics/DCO b/vendor/kmodules.xyz/resource-metrics/DCO deleted file mode 100644 index 716561d5d..000000000 --- a/vendor/kmodules.xyz/resource-metrics/DCO +++ /dev/null @@ -1,36 +0,0 @@ -Developer Certificate of Origin -Version 1.1 - -Copyright (C) 2004, 2006 The Linux Foundation and its contributors. -660 York Street, Suite 102, -San Francisco, CA 94110 USA - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - - -Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -(a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -(b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -(c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -(d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. diff --git a/vendor/kmodules.xyz/resource-metrics/LICENSE b/vendor/kmodules.xyz/resource-metrics/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/vendor/kmodules.xyz/resource-metrics/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - 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 "[]" - 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 - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/kmodules.xyz/resource-metrics/Makefile b/vendor/kmodules.xyz/resource-metrics/Makefile deleted file mode 100644 index 4c28c49a3..000000000 --- a/vendor/kmodules.xyz/resource-metrics/Makefile +++ /dev/null @@ -1,300 +0,0 @@ -# Copyright AppsCode Inc. and Contributors -# -# 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. - -SHELL=/bin/bash -o pipefail - -GO_PKG := kmodules.xyz -REPO := $(notdir $(shell pwd)) -BIN := resource-calculator -COMPRESS ?= no - -# This version-strategy uses git tags to set the version string -git_branch := $(shell git rev-parse --abbrev-ref HEAD) -git_tag := $(shell git describe --exact-match --abbrev=0 2>/dev/null || echo "") -commit_hash := $(shell git rev-parse --verify HEAD) -commit_timestamp := $(shell date --date="@$$(git show -s --format=%ct)" --utc +%FT%T) - -VERSION := $(shell git describe --tags --always --dirty) -version_strategy := commit_hash -ifdef git_tag - VERSION := $(git_tag) - version_strategy := tag -else - ifeq (,$(findstring $(git_branch),master HEAD)) - ifneq (,$(patsubst release-%,,$(git_branch))) - VERSION := $(git_branch) - version_strategy := branch - endif - endif -endif - -### -### These variables should not need tweaking. -### - -SRC_PKGS := api apps batch core kubedb.com kubevault.com ops.kubedb.com -SRC_DIRS := $(SRC_PKGS) *.go # directories which hold app source (not vendored) - -DOCKER_PLATFORMS := linux/amd64 linux/arm linux/arm64 -BIN_PLATFORMS := $(DOCKER_PLATFORMS) windows/amd64 darwin/amd64 darwin/arm64 - -# Used internally. Users should pass GOOS and/or GOARCH. -OS := $(if $(GOOS),$(GOOS),$(shell go env GOOS)) -ARCH := $(if $(GOARCH),$(GOARCH),$(shell go env GOARCH)) - -GO_VERSION ?= 1.21 -BUILD_IMAGE ?= ghcr.io/appscode/golang-dev:$(GO_VERSION) - -OUTBIN = bin/$(BIN)-$(OS)-$(ARCH) -ifeq ($(OS),windows) - OUTBIN := bin/$(BIN)-$(OS)-$(ARCH).exe - BIN := $(BIN).exe -endif - -# Directories that we need created to build/test. -BUILD_DIRS := bin/$(OS)_$(ARCH) \ - .go/bin/$(OS)_$(ARCH) \ - .go/cache \ - hack/config \ - $(HOME)/.credentials \ - $(HOME)/.kube \ - $(HOME)/.minikube - -DOCKER_REPO_ROOT := /go/src/$(GO_PKG)/$(REPO) - -# If you want to build all binaries, see the 'all-build' rule. -# If you want to build all containers, see the 'all-container' rule. -# If you want to build AND push all containers, see the 'all-push' rule. -all: fmt build - -# For the following OS/ARCH expansions, we transform OS/ARCH into OS_ARCH -# because make pattern rules don't match with embedded '/' characters. - -build-%: - @$(MAKE) build \ - --no-print-directory \ - GOOS=$(firstword $(subst _, ,$*)) \ - GOARCH=$(lastword $(subst _, ,$*)) - -all-build: $(addprefix build-, $(subst /,_, $(BIN_PLATFORMS))) -ifeq ($(COMPRESS),yes) - @cd bin; \ - sha256sum $(patsubst $(BIN)-windows-%.tar.gz,$(BIN)-windows-%.zip, $(addsuffix .tar.gz, $(addprefix $(BIN)-, $(subst /,-, $(BIN_PLATFORMS))))) > $(BIN)-checksums.txt -endif - -version: - @echo ::set-output name=version::$(VERSION) - @echo ::set-output name=version_strategy::$(version_strategy) - @echo ::set-output name=git_tag::$(git_tag) - @echo ::set-output name=git_branch::$(git_branch) - @echo ::set-output name=commit_hash::$(commit_hash) - @echo ::set-output name=commit_timestamp::$(commit_timestamp) - -gen: - @true - -fmt: $(BUILD_DIRS) - @docker run \ - -i \ - --rm \ - -u $$(id -u):$$(id -g) \ - -v $$(pwd):/src \ - -w /src \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin/$(OS)_$(ARCH) \ - -v $$(pwd)/.go/cache:/.cache \ - --env HTTP_PROXY=$(HTTP_PROXY) \ - --env HTTPS_PROXY=$(HTTPS_PROXY) \ - $(BUILD_IMAGE) \ - /bin/bash -c " \ - REPO_PKG=$(GO_PKG) \ - ./hack/fmt.sh $(SRC_DIRS) \ - " - -build: $(OUTBIN) - -# The following structure defeats Go's (intentional) behavior to always touch -# result files, even if they have not changed. This will still run `go` but -# will not trigger further work if nothing has actually changed. - -$(OUTBIN): .go/$(OUTBIN).stamp - @true - -# This will build the binary under ./.go and update the real binary iff needed. -.PHONY: .go/$(OUTBIN).stamp -.go/$(OUTBIN).stamp: $(BUILD_DIRS) - @echo "making $(OUTBIN)" - @docker run \ - -i \ - --rm \ - -u $$(id -u):$$(id -g) \ - -v $$(pwd):/src \ - -w /src \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin/$(OS)_$(ARCH) \ - -v $$(pwd)/.go/cache:/.cache \ - --env HTTP_PROXY=$(HTTP_PROXY) \ - --env HTTPS_PROXY=$(HTTPS_PROXY) \ - $(BUILD_IMAGE) \ - /bin/bash -c " \ - ARCH=$(ARCH) \ - OS=$(OS) \ - VERSION=$(VERSION) \ - version_strategy=$(version_strategy) \ - git_branch=$(git_branch) \ - git_tag=$(git_tag) \ - commit_hash=$(commit_hash) \ - commit_timestamp=$(commit_timestamp) \ - ./hack/build.sh \ - " - @if ! cmp -s .go/bin/$(OS)_$(ARCH)/$(BIN) $(OUTBIN); then \ - mv .go/bin/$(OS)_$(ARCH)/$(BIN) $(OUTBIN); \ - date >$@; \ - fi -ifeq ($(COMPRESS),yes) -ifeq ($(OS),windows) - @echo "compressing $(OUTBIN)"; \ - cd bin; \ - zip -j $(subst .exe,,$(BIN))-$(OS)-$(ARCH).zip $(subst .exe,,$(BIN))-$(OS)-$(ARCH).exe ../LICENSE -else - @echo "compressing $(OUTBIN)"; \ - cd bin; \ - tar -czvf $(BIN)-$(OS)-$(ARCH).tar.gz $(BIN)-$(OS)-$(ARCH) ../LICENSE -endif -endif - @echo - -.PHONY: test -test: unit-tests - -unit-tests: $(BUILD_DIRS) - @docker run \ - -i \ - --rm \ - -u $$(id -u):$$(id -g) \ - -v $$(pwd):/src \ - -w /src \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin/$(OS)_$(ARCH) \ - -v $$(pwd)/.go/cache:/.cache \ - --env HTTP_PROXY=$(HTTP_PROXY) \ - --env HTTPS_PROXY=$(HTTPS_PROXY) \ - $(BUILD_IMAGE) \ - /bin/bash -c " \ - ARCH=$(ARCH) \ - OS=$(OS) \ - VERSION=$(VERSION) \ - ./hack/test.sh $(SRC_PKGS) \ - " - -ADDTL_LINTERS := goconst,gofmt,goimports,unparam - -.PHONY: lint -lint: $(BUILD_DIRS) - @echo "running linter" - @docker run \ - -i \ - --rm \ - -u $$(id -u):$$(id -g) \ - -v $$(pwd):/src \ - -w /src \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin \ - -v $$(pwd)/.go/bin/$(OS)_$(ARCH):/go/bin/$(OS)_$(ARCH) \ - -v $$(pwd)/.go/cache:/.cache \ - --env HTTP_PROXY=$(HTTP_PROXY) \ - --env HTTPS_PROXY=$(HTTPS_PROXY) \ - --env GO111MODULE=on \ - --env GOFLAGS="-mod=vendor" \ - $(BUILD_IMAGE) \ - golangci-lint run --enable $(ADDTL_LINTERS) --timeout=10m --skip-files="generated.*\.go$\" --skip-dirs-use-default - -$(BUILD_DIRS): - @mkdir -p $@ - -.PHONY: dev -dev: gen fmt build - -.PHONY: verify -verify: verify-gen verify-modules - -.PHONY: verify-modules -verify-modules: - GO111MODULE=on go mod tidy - GO111MODULE=on go mod vendor - @if !(git diff --exit-code HEAD); then \ - echo "go module files are out of date"; exit 1; \ - fi - -.PHONY: verify-gen -verify-gen: gen fmt - @if !(git diff --exit-code HEAD); then \ - echo "files are out of date, run make gen fmt"; exit 1; \ - fi - -.PHONY: add-license -add-license: - @echo "Adding license header" - @docker run --rm \ - -u $$(id -u):$$(id -g) \ - -v /tmp:/.cache \ - -v $$(pwd):$(DOCKER_REPO_ROOT) \ - -w $(DOCKER_REPO_ROOT) \ - --env HTTP_PROXY=$(HTTP_PROXY) \ - --env HTTPS_PROXY=$(HTTPS_PROXY) \ - $(BUILD_IMAGE) \ - ltag -t "./hack/license" --excludes "vendor contrib" -v - -.PHONY: check-license -check-license: - @echo "Checking files for license header" - @docker run --rm \ - -u $$(id -u):$$(id -g) \ - -v /tmp:/.cache \ - -v $$(pwd):$(DOCKER_REPO_ROOT) \ - -w $(DOCKER_REPO_ROOT) \ - --env HTTP_PROXY=$(HTTP_PROXY) \ - --env HTTPS_PROXY=$(HTTPS_PROXY) \ - $(BUILD_IMAGE) \ - ltag -t "./hack/license" --excludes "vendor contrib" --check -v - -.PHONY: ci -ci: verify check-license lint build unit-tests #cover - -.PHONY: qa -qa: - @if [ "$$APPSCODE_ENV" = "prod" ]; then \ - echo "Nothing to do in prod env. Are you trying to 'release' binaries to prod?"; \ - exit 1; \ - fi - @if [ "$(version_strategy)" = "tag" ]; then \ - echo "Are you trying to 'release' binaries to prod?"; \ - exit 1; \ - fi - @$(MAKE) clean all-build --no-print-directory - -.PHONY: release -release: - @if [ "$$APPSCODE_ENV" != "prod" ]; then \ - echo "'release' only works in PROD env."; \ - exit 1; \ - fi - @if [ "$(version_strategy)" != "tag" ]; then \ - echo "apply tag to release binaries and/or docker images."; \ - exit 1; \ - fi - @$(MAKE) clean all-build --no-print-directory - -.PHONY: clean -clean: - rm -rf .go bin diff --git a/vendor/kmodules.xyz/resource-metrics/README.md b/vendor/kmodules.xyz/resource-metrics/README.md deleted file mode 100644 index b26bf3bfd..000000000 --- a/vendor/kmodules.xyz/resource-metrics/README.md +++ /dev/null @@ -1,8 +0,0 @@ -[![PkgGoDev](https://pkg.go.dev/badge/kmodules.xyz/resource-metrics)](https://pkg.go.dev/kmodules.xyz/resource-metrics) -[![Build Status](https://github.com/kmodules/resource-metrics/workflows/CI/badge.svg)](https://github.com/kmodules/resource-metrics/actions?workflow=CI) -[![Slack](https://shields.io/badge/Join_Slack-salck?color=4A154B&logo=slack)](https://slack.appscode.com) -[![Twitter](https://img.shields.io/twitter/follow/appscodehq.svg?style=social&logo=twitter&label=Follow)](https://twitter.com/intent/follow?screen_name=AppsCodeHQ) - -# resource-metrics - -Kubernetes resource metrics calculator diff --git a/vendor/kmodules.xyz/resource-metrics/api/constants.go b/vendor/kmodules.xyz/resource-metrics/api/constants.go deleted file mode 100644 index 65a5ebf9d..000000000 --- a/vendor/kmodules.xyz/resource-metrics/api/constants.go +++ /dev/null @@ -1,35 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 api - -type PodRole string - -const ( - PodRoleDefault PodRole = "" - PodRoleInit PodRole = "init" - PodRoleRouter PodRole = "router" - PodRoleExporter PodRole = "exporter" - PodRoleTotalShard PodRole = "total_shard" - PodRoleShard PodRole = "shard" - PodRoleReplicasPerShard PodRole = "replicas_per_shard" - PodRoleConfigServer PodRole = "config_server" - PodRoleMongos PodRole = "mongos" - PodRoleAggregator PodRole = "aggregator" - PodRoleLeaf PodRole = "leaf" -) - -type ReplicaList map[PodRole]int64 diff --git a/vendor/kmodules.xyz/resource-metrics/api/doc.go b/vendor/kmodules.xyz/resource-metrics/api/doc.go deleted file mode 100644 index 194a94a30..000000000 --- a/vendor/kmodules.xyz/resource-metrics/api/doc.go +++ /dev/null @@ -1,17 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 api diff --git a/vendor/kmodules.xyz/resource-metrics/api/interface.go b/vendor/kmodules.xyz/resource-metrics/api/interface.go deleted file mode 100644 index ed3735f43..000000000 --- a/vendor/kmodules.xyz/resource-metrics/api/interface.go +++ /dev/null @@ -1,131 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 api - -import ( - core "k8s.io/api/core/v1" -) - -type ResourceCalculator interface { - Replicas(obj map[string]interface{}) (int64, error) - RoleReplicas(obj map[string]interface{}) (ReplicaList, error) - - Mode(obj map[string]interface{}) (string, error) - UsesTLS(obj map[string]interface{}) (bool, error) - - TotalResourceLimits(obj map[string]interface{}) (core.ResourceList, error) - TotalResourceRequests(obj map[string]interface{}) (core.ResourceList, error) - - AppResourceLimits(obj map[string]interface{}) (core.ResourceList, error) - AppResourceRequests(obj map[string]interface{}) (core.ResourceList, error) - - RoleResourceLimits(obj map[string]interface{}) (map[PodRole]core.ResourceList, error) - RoleResourceRequests(obj map[string]interface{}) (map[PodRole]core.ResourceList, error) -} - -type ResourceCalculatorFuncs struct { - // Resources used by the main application (eg, database) containers - AppRoles []PodRole - - // usually AppRoles + Exporter + Any custom sidecar (label selector etc.) that is used at runtime - // Must NOT include init container resources - RuntimeRoles []PodRole - - RoleReplicasFn func(obj map[string]interface{}) (ReplicaList, error) - ModeFn func(obj map[string]interface{}) (string, error) - UsesTLSFn func(obj map[string]interface{}) (bool, error) - RoleResourceLimitsFn func(obj map[string]interface{}) (map[PodRole]core.ResourceList, error) - RoleResourceRequestsFn func(obj map[string]interface{}) (map[PodRole]core.ResourceList, error) -} - -var _ ResourceCalculator = &ResourceCalculatorFuncs{} - -func (c ResourceCalculatorFuncs) Replicas(obj map[string]interface{}) (int64, error) { - replicas, err := c.RoleReplicas(obj) - if err != nil { - return 0, err - } - var cnt int64 = 0 - for _, role := range c.AppRoles { - cnt += replicas[role] - } - return cnt, nil -} - -func (c ResourceCalculatorFuncs) RoleReplicas(obj map[string]interface{}) (ReplicaList, error) { - return c.RoleReplicasFn(obj) -} - -func (c ResourceCalculatorFuncs) Mode(obj map[string]interface{}) (string, error) { - if c.ModeFn != nil { - return c.ModeFn(obj) - } - return "", nil -} - -func (c ResourceCalculatorFuncs) UsesTLS(obj map[string]interface{}) (bool, error) { - if c.UsesTLSFn != nil { - return c.UsesTLSFn(obj) - } - return false, nil -} - -func (c ResourceCalculatorFuncs) TotalResourceLimits(obj map[string]interface{}) (core.ResourceList, error) { - rr, err := c.RoleResourceLimits(obj) - if err != nil { - return nil, err - } - return MaxResourceList( - ResourceListForRoles(rr, c.RuntimeRoles), - ResourceListForRoles(rr, []PodRole{PodRoleInit}), - ), nil -} - -func (c ResourceCalculatorFuncs) TotalResourceRequests(obj map[string]interface{}) (core.ResourceList, error) { - rr, err := c.RoleResourceRequests(obj) - if err != nil { - return nil, err - } - return MaxResourceList( - ResourceListForRoles(rr, c.RuntimeRoles), - ResourceListForRoles(rr, []PodRole{PodRoleInit}), - ), nil -} - -func (c ResourceCalculatorFuncs) AppResourceLimits(obj map[string]interface{}) (core.ResourceList, error) { - rr, err := c.RoleResourceLimits(obj) - if err != nil { - return nil, err - } - return ResourceListForRoles(rr, c.AppRoles), nil -} - -func (c ResourceCalculatorFuncs) AppResourceRequests(obj map[string]interface{}) (core.ResourceList, error) { - rr, err := c.RoleResourceRequests(obj) - if err != nil { - return nil, err - } - return ResourceListForRoles(rr, c.AppRoles), nil -} - -func (c ResourceCalculatorFuncs) RoleResourceLimits(obj map[string]interface{}) (map[PodRole]core.ResourceList, error) { - return c.RoleResourceLimitsFn(obj) -} - -func (c ResourceCalculatorFuncs) RoleResourceRequests(obj map[string]interface{}) (map[PodRole]core.ResourceList, error) { - return c.RoleResourceRequestsFn(obj) -} diff --git a/vendor/kmodules.xyz/resource-metrics/api/plugins.go b/vendor/kmodules.xyz/resource-metrics/api/plugins.go deleted file mode 100644 index 73319bbb9..000000000 --- a/vendor/kmodules.xyz/resource-metrics/api/plugins.go +++ /dev/null @@ -1,76 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 api - -import ( - "fmt" - "sync" - - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -var ( - plugins = map[schema.GroupVersionKind]ResourceCalculator{} - lock sync.RWMutex -) - -func Register(gvk schema.GroupVersionKind, c ResourceCalculator) { - lock.Lock() - plugins[gvk] = c - lock.Unlock() -} - -func Load(obj map[string]interface{}) (ResourceCalculator, error) { - u := unstructured.Unstructured{Object: obj} - gvk := u.GroupVersionKind() - - lock.RLock() - c, ok := plugins[gvk] - lock.RUnlock() - if !ok { - return nil, NotRegistered{gvk} - } - return c, nil -} - -func RegisteredTypes() []schema.GroupVersionKind { - lock.RLock() - result := make([]schema.GroupVersionKind, 0, len(plugins)) - for gvk := range plugins { - result = append(result, gvk) - } - lock.RUnlock() - return result -} - -func IsRegistered(gvk schema.GroupVersionKind) bool { - lock.RLock() - _, ok := plugins[gvk] - lock.RUnlock() - return ok -} - -type NotRegistered struct { - gvk schema.GroupVersionKind -} - -var _ error = NotRegistered{} - -func (e NotRegistered) Error() string { - return fmt.Sprintf("no calculator registered for %v", e.gvk) -} diff --git a/vendor/kmodules.xyz/resource-metrics/api/utils.go b/vendor/kmodules.xyz/resource-metrics/api/utils.go deleted file mode 100644 index e1690b4aa..000000000 --- a/vendor/kmodules.xyz/resource-metrics/api/utils.go +++ /dev/null @@ -1,381 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 api - -import ( - "fmt" - "strings" - - ofst "kmodules.xyz/offshoot-api/api/v1" - ofstv2 "kmodules.xyz/offshoot-api/api/v2" - - "gomodules.xyz/pointer" - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/util/sets" -) - -func ResourceListForRoles(rr map[PodRole]core.ResourceList, roles []PodRole) core.ResourceList { - cpu := resource.Quantity{Format: resource.DecimalSI} - memory := resource.Quantity{Format: resource.BinarySI} - storage := resource.Quantity{Format: resource.BinarySI} - - var rl core.ResourceList - for _, role := range roles { - rl = rr[role] - cpu.Add(*rl.Cpu()) - memory.Add(*rl.Memory()) - storage.Add(*rl.Storage()) - } - - result := core.ResourceList{} - if !cpu.IsZero() { - result[core.ResourceCPU] = cpu - } - if !memory.IsZero() { - result[core.ResourceMemory] = memory - } - if !storage.IsZero() { - result[core.ResourceStorage] = storage - } - return result -} - -func AddResourceList(x, y core.ResourceList) core.ResourceList { - names := sets.NewString() - for k := range x { - names.Insert(string(k)) - } - for k := range y { - names.Insert(string(k)) - } - - result := core.ResourceList{} - for _, fullName := range names.UnsortedList() { - _, name, found := strings.Cut(fullName, ".") - var rf resource.Format - if found { - rf = resourceFormat(core.ResourceName(name)) - } else { - rf = resourceFormat(core.ResourceName(fullName)) - } - - sum := resource.Quantity{Format: rf} - sum.Add(*x.Name(core.ResourceName(fullName), rf)) - sum.Add(*y.Name(core.ResourceName(fullName), rf)) - if !sum.IsZero() { - result[core.ResourceName(fullName)] = sum - } - } - return result -} - -func SubtractResourceList(x, y core.ResourceList) core.ResourceList { - names := sets.NewString() - for k := range x { - names.Insert(string(k)) - } - for k := range y { - names.Insert(string(k)) - } - - result := core.ResourceList{} - for _, fullName := range names.UnsortedList() { - _, name, found := strings.Cut(fullName, ".") - var rf resource.Format - if found { - rf = resourceFormat(core.ResourceName(name)) - } else { - rf = resourceFormat(core.ResourceName(fullName)) - } - - sum := resource.Quantity{Format: rf} - sum.Add(*x.Name(core.ResourceName(fullName), rf)) - sum.Sub(*y.Name(core.ResourceName(fullName), rf)) - result[core.ResourceName(fullName)] = sum - } - return result -} - -func resourceFormat(name core.ResourceName) resource.Format { - switch name { - case core.ResourceCPU: - return resource.DecimalSI - case core.ResourceMemory: - return resource.BinarySI - case core.ResourceStorage: - return resource.BinarySI - case core.ResourcePods: - return resource.DecimalSI - case core.ResourceEphemeralStorage: - return resource.BinarySI - } - return resource.DecimalExponent -} - -func MulResourceList(x core.ResourceList, multiplier int64) core.ResourceList { - result := core.ResourceList{} - - var q *resource.Quantity - - q = x.Cpu() - if !q.IsZero() { - n := resource.Quantity{Format: q.Format} - n.SetMilli(q.MilliValue() * multiplier) - result[core.ResourceCPU] = n - } - - q = x.Memory() - if !q.IsZero() { - n := resource.Quantity{Format: q.Format} - n.SetMilli(q.MilliValue() * multiplier) - result[core.ResourceMemory] = n - } - - q = x.Storage() - if !q.IsZero() { - n := resource.Quantity{Format: q.Format} - n.SetMilli(q.MilliValue() * multiplier) - result[core.ResourceStorage] = n - } - - return result -} - -func MaxResourceList(x, y core.ResourceList) core.ResourceList { - result := core.ResourceList{} - var q *resource.Quantity - - xCPU, yCPU := x.Cpu(), y.Cpu() - if xCPU.Cmp(*yCPU) >= 0 { - q = xCPU - } else { - q = yCPU - } - if !q.IsZero() { - result[core.ResourceCPU] = *q - } - - xMemory, yMemory := x.Memory(), y.Memory() - if xMemory.Cmp(*yMemory) >= 0 { - q = xMemory - } else { - q = yMemory - } - if !q.IsZero() { - result[core.ResourceMemory] = *q - } - - xStorage, yStorage := x.Storage(), y.Storage() - if xStorage.Cmp(*yStorage) >= 0 { - q = xStorage - } else { - q = yStorage - } - if !q.IsZero() { - result[core.ResourceStorage] = *q - } - - return result -} - -func ResourceLimits(rr core.ResourceRequirements) core.ResourceList { - get := func(name core.ResourceName) (*resource.Quantity, bool) { - if limit, exists := rr.Limits[name]; exists { - return &limit, true - } - if req, exists := rr.Requests[name]; exists { - return &req, true - } - return nil, false - } - result := core.ResourceList{} - if q, exists := get(core.ResourceCPU); exists { - result[core.ResourceCPU] = *q - } - if q, exists := get(core.ResourceMemory); exists { - result[core.ResourceMemory] = *q - } - if q, exists := get(core.ResourceStorage); exists { - result[core.ResourceStorage] = *q - } - return result -} - -func ResourceRequests(rr core.ResourceRequirements) core.ResourceList { - if rr.Requests == nil { - return core.ResourceList{} - } - return rr.Requests -} - -type Container struct { - Resources core.ResourceRequirements `json:"resources"` -} - -func AggregateContainerResources( - obj map[string]interface{}, - fn func(rr core.ResourceRequirements) core.ResourceList, - aggregate func(x, y core.ResourceList) core.ResourceList, - fields ...string, -) (core.ResourceList, error) { - val, found, err := unstructured.NestedFieldNoCopy(obj, fields...) - if !found || err != nil { - return nil, err - } - containers, ok := val.([]interface{}) - if !ok { - return nil, fmt.Errorf("%v accessor error: %v is of the type %T, expected []interface{}", strings.Join(fields, "."), val, val) - } - - result := core.ResourceList{} - for i := range containers { - container, ok := containers[i].(map[string]interface{}) - if !ok { - continue - } - - var c Container - err := runtime.DefaultUnstructuredConverter.FromUnstructured(container, &c) - if err != nil { - return nil, fmt.Errorf("failed to parse container %#v: %w", container, err) - } - result = aggregate(result, fn(c.Resources)) - } - return result, nil -} - -func ContainerResources( - obj map[string]interface{}, - fn func(rr core.ResourceRequirements) core.ResourceList, - fields ...string, -) (core.ResourceList, error) { - val, found, err := unstructured.NestedFieldNoCopy(obj, fields...) - if !found || err != nil { - return nil, err - } - - var container Container - err = runtime.DefaultUnstructuredConverter.FromUnstructured(val.(map[string]interface{}), &container) - if err != nil { - return nil, fmt.Errorf("failed to parse container %#v: %w", container, err) - } - return fn(container.Resources), nil -} - -func StorageResources( - obj map[string]interface{}, - fn func(rr core.ResourceRequirements) core.ResourceList, - fields ...string, -) (core.ResourceList, error) { - val, found, err := unstructured.NestedFieldNoCopy(obj, fields...) - if !found || err != nil { - return nil, err - } - - var storage core.PersistentVolumeClaimSpec - err = runtime.DefaultUnstructuredConverter.FromUnstructured(val.(map[string]interface{}), &storage) - if err != nil { - return nil, fmt.Errorf("failed to parse storage %#v: %w", storage, err) - } - return fn(ToResourceRequirements(storage.Resources)), nil -} - -type AppNode struct { - Replicas *int64 `json:"replicas,omitempty"` - PodTemplate ofst.PodTemplateSpec `json:"podTemplate,omitempty"` - Storage core.PersistentVolumeClaimSpec `json:"storage,omitempty"` -} - -func AppNodeResources( - obj map[string]interface{}, - fn func(rr core.ResourceRequirements) core.ResourceList, - fields ...string, -) (core.ResourceList, int64, error) { - val, found, err := unstructured.NestedFieldNoCopy(obj, fields...) - if !found || err != nil { - return nil, 0, err - } - - var node AppNode - err = runtime.DefaultUnstructuredConverter.FromUnstructured(val.(map[string]interface{}), &node) - if err != nil { - return nil, 0, fmt.Errorf("failed to parse node %#v: %w", node, err) - } - - if node.Replicas == nil { - node.Replicas = pointer.Int64P(1) - } - rr := fn(node.PodTemplate.Spec.Resources) - sr := fn(ToResourceRequirements(node.Storage.Resources)) - rr[core.ResourceStorage] = *sr.Storage() - - return rr, *node.Replicas, nil -} - -type AppNodeV2 struct { - Replicas *int64 `json:"replicas,omitempty"` - PodTemplate ofstv2.PodTemplateSpec `json:"podTemplate,omitempty"` - Storage core.PersistentVolumeClaimSpec `json:"storage,omitempty"` -} - -func AppNodeResourcesV2( - obj map[string]interface{}, - fn func(rr core.ResourceRequirements) core.ResourceList, - containerName string, - fields ...string, -) (core.ResourceList, int64, error) { - val, found, err := unstructured.NestedFieldNoCopy(obj, fields...) - if !found || err != nil { - return nil, 0, err - } - - var node AppNodeV2 - err = runtime.DefaultUnstructuredConverter.FromUnstructured(val.(map[string]interface{}), &node) - if err != nil { - return nil, 0, fmt.Errorf("failed to parse node %#v: %w", node, err) - } - - if node.Replicas == nil { - node.Replicas = pointer.Int64P(1) - } - - dbContainer := GetContainerByName(node.PodTemplate.Spec.Containers, containerName) - rr := fn(dbContainer.Resources) - sr := fn(ToResourceRequirements(node.Storage.Resources)) - rr[core.ResourceStorage] = *sr.Storage() - - return rr, *node.Replicas, nil -} - -func ToResourceRequirements(vrr core.VolumeResourceRequirements) core.ResourceRequirements { - return core.ResourceRequirements{ - Limits: vrr.Limits, - Requests: vrr.Requests, - } -} - -func GetContainerByName(containers []core.Container, name string) *core.Container { - for i := range containers { - if containers[i].Name == name { - return &containers[i] - } - } - return nil -} diff --git a/vendor/kmodules.xyz/resource-metrics/apps/v1/daemonset.go b/vendor/kmodules.xyz/resource-metrics/apps/v1/daemonset.go deleted file mode 100644 index 813dd80f6..000000000 --- a/vendor/kmodules.xyz/resource-metrics/apps/v1/daemonset.go +++ /dev/null @@ -1,61 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1 - -import ( - "kmodules.xyz/resource-metrics/api" - - apps "k8s.io/api/apps/v1" - core "k8s.io/api/core/v1" -) - -func init() { - api.Register(apps.SchemeGroupVersion.WithKind("DaemonSet"), DaemonSet{}.ResourceCalculator()) -} - -type DaemonSet struct{} - -func (r DaemonSet) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault}, - RoleReplicasFn: r.roleReplicasFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (_ DaemonSet) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - return nil, nil -} - -func (r DaemonSet) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - containers, err := api.AggregateContainerResources(obj, fn, api.AddResourceList, "spec", "template", "spec", "containers") - if err != nil { - return nil, err - } - initContainers, err := api.AggregateContainerResources(obj, fn, api.MaxResourceList, "spec", "template", "spec", "initContainers") - if err != nil { - return nil, err - } - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: containers, - api.PodRoleInit: initContainers, - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/apps/v1/deployment.go b/vendor/kmodules.xyz/resource-metrics/apps/v1/deployment.go deleted file mode 100644 index 5cc23c256..000000000 --- a/vendor/kmodules.xyz/resource-metrics/apps/v1/deployment.go +++ /dev/null @@ -1,77 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1 - -import ( - "fmt" - - "kmodules.xyz/resource-metrics/api" - - apps "k8s.io/api/apps/v1" - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" -) - -func init() { - api.Register(apps.SchemeGroupVersion.WithKind("Deployment"), Deployment{}.ResourceCalculator()) -} - -type Deployment struct{} - -func (r Deployment) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault}, - RoleReplicasFn: r.roleReplicasFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (_ Deployment) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - replicas, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return nil, fmt.Errorf("failed to read spec.replicas %v: %w", obj, err) - } - if !found { - return api.ReplicaList{api.PodRoleDefault: 1}, nil - } - return api.ReplicaList{api.PodRoleDefault: replicas}, nil -} - -func (r Deployment) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - rr, err := r.roleReplicasFn(obj) - if err != nil { - return nil, err - } - replicas := rr[api.PodRoleDefault] - - containers, err := api.AggregateContainerResources(obj, fn, api.AddResourceList, "spec", "template", "spec", "containers") - if err != nil { - return nil, err - } - initContainers, err := api.AggregateContainerResources(obj, fn, api.MaxResourceList, "spec", "template", "spec", "initContainers") - if err != nil { - return nil, err - } - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: api.MulResourceList(containers, replicas), - api.PodRoleInit: api.MulResourceList(initContainers, replicas), - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/apps/v1/replicaset.go b/vendor/kmodules.xyz/resource-metrics/apps/v1/replicaset.go deleted file mode 100644 index 9a21294b8..000000000 --- a/vendor/kmodules.xyz/resource-metrics/apps/v1/replicaset.go +++ /dev/null @@ -1,77 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1 - -import ( - "fmt" - - "kmodules.xyz/resource-metrics/api" - - apps "k8s.io/api/apps/v1" - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" -) - -func init() { - api.Register(apps.SchemeGroupVersion.WithKind("ReplicaSet"), ReplicaSet{}.ResourceCalculator()) -} - -type ReplicaSet struct{} - -func (r ReplicaSet) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault}, - RoleReplicasFn: r.roleReplicasFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (_ ReplicaSet) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - replicas, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return nil, fmt.Errorf("failed to read spec.replicas %v: %w", obj, err) - } - if !found { - return api.ReplicaList{api.PodRoleDefault: 1}, nil - } - return api.ReplicaList{api.PodRoleDefault: replicas}, nil -} - -func (r ReplicaSet) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - rr, err := r.roleReplicasFn(obj) - if err != nil { - return nil, err - } - replicas := rr[api.PodRoleDefault] - - containers, err := api.AggregateContainerResources(obj, fn, api.AddResourceList, "spec", "template", "spec", "containers") - if err != nil { - return nil, err - } - initContainers, err := api.AggregateContainerResources(obj, fn, api.MaxResourceList, "spec", "template", "spec", "initContainers") - if err != nil { - return nil, err - } - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: api.MulResourceList(containers, replicas), - api.PodRoleInit: api.MulResourceList(initContainers, replicas), - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/apps/v1/statefulset.go b/vendor/kmodules.xyz/resource-metrics/apps/v1/statefulset.go deleted file mode 100644 index 9eda6d739..000000000 --- a/vendor/kmodules.xyz/resource-metrics/apps/v1/statefulset.go +++ /dev/null @@ -1,77 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1 - -import ( - "fmt" - - "kmodules.xyz/resource-metrics/api" - - apps "k8s.io/api/apps/v1" - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" -) - -func init() { - api.Register(apps.SchemeGroupVersion.WithKind("StatefulSet"), StatefulSet{}.ResourceCalculator()) -} - -type StatefulSet struct{} - -func (r StatefulSet) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault}, - RoleReplicasFn: r.roleReplicasFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (_ StatefulSet) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - replicas, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return nil, fmt.Errorf("failed to read spec.replicas %v: %w", obj, err) - } - if !found { - return api.ReplicaList{api.PodRoleDefault: 1}, nil - } - return api.ReplicaList{api.PodRoleDefault: replicas}, nil -} - -func (r StatefulSet) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - rr, err := r.roleReplicasFn(obj) - if err != nil { - return nil, err - } - replicas := rr[api.PodRoleDefault] - - containers, err := api.AggregateContainerResources(obj, fn, api.AddResourceList, "spec", "template", "spec", "containers") - if err != nil { - return nil, err - } - initContainers, err := api.AggregateContainerResources(obj, fn, api.MaxResourceList, "spec", "template", "spec", "initContainers") - if err != nil { - return nil, err - } - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: api.MulResourceList(containers, replicas), - api.PodRoleInit: api.MulResourceList(initContainers, replicas), - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/batch/v1/cronjob.go b/vendor/kmodules.xyz/resource-metrics/batch/v1/cronjob.go deleted file mode 100644 index e44ff8ff7..000000000 --- a/vendor/kmodules.xyz/resource-metrics/batch/v1/cronjob.go +++ /dev/null @@ -1,61 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1 - -import ( - "kmodules.xyz/resource-metrics/api" - - batch "k8s.io/api/batch/v1" - core "k8s.io/api/core/v1" -) - -func init() { - api.Register(batch.SchemeGroupVersion.WithKind("CronJob"), CronJob{}.ResourceCalculator()) -} - -type CronJob struct{} - -func (r CronJob) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault}, - RoleReplicasFn: r.roleReplicasFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (_ CronJob) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - return nil, nil -} - -func (r CronJob) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - containers, err := api.AggregateContainerResources(obj, fn, api.AddResourceList, "spec", "jobTemplate", "spec", "template", "spec", "containers") - if err != nil { - return nil, err - } - initContainers, err := api.AggregateContainerResources(obj, fn, api.MaxResourceList, "spec", "jobTemplate", "spec", "template", "spec", "initContainers") - if err != nil { - return nil, err - } - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: containers, - api.PodRoleInit: initContainers, - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/batch/v1/job.go b/vendor/kmodules.xyz/resource-metrics/batch/v1/job.go deleted file mode 100644 index 07cb3b892..000000000 --- a/vendor/kmodules.xyz/resource-metrics/batch/v1/job.go +++ /dev/null @@ -1,61 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1 - -import ( - "kmodules.xyz/resource-metrics/api" - - batch "k8s.io/api/batch/v1" - core "k8s.io/api/core/v1" -) - -func init() { - api.Register(batch.SchemeGroupVersion.WithKind("Job"), Job{}.ResourceCalculator()) -} - -type Job struct{} - -func (r Job) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault}, - RoleReplicasFn: r.roleReplicasFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (_ Job) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - return nil, nil -} - -func (r Job) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - containers, err := api.AggregateContainerResources(obj, fn, api.AddResourceList, "spec", "template", "spec", "containers") - if err != nil { - return nil, err - } - initContainers, err := api.AggregateContainerResources(obj, fn, api.MaxResourceList, "spec", "template", "spec", "initContainers") - if err != nil { - return nil, err - } - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: containers, - api.PodRoleInit: initContainers, - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/batch/v1beta1/cronjob.go b/vendor/kmodules.xyz/resource-metrics/batch/v1beta1/cronjob.go deleted file mode 100644 index f77da7295..000000000 --- a/vendor/kmodules.xyz/resource-metrics/batch/v1beta1/cronjob.go +++ /dev/null @@ -1,61 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1beta1 - -import ( - "kmodules.xyz/resource-metrics/api" - - batch "k8s.io/api/batch/v1beta1" - core "k8s.io/api/core/v1" -) - -func init() { - api.Register(batch.SchemeGroupVersion.WithKind("CronJob"), CronJob{}.ResourceCalculator()) -} - -type CronJob struct{} - -func (r CronJob) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault}, - RoleReplicasFn: r.roleReplicasFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (_ CronJob) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - return nil, nil -} - -func (r CronJob) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - containers, err := api.AggregateContainerResources(obj, fn, api.AddResourceList, "spec", "jobTemplate", "spec", "template", "spec", "containers") - if err != nil { - return nil, err - } - initContainers, err := api.AggregateContainerResources(obj, fn, api.MaxResourceList, "spec", "jobTemplate", "spec", "template", "spec", "initContainers") - if err != nil { - return nil, err - } - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: containers, - api.PodRoleInit: initContainers, - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/calculator.go b/vendor/kmodules.xyz/resource-metrics/calculator.go deleted file mode 100644 index 5440b4d35..000000000 --- a/vendor/kmodules.xyz/resource-metrics/calculator.go +++ /dev/null @@ -1,110 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 resourcemetrics - -import ( - "kmodules.xyz/resource-metrics/api" - _ "kmodules.xyz/resource-metrics/apps/v1" - _ "kmodules.xyz/resource-metrics/batch/v1" - _ "kmodules.xyz/resource-metrics/batch/v1beta1" - _ "kmodules.xyz/resource-metrics/core/v1" - _ "kmodules.xyz/resource-metrics/kubedb.com/v1alpha2" - _ "kmodules.xyz/resource-metrics/kubevault.com/v1alpha2" - _ "kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1" - - core "k8s.io/api/core/v1" -) - -func Replicas(obj map[string]interface{}) (int64, error) { - c, err := api.Load(obj) - if err != nil { - return 0, err - } - return c.Replicas(obj) -} - -func RoleReplicas(obj map[string]interface{}) (api.ReplicaList, error) { - c, err := api.Load(obj) - if err != nil { - return nil, err - } - return c.RoleReplicas(obj) -} - -func Mode(obj map[string]interface{}) (string, error) { - c, err := api.Load(obj) - if err != nil { - return "", err - } - return c.Mode(obj) -} - -func UsesTLS(obj map[string]interface{}) (bool, error) { - c, err := api.Load(obj) - if err != nil { - return false, err - } - return c.UsesTLS(obj) -} - -func TotalResourceLimits(obj map[string]interface{}) (core.ResourceList, error) { - c, err := api.Load(obj) - if err != nil { - return nil, err - } - return c.TotalResourceLimits(obj) -} - -func TotalResourceRequests(obj map[string]interface{}) (core.ResourceList, error) { - c, err := api.Load(obj) - if err != nil { - return nil, err - } - return c.TotalResourceRequests(obj) -} - -func AppResourceLimits(obj map[string]interface{}) (core.ResourceList, error) { - c, err := api.Load(obj) - if err != nil { - return nil, err - } - return c.AppResourceLimits(obj) -} - -func AppResourceRequests(obj map[string]interface{}) (core.ResourceList, error) { - c, err := api.Load(obj) - if err != nil { - return nil, err - } - return c.AppResourceRequests(obj) -} - -func RoleResourceLimits(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - c, err := api.Load(obj) - if err != nil { - return nil, err - } - return c.RoleResourceLimits(obj) -} - -func RoleResourceRequests(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - c, err := api.Load(obj) - if err != nil { - return nil, err - } - return c.RoleResourceRequests(obj) -} diff --git a/vendor/kmodules.xyz/resource-metrics/core/v1/pod.go b/vendor/kmodules.xyz/resource-metrics/core/v1/pod.go deleted file mode 100644 index 24824d8eb..000000000 --- a/vendor/kmodules.xyz/resource-metrics/core/v1/pod.go +++ /dev/null @@ -1,60 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1 - -import ( - "kmodules.xyz/resource-metrics/api" - - core "k8s.io/api/core/v1" -) - -func init() { - api.Register(core.SchemeGroupVersion.WithKind("Pod"), Pod{}.ResourceCalculator()) -} - -type Pod struct{} - -func (r Pod) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault}, - RoleReplicasFn: r.roleReplicasFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (_ Pod) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - return api.ReplicaList{api.PodRoleDefault: 1}, nil -} - -func (r Pod) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - containers, err := api.AggregateContainerResources(obj, fn, api.AddResourceList, "spec", "containers") - if err != nil { - return nil, err - } - initContainer, err := api.AggregateContainerResources(obj, fn, api.MaxResourceList, "spec", "initContainers") - if err != nil { - return nil, err - } - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: containers, - api.PodRoleInit: initContainer, - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/core/v1/pv.go b/vendor/kmodules.xyz/resource-metrics/core/v1/pv.go deleted file mode 100644 index ab6bd0be7..000000000 --- a/vendor/kmodules.xyz/resource-metrics/core/v1/pv.go +++ /dev/null @@ -1,41 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1 - -import ( - "kmodules.xyz/resource-metrics/api" -) - -//func init() { -// api.Register(core.SchemeGroupVersion.WithKind("PersistentVolume"), PersistentVolume{}.ResourceCalculator()) -//} - -type PersistentVolume struct{} - -func (_ PersistentVolume) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault}, - RoleReplicasFn: nil, - RoleResourceLimitsFn: nil, - RoleResourceRequestsFn: nil, - } -} - -func (_ PersistentVolume) Replicas(_ map[string]interface{}) int { - return 0 // PersistentVolume does not have this field -} diff --git a/vendor/kmodules.xyz/resource-metrics/core/v1/rc.go b/vendor/kmodules.xyz/resource-metrics/core/v1/rc.go deleted file mode 100644 index 444847dc1..000000000 --- a/vendor/kmodules.xyz/resource-metrics/core/v1/rc.go +++ /dev/null @@ -1,76 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1 - -import ( - "fmt" - - "kmodules.xyz/resource-metrics/api" - - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" -) - -func init() { - api.Register(core.SchemeGroupVersion.WithKind("ReplicationController"), ReplicationController{}.ResourceCalculator()) -} - -type ReplicationController struct{} - -func (r ReplicationController) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault}, - RoleReplicasFn: r.roleReplicasFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (_ ReplicationController) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - replicas, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return nil, fmt.Errorf("failed to read spec.replicas %v: %w", obj, err) - } - if !found { - return api.ReplicaList{api.PodRoleDefault: 1}, nil - } - return api.ReplicaList{api.PodRoleDefault: replicas}, nil -} - -func (r ReplicationController) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - rr, err := r.roleReplicasFn(obj) - if err != nil { - return nil, err - } - replicas := rr[api.PodRoleDefault] - - container, err := api.AggregateContainerResources(obj, fn, api.AddResourceList, "spec", "template", "spec", "containers") - if err != nil { - return nil, err - } - initContainers, err := api.AggregateContainerResources(obj, fn, api.MaxResourceList, "spec", "template", "spec", "initContainers") - if err != nil { - return nil, err - } - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: api.MulResourceList(container, replicas), - api.PodRoleInit: api.MulResourceList(initContainers, replicas), - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/doc.go b/vendor/kmodules.xyz/resource-metrics/doc.go deleted file mode 100644 index 195ec750d..000000000 --- a/vendor/kmodules.xyz/resource-metrics/doc.go +++ /dev/null @@ -1,17 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 resourcemetrics // import "kmodules.xyz/resource-metrics" diff --git a/vendor/kmodules.xyz/resource-metrics/eval.go b/vendor/kmodules.xyz/resource-metrics/eval.go deleted file mode 100644 index 0b5bad1dd..000000000 --- a/vendor/kmodules.xyz/resource-metrics/eval.go +++ /dev/null @@ -1,116 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 resourcemetrics - -import ( - "fmt" - "reflect" - - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" -) - -// EvalFuncs for https://github.com/gomodules/eval -func EvalFuncs() map[string]func(arguments ...interface{}) (interface{}, error) { - return map[string]func(arguments ...interface{}) (interface{}, error){ - "resource_replicas": resourceReplicas, - "resource_mode": resourceMode, - "resource_uses_tls": resourceUsesTLS, - "total_resource_limits": totalResourceLimits, - "total_resource_requests": totalResourceRequests, - "app_resource_limits": appResourceLimits, - "app_resource_requests": appResourceRequests, - } -} - -// resourceReplicas(resource_obj) -func resourceReplicas(args ...interface{}) (interface{}, error) { - return Replicas(args[0].(map[string]interface{})) -} - -// resourceMode(resource_obj) -func resourceMode(args ...interface{}) (interface{}, error) { - return Mode(args[0].(map[string]interface{})) -} - -// resourceUsesTLS(resource_obj) -func resourceUsesTLS(args ...interface{}) (interface{}, error) { - return UsesTLS(args[0].(map[string]interface{})) -} - -// totalResourceLimits(resource_obj, resource_type) => cpu cores (float64) -func totalResourceLimits(args ...interface{}) (interface{}, error) { - rr, err := TotalResourceLimits(args[0].(map[string]interface{})) - if err != nil { - return nil, err - } - return resourceQuantity(rr, args[1]) -} - -// totalResourceRequests(resource_obj, resource_type) -func totalResourceRequests(args ...interface{}) (interface{}, error) { - rr, err := TotalResourceRequests(args[0].(map[string]interface{})) - if err != nil { - return nil, err - } - return resourceQuantity(rr, args[1]) -} - -// appResourceLimits(resource_obj, resource_type) -func appResourceLimits(args ...interface{}) (interface{}, error) { - rr, err := AppResourceLimits(args[0].(map[string]interface{})) - if err != nil { - return nil, err - } - return resourceQuantity(rr, args[1]) -} - -// appResourceRequests(resource_obj, resource_type) -func appResourceRequests(args ...interface{}) (interface{}, error) { - rr, err := AppResourceRequests(args[0].(map[string]interface{})) - if err != nil { - return nil, err - } - return resourceQuantity(rr, args[1]) -} - -func resourceQuantity(rr core.ResourceList, resourceName interface{}) (interface{}, error) { - var name core.ResourceName - - switch u := resourceName.(type) { - case core.ResourceName: - name = u - case string: - name = core.ResourceName(u) - default: - return nil, fmt.Errorf("ResourceName %v with unrecognized type %v", resourceName, reflect.TypeOf(resourceName)) - } - - q := rr[name] - return resourceQuantityAsFloat64(name, q), nil -} - -func resourceQuantityAsFloat64(name core.ResourceName, q resource.Quantity) float64 { - // WARNING: q.AsApproximateFloat64() does not work - // ref: https://github.com/kubernetes/kube-state-metrics/blob/16e8f54c9e7f9f4b4ad73002e03e9d0dcee5b1ce/internal/store/pod.go#L234 - switch name { - case core.ResourceCPU: - return float64(q.MilliValue()) / 1000 - default: - return float64(q.Value()) - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/constants.go b/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/constants.go deleted file mode 100644 index d38edabc1..000000000 --- a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/constants.go +++ /dev/null @@ -1,33 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha2 - -const ( - DBModeEnsemble = "Ensemble" - DBModeCluster = "Cluster" - DBModeSharded = "Sharded" - DBModeStandalone = "Standalone" - DBModeReplicaSet = "ReplicaSet" - DBModeDedicated = "Dedicated" - DBModeCombined = "Combined" -) - -const ( - RabbitMQContainerName = "rabbitmq" - SinglestoreContainerName = "singlestore" - ZooKeeperContainerName = "zookeeper" -) diff --git a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/elasticsearch.go b/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/elasticsearch.go deleted file mode 100644 index 323618974..000000000 --- a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/elasticsearch.go +++ /dev/null @@ -1,180 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha2 - -import ( - "fmt" - "reflect" - - "kmodules.xyz/resource-metrics/api" - - "gomodules.xyz/pointer" - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func init() { - api.Register(schema.GroupVersionKind{ - Group: "kubedb.com", - Version: "v1alpha2", - Kind: "Elasticsearch", - }, Elasticsearch{}.ResourceCalculator()) -} - -type Elasticsearch struct{} - -func (r Elasticsearch) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault, api.PodRoleExporter}, - RoleReplicasFn: r.roleReplicasFn, - ModeFn: r.modeFn, - UsesTLSFn: r.usesTLSFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (r Elasticsearch) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - result := api.ReplicaList{} - - topology, found, err := unstructured.NestedMap(obj, "spec", "topology") - if err != nil { - return nil, err - } - if found && topology != nil { - var replicas int64 = 0 - for role, roleSpec := range topology { - roleReplicas, found, err := unstructured.NestedInt64(roleSpec.(map[string]interface{}), "replicas") - if err != nil { - return nil, err - } - if found { - result[api.PodRole(role)] = roleReplicas - replicas += roleReplicas - } - } - result[api.PodRoleDefault] = replicas - } else { - // Combined mode - replicas, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return nil, fmt.Errorf("failed to read spec.replicas %v: %w", obj, err) - } - if !found { - result[api.PodRoleDefault] = 1 - } else { - result[api.PodRoleDefault] = replicas - } - } - return result, nil -} - -func (r Elasticsearch) modeFn(obj map[string]interface{}) (string, error) { - topology, found, err := unstructured.NestedFieldNoCopy(obj, "spec", "topology") - if err != nil { - return "", err - } - if found && !reflect.ValueOf(topology).IsNil() { - return DBModeDedicated, nil - } - return DBModeCombined, nil -} - -func (r Elasticsearch) usesTLSFn(obj map[string]interface{}) (bool, error) { - _, found, err := unstructured.NestedFieldNoCopy(obj, "spec", "enableSSL") - return found, err -} - -func (r Elasticsearch) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - exporter, err := api.ContainerResources(obj, fn, "spec", "monitor", "prometheus", "exporter") - if err != nil { - return nil, err - } - - topology, found, err := unstructured.NestedMap(obj, "spec", "topology") - if err != nil { - return nil, err - } - if found && topology != nil { - var replicas int64 = 0 - var totalResources core.ResourceList - result := map[api.PodRole]core.ResourceList{} - - for role, roleSpec := range topology { - rolePerReplicaResources, roleReplicas, err := ElasticsearchNodeResources(roleSpec.(map[string]interface{}), fn) - if err != nil { - return nil, err - } - - roleResources := api.MulResourceList(rolePerReplicaResources, roleReplicas) - result[api.PodRole(role)] = roleResources - totalResources = api.AddResourceList(totalResources, roleResources) - } - - result[api.PodRoleDefault] = totalResources - result[api.PodRoleExporter] = api.MulResourceList(exporter, replicas) - return result, nil - } - - // Elasticsearch Combined - container, replicas, err := api.AppNodeResources(obj, fn, "spec") - if err != nil { - return nil, err - } - - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: api.MulResourceList(container, replicas), - api.PodRoleExporter: api.MulResourceList(exporter, replicas), - }, nil - } -} - -type ElasticsearchNode struct { - Replicas *int64 `json:"replicas,omitempty"` - Resources core.ResourceRequirements `json:"resources,omitempty"` - Storage core.PersistentVolumeClaimSpec `json:"storage,omitempty"` -} - -func ElasticsearchNodeResources( - obj map[string]interface{}, - fn func(rr core.ResourceRequirements) core.ResourceList, - fields ...string, -) (core.ResourceList, int64, error) { - val, found, err := unstructured.NestedFieldNoCopy(obj, fields...) - if !found || err != nil { - return nil, 0, err - } - - var node ElasticsearchNode - err = runtime.DefaultUnstructuredConverter.FromUnstructured(val.(map[string]interface{}), &node) - if err != nil { - return nil, 0, fmt.Errorf("failed to parse node %#v: %w", node, err) - } - - if node.Replicas == nil { - node.Replicas = pointer.Int64P(1) - } - rr := fn(node.Resources) - sr := fn(api.ToResourceRequirements(node.Storage.Resources)) - rr[core.ResourceStorage] = *sr.Storage() - - return rr, *node.Replicas, nil -} diff --git a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/kafka.go b/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/kafka.go deleted file mode 100644 index caa347c7a..000000000 --- a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/kafka.go +++ /dev/null @@ -1,181 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha2 - -import ( - "fmt" - "reflect" - - "kmodules.xyz/resource-metrics/api" - - "gomodules.xyz/pointer" - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func init() { - api.Register(schema.GroupVersionKind{ - Group: "kubedb.com", - Version: "v1alpha2", - Kind: "Kafka", - }, Kafka{}.ResourceCalculator()) -} - -type Kafka struct{} - -func (r Kafka) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault, api.PodRoleExporter}, - RoleReplicasFn: r.roleReplicasFn, - ModeFn: r.modeFn, - UsesTLSFn: r.usesTLSFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (r Kafka) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - result := api.ReplicaList{} - - topology, found, err := unstructured.NestedMap(obj, "spec", "topology") - if err != nil { - return nil, err - } - if found && topology != nil { - // dedicated topology mode - var replicas int64 = 0 - for role, roleSpec := range topology { - roleReplicas, found, err := unstructured.NestedInt64(roleSpec.(map[string]interface{}), "replicas") - if err != nil { - return nil, err - } - if found { - result[api.PodRole(role)] = roleReplicas - replicas += roleReplicas - } - } - result[api.PodRoleDefault] = replicas - } else { - // Combined mode - replicas, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return nil, fmt.Errorf("failed to read spec.replicas %v: %w", obj, err) - } - if !found { - result[api.PodRoleDefault] = 1 - } else { - result[api.PodRoleDefault] = replicas - } - } - return result, nil -} - -func (r Kafka) modeFn(obj map[string]interface{}) (string, error) { - topology, found, err := unstructured.NestedFieldNoCopy(obj, "spec", "topology") - if err != nil { - return "", err - } - if found && !reflect.ValueOf(topology).IsNil() { - return DBModeDedicated, nil - } - return DBModeCombined, nil -} - -func (r Kafka) usesTLSFn(obj map[string]interface{}) (bool, error) { - _, found, err := unstructured.NestedFieldNoCopy(obj, "spec", "enableSSL") - return found, err -} - -func (r Kafka) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - exporter, err := api.ContainerResources(obj, fn, "spec", "monitor", "prometheus", "exporter") - if err != nil { - return nil, err - } - - topology, found, err := unstructured.NestedMap(obj, "spec", "topology") - if err != nil { - return nil, err - } - if found && topology != nil { - var replicas int64 = 0 - var totalResources core.ResourceList - result := map[api.PodRole]core.ResourceList{} - - for role, roleSpec := range topology { - rolePerReplicaResources, roleReplicas, err := KafkaNodeResources(roleSpec.(map[string]interface{}), fn) - if err != nil { - return nil, err - } - - roleResources := api.MulResourceList(rolePerReplicaResources, roleReplicas) - result[api.PodRole(role)] = roleResources - totalResources = api.AddResourceList(totalResources, roleResources) - } - - result[api.PodRoleDefault] = totalResources - result[api.PodRoleExporter] = api.MulResourceList(exporter, replicas) - return result, nil - } - - // Kafka Combined - container, replicas, err := api.AppNodeResources(obj, fn, "spec") - if err != nil { - return nil, err - } - - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: api.MulResourceList(container, replicas), - api.PodRoleExporter: api.MulResourceList(exporter, replicas), - }, nil - } -} - -type KafkaNode struct { - Replicas *int64 `json:"replicas,omitempty"` - Resources core.ResourceRequirements `json:"resources,omitempty"` - Storage core.PersistentVolumeClaimSpec `json:"storage,omitempty"` -} - -func KafkaNodeResources( - obj map[string]interface{}, - fn func(rr core.ResourceRequirements) core.ResourceList, - fields ...string, -) (core.ResourceList, int64, error) { - val, found, err := unstructured.NestedFieldNoCopy(obj, fields...) - if !found || err != nil { - return nil, 0, err - } - - var node KafkaNode - err = runtime.DefaultUnstructuredConverter.FromUnstructured(val.(map[string]interface{}), &node) - if err != nil { - return nil, 0, fmt.Errorf("failed to parse node %#v: %w", node, err) - } - - if node.Replicas == nil { - node.Replicas = pointer.Int64P(1) - } - rr := fn(node.Resources) - sr := fn(api.ToResourceRequirements(node.Storage.Resources)) - rr[core.ResourceStorage] = *sr.Storage() - - return rr, *node.Replicas, nil -} diff --git a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/mariadb.go b/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/mariadb.go deleted file mode 100644 index 7095e5ac2..000000000 --- a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/mariadb.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha2 - -import ( - "fmt" - - "kmodules.xyz/resource-metrics/api" - - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func init() { - api.Register(schema.GroupVersionKind{ - Group: "kubedb.com", - Version: "v1alpha2", - Kind: "MariaDB", - }, MariaDB{}.ResourceCalculator()) -} - -type MariaDB struct{} - -func (r MariaDB) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault, api.PodRoleExporter}, - RoleReplicasFn: r.roleReplicasFn, - ModeFn: r.modeFn, - UsesTLSFn: r.usesTLSFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (r MariaDB) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - replicas, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return nil, fmt.Errorf("failed to read spec.replicas %v: %w", obj, err) - } - if !found { - return api.ReplicaList{api.PodRoleDefault: 1}, nil - } - return api.ReplicaList{api.PodRoleDefault: replicas}, nil -} - -func (r MariaDB) modeFn(obj map[string]interface{}) (string, error) { - replicas, _, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return "", err - } - if replicas > 1 { - return DBModeCluster, nil - } - return DBModeStandalone, nil -} - -func (r MariaDB) usesTLSFn(obj map[string]interface{}) (bool, error) { - _, found, err := unstructured.NestedFieldNoCopy(obj, "spec", "tls") - return found, err -} - -func (r MariaDB) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - container, replicas, err := api.AppNodeResources(obj, fn, "spec") - if err != nil { - return nil, err - } - - exporter, err := api.ContainerResources(obj, fn, "spec", "monitor", "prometheus", "exporter") - if err != nil { - return nil, err - } - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: api.MulResourceList(container, replicas), - api.PodRoleExporter: api.MulResourceList(exporter, replicas), - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/memcached.go b/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/memcached.go deleted file mode 100644 index 501569d3b..000000000 --- a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/memcached.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha2 - -import ( - "fmt" - - "kmodules.xyz/resource-metrics/api" - - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func init() { - api.Register(schema.GroupVersionKind{ - Group: "kubedb.com", - Version: "v1alpha2", - Kind: "Memcached", - }, Memcached{}.ResourceCalculator()) -} - -type Memcached struct{} - -func (r Memcached) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault, api.PodRoleExporter}, - RoleReplicasFn: r.roleReplicasFn, - ModeFn: r.modeFn, - UsesTLSFn: r.usesTLSFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (r Memcached) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - replicas, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return nil, fmt.Errorf("failed to read spec.replicas %v: %w", obj, err) - } - if !found { - return api.ReplicaList{api.PodRoleDefault: 1}, nil - } - return api.ReplicaList{api.PodRoleDefault: replicas}, nil -} - -func (r Memcached) modeFn(obj map[string]interface{}) (string, error) { - replicas, _, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return "", err - } - if replicas > 1 { - return DBModeCluster, nil - } - return DBModeStandalone, nil -} - -func (r Memcached) usesTLSFn(obj map[string]interface{}) (bool, error) { - _, found, err := unstructured.NestedFieldNoCopy(obj, "spec", "tls") - return found, err -} - -func (r Memcached) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - container, replicas, err := api.AppNodeResources(obj, fn, "spec") - if err != nil { - return nil, err - } - - exporter, err := api.ContainerResources(obj, fn, "spec", "monitor", "prometheus", "exporter") - if err != nil { - return nil, err - } - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: api.MulResourceList(container, replicas), - api.PodRoleExporter: api.MulResourceList(exporter, replicas), - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/mongodb.go b/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/mongodb.go deleted file mode 100644 index cbac3b80f..000000000 --- a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/mongodb.go +++ /dev/null @@ -1,171 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha2 - -import ( - "fmt" - - "kmodules.xyz/resource-metrics/api" - - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func init() { - api.Register(schema.GroupVersionKind{ - Group: "kubedb.com", - Version: "v1alpha2", - Kind: "MongoDB", - }, MongoDB{}.ResourceCalculator()) -} - -type MongoDB struct{} - -func (r MongoDB) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault, api.PodRoleTotalShard, api.PodRoleConfigServer, api.PodRoleMongos}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault, api.PodRoleTotalShard, api.PodRoleConfigServer, api.PodRoleMongos, api.PodRoleExporter}, - RoleReplicasFn: r.roleReplicasFn, - ModeFn: r.modeFn, - UsesTLSFn: r.usesTLSFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (r MongoDB) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - // Sharded MongoDB cluster - shardTopology, found, err := unstructured.NestedMap(obj, "spec", "shardTopology") - if err != nil { - return nil, err - } - if found && shardTopology != nil { - shards, _, err := unstructured.NestedInt64(shardTopology, "shard", "shards") - if err != nil { - return nil, err - } - shardReplicas, _, err := unstructured.NestedInt64(shardTopology, "shard", "replicas") - if err != nil { - return nil, err - } - configServerReplicas, _, err := unstructured.NestedInt64(shardTopology, "configServer", "replicas") - if err != nil { - return nil, err - } - mongosReplicas, _, err := unstructured.NestedInt64(shardTopology, "mongos", "replicas") - if err != nil { - return nil, err - } - return api.ReplicaList{ - api.PodRoleTotalShard: shards * shardReplicas, - api.PodRoleShard: shards, - api.PodRoleReplicasPerShard: shardReplicas, - api.PodRoleConfigServer: configServerReplicas, - api.PodRoleMongos: mongosReplicas, - }, nil - } - - // MongoDB ReplicaSet or Standalone - replicas, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return nil, fmt.Errorf("failed to read spec.replicas %v: %w", obj, err) - } - if !found { - return api.ReplicaList{api.PodRoleDefault: 1}, nil - } - return api.ReplicaList{api.PodRoleDefault: replicas}, nil -} - -func (r MongoDB) modeFn(obj map[string]interface{}) (string, error) { - shards, found, err := unstructured.NestedMap(obj, "spec", "shardTopology") - if err != nil { - return "", err - } - if found && shards != nil { - return DBModeSharded, nil - } - rs, found, err := unstructured.NestedMap(obj, "spec", "replicaSet") - if err != nil { - return "", err - } - if found && rs != nil { - return DBModeReplicaSet, nil - } - return DBModeStandalone, nil -} - -func (r MongoDB) usesTLSFn(obj map[string]interface{}) (bool, error) { - _, found, err := unstructured.NestedFieldNoCopy(obj, "spec", "tls") - return found, err -} - -func (r MongoDB) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - exporter, err := api.ContainerResources(obj, fn, "spec", "monitor", "prometheus", "exporter") - if err != nil { - return nil, err - } - - // Sharded MongoDB - shardTopology, found, err := unstructured.NestedMap(obj, "spec", "shardTopology") - if err != nil { - return nil, err - } - if found && shardTopology != nil { - // Shard nodes resources - shards, _, err := unstructured.NestedInt64(shardTopology, "shard", "shards") - if err != nil { - return nil, err - } - shard, shardReplicas, err := api.AppNodeResources(shardTopology, fn, "shard") - if err != nil { - return nil, err - } - - // ConfigServer nodes resources - configServer, configServerReplicas, err := api.AppNodeResources(shardTopology, fn, "configServer") - if err != nil { - return nil, err - } - - // Mongos node resources - mongos, mongosReplicas, err := api.AppNodeResources(shardTopology, fn, "mongos") - if err != nil { - return nil, err - } - - return map[api.PodRole]core.ResourceList{ - api.PodRoleTotalShard: api.MulResourceList(shard, shards*shardReplicas), - api.PodRoleConfigServer: api.MulResourceList(configServer, configServerReplicas), - api.PodRoleMongos: api.MulResourceList(mongos, mongosReplicas), - api.PodRoleExporter: api.MulResourceList(exporter, shards*shardReplicas+configServerReplicas+mongosReplicas), - }, nil - } - - // MongoDB ReplicaSet or Standalone - container, replicas, err := api.AppNodeResources(obj, fn, "spec") - if err != nil { - return nil, err - } - - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: api.MulResourceList(container, replicas), - api.PodRoleExporter: api.MulResourceList(exporter, replicas), - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/mysql.go b/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/mysql.go deleted file mode 100644 index c2cb55e9b..000000000 --- a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/mysql.go +++ /dev/null @@ -1,132 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha2 - -import ( - "fmt" - - "kmodules.xyz/resource-metrics/api" - - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func init() { - api.Register(schema.GroupVersionKind{ - Group: "kubedb.com", - Version: "v1alpha2", - Kind: "MySQL", - }, MySQL{}.ResourceCalculator()) -} - -type MySQL struct{} - -func (r MySQL) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault, api.PodRoleRouter}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault, api.PodRoleExporter, api.PodRoleRouter}, - RoleReplicasFn: r.roleReplicasFn, - ModeFn: r.modeFn, - UsesTLSFn: r.usesTLSFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (r MySQL) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - result := api.ReplicaList{} - - // Standalone or GroupReplication Mode - replicas, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return nil, fmt.Errorf("failed to read spec.replicas %v: %w", obj, err) - } - if !found { - result[api.PodRoleDefault] = 1 - } else { - result[api.PodRoleDefault] = replicas - } - - // InnoDB Router - mode, found, err := unstructured.NestedString(obj, "spec", "topology", "mode") - if err != nil { - return nil, err - } - if found && mode == "InnoDBCluster" { - replicas, found, err := unstructured.NestedInt64(obj, "spec", "topology", "innoDBCluster", "router", "replicas") - if err != nil { - return nil, err - } - if !found { - result[api.PodRoleRouter] = 1 - } else { - result[api.PodRoleRouter] = replicas - } - } - - return result, nil -} - -func (r MySQL) modeFn(obj map[string]interface{}) (string, error) { - mode, found, err := unstructured.NestedString(obj, "spec", "topology", "mode") - if err != nil { - return "", err - } - if found { - return mode, nil - } - return DBModeStandalone, nil -} - -func (r MySQL) usesTLSFn(obj map[string]interface{}) (bool, error) { - _, found, err := unstructured.NestedFieldNoCopy(obj, "spec", "tls") - return found, err -} - -func (r MySQL) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - container, replicas, err := api.AppNodeResources(obj, fn, "spec") - if err != nil { - return nil, err - } - - exporter, err := api.ContainerResources(obj, fn, "spec", "monitor", "prometheus", "exporter") - if err != nil { - return nil, err - } - - result := map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: api.MulResourceList(container, replicas), - api.PodRoleExporter: api.MulResourceList(exporter, replicas), - } - - // InnoDB Router - mode, found, err := unstructured.NestedString(obj, "spec", "topology", "mode") - if err != nil { - return nil, err - } - if found && mode == "InnoDBCluster" { - router, replicas, err := api.AppNodeResources(obj, fn, "spec", "topology", "innoDBCluster", "router") - if err != nil { - return nil, err - } - result[api.PodRoleRouter] = api.MulResourceList(router, replicas) - } - return result, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/perconaxtradb.go b/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/perconaxtradb.go deleted file mode 100644 index 476c67358..000000000 --- a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/perconaxtradb.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha2 - -import ( - "fmt" - - "kmodules.xyz/resource-metrics/api" - - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func init() { - api.Register(schema.GroupVersionKind{ - Group: "kubedb.com", - Version: "v1alpha2", - Kind: "PerconaXtraDB", - }, PerconaXtraDB{}.ResourceCalculator()) -} - -type PerconaXtraDB struct{} - -func (r PerconaXtraDB) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault, api.PodRoleExporter}, - RoleReplicasFn: r.roleReplicasFn, - ModeFn: r.modeFn, - UsesTLSFn: r.usesTLSFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (r PerconaXtraDB) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - replicas, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return nil, fmt.Errorf("failed to read spec.replicas %v: %w", obj, err) - } - if !found { - return api.ReplicaList{api.PodRoleDefault: 1}, nil - } - return api.ReplicaList{api.PodRoleDefault: replicas}, nil -} - -func (r PerconaXtraDB) modeFn(obj map[string]interface{}) (string, error) { - replicas, _, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return "", err - } - if replicas > 1 { - return DBModeCluster, nil - } - return DBModeStandalone, nil -} - -func (r PerconaXtraDB) usesTLSFn(obj map[string]interface{}) (bool, error) { - _, found, err := unstructured.NestedFieldNoCopy(obj, "spec", "tls") - return found, err -} - -func (r PerconaXtraDB) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - container, replicas, err := api.AppNodeResources(obj, fn, "spec") - if err != nil { - return nil, err - } - - exporter, err := api.ContainerResources(obj, fn, "spec", "monitor", "prometheus", "exporter") - if err != nil { - return nil, err - } - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: api.MulResourceList(container, replicas), - api.PodRoleExporter: api.MulResourceList(exporter, replicas), - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/pgbouncer.go b/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/pgbouncer.go deleted file mode 100644 index 0d8b5b11b..000000000 --- a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/pgbouncer.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha2 - -import ( - "fmt" - - "kmodules.xyz/resource-metrics/api" - - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func init() { - api.Register(schema.GroupVersionKind{ - Group: "kubedb.com", - Version: "v1alpha2", - Kind: "PgBouncer", - }, PgBouncer{}.ResourceCalculator()) -} - -type PgBouncer struct{} - -func (r PgBouncer) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault, api.PodRoleExporter}, - RoleReplicasFn: r.roleReplicasFn, - ModeFn: r.modeFn, - UsesTLSFn: r.usesTLSFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (r PgBouncer) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - replicas, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return nil, fmt.Errorf("failed to read spec.replicas %v: %w", obj, err) - } - if !found { - return api.ReplicaList{api.PodRoleDefault: 1}, nil - } - return api.ReplicaList{api.PodRoleDefault: replicas}, nil -} - -func (r PgBouncer) modeFn(obj map[string]interface{}) (string, error) { - replicas, _, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return "", err - } - if replicas > 1 { - return DBModeCluster, nil - } - return DBModeStandalone, nil -} - -func (r PgBouncer) usesTLSFn(obj map[string]interface{}) (bool, error) { - _, found, err := unstructured.NestedFieldNoCopy(obj, "spec", "tls") - return found, err -} - -func (r PgBouncer) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - container, replicas, err := api.AppNodeResources(obj, fn, "spec") - if err != nil { - return nil, err - } - - exporter, err := api.ContainerResources(obj, fn, "spec", "monitor", "prometheus", "exporter") - if err != nil { - return nil, err - } - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: api.MulResourceList(container, replicas), - api.PodRoleExporter: api.MulResourceList(exporter, replicas), - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/postgres.go b/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/postgres.go deleted file mode 100644 index 8cc498512..000000000 --- a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/postgres.go +++ /dev/null @@ -1,95 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha2 - -import ( - "fmt" - - "kmodules.xyz/resource-metrics/api" - - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func init() { - api.Register(schema.GroupVersionKind{ - Group: "kubedb.com", - Version: "v1alpha2", - Kind: "Postgres", - }, Postgres{}.ResourceCalculator()) -} - -type Postgres struct{} - -func (r Postgres) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault, api.PodRoleExporter}, - RoleReplicasFn: r.roleReplicasFn, - ModeFn: r.modeFn, - UsesTLSFn: r.usesTLSFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (r Postgres) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - v, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return nil, fmt.Errorf("failed to read spec.replicas %v: %w", obj, err) - } - if !found { - return api.ReplicaList{api.PodRoleDefault: 1}, nil - } - return api.ReplicaList{api.PodRoleDefault: v}, nil -} - -func (r Postgres) modeFn(obj map[string]interface{}) (string, error) { - mode, found, err := unstructured.NestedString(obj, "spec", "mode") - if err == nil && found { - return mode, nil - } - replicas, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err == nil && found && replicas > 1 { - return DBModeCluster, nil - } - return DBModeStandalone, nil -} - -func (r Postgres) usesTLSFn(obj map[string]interface{}) (bool, error) { - _, found, err := unstructured.NestedFieldNoCopy(obj, "spec", "tls") - return found, err -} - -func (r Postgres) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - container, replicas, err := api.AppNodeResources(obj, fn, "spec") - if err != nil { - return nil, err - } - - exporter, err := api.ContainerResources(obj, fn, "spec", "monitor", "prometheus", "exporter") - if err != nil { - return nil, err - } - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: api.MulResourceList(container, replicas), - api.PodRoleExporter: api.MulResourceList(exporter, replicas), - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/proxysql.go b/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/proxysql.go deleted file mode 100644 index c8f9c2d39..000000000 --- a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/proxysql.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha2 - -import ( - "fmt" - - "kmodules.xyz/resource-metrics/api" - - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func init() { - api.Register(schema.GroupVersionKind{ - Group: "kubedb.com", - Version: "v1alpha2", - Kind: "ProxySQL", - }, ProxySQL{}.ResourceCalculator()) -} - -type ProxySQL struct{} - -func (r ProxySQL) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault, api.PodRoleExporter}, - RoleReplicasFn: r.roleReplicasFn, - ModeFn: r.modeFn, - UsesTLSFn: r.usesTLSFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (r ProxySQL) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - replicas, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return nil, fmt.Errorf("failed to read spec.replicas %v: %w", obj, err) - } - if !found { - return api.ReplicaList{api.PodRoleDefault: 1}, nil - } - return api.ReplicaList{api.PodRoleDefault: replicas}, nil -} - -func (r ProxySQL) modeFn(obj map[string]interface{}) (string, error) { - replicas, _, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return "", err - } - if replicas > 1 { - return DBModeCluster, nil - } - return DBModeStandalone, nil -} - -func (r ProxySQL) usesTLSFn(obj map[string]interface{}) (bool, error) { - _, found, err := unstructured.NestedFieldNoCopy(obj, "spec", "tls") - return found, err -} - -func (r ProxySQL) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - container, replicas, err := api.AppNodeResources(obj, fn, "spec") - if err != nil { - return nil, err - } - - exporter, err := api.ContainerResources(obj, fn, "spec", "monitor", "prometheus", "exporter") - if err != nil { - return nil, err - } - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: api.MulResourceList(container, replicas), - api.PodRoleExporter: api.MulResourceList(exporter, replicas), - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/rabbitmq.go b/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/rabbitmq.go deleted file mode 100644 index 07cfcb32f..000000000 --- a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/rabbitmq.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha2 - -import ( - "fmt" - - "kmodules.xyz/resource-metrics/api" - - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func init() { - api.Register(schema.GroupVersionKind{ - Group: "kubedb.com", - Version: "v1alpha2", - Kind: "RabbitMQ", - }, RabbitMQ{}.ResourceCalculator()) -} - -type RabbitMQ struct{} - -func (r RabbitMQ) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault, api.PodRoleExporter}, - RoleReplicasFn: r.roleReplicasFn, - ModeFn: r.modeFn, - UsesTLSFn: r.usesTLSFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (r RabbitMQ) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - replicas, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return nil, fmt.Errorf("failed to read spec.replicas %v: %w", obj, err) - } - if !found { - return api.ReplicaList{api.PodRoleDefault: 1}, nil - } - return api.ReplicaList{api.PodRoleDefault: replicas}, nil -} - -func (r RabbitMQ) modeFn(obj map[string]interface{}) (string, error) { - replicas, _, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return "", err - } - if replicas > 1 { - return DBModeCluster, nil - } - return DBModeStandalone, nil -} - -func (r RabbitMQ) usesTLSFn(obj map[string]interface{}) (bool, error) { - _, found, err := unstructured.NestedFieldNoCopy(obj, "spec", "tls") - return found, err -} - -func (r RabbitMQ) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - container, replicas, err := api.AppNodeResourcesV2(obj, fn, RabbitMQContainerName, "spec") - if err != nil { - return nil, err - } - - exporter, err := api.ContainerResources(obj, fn, "spec", "monitor", "prometheus", "exporter") - if err != nil { - return nil, err - } - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: api.MulResourceList(container, replicas), - api.PodRoleExporter: api.MulResourceList(exporter, replicas), - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/redis.go b/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/redis.go deleted file mode 100644 index 6135e1b3a..000000000 --- a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/redis.go +++ /dev/null @@ -1,137 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha2 - -import ( - "fmt" - - "kmodules.xyz/resource-metrics/api" - - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func init() { - api.Register(schema.GroupVersionKind{ - Group: "kubedb.com", - Version: "v1alpha2", - Kind: "Redis", - }, Redis{}.ResourceCalculator()) -} - -type Redis struct{} - -func (r Redis) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault, api.PodRoleExporter}, - RoleReplicasFn: r.roleReplicasFn, - ModeFn: r.modeFn, - UsesTLSFn: r.usesTLSFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (r Redis) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - mode, found, err := unstructured.NestedString(obj, "spec", "mode") - if err != nil { - return nil, err - } - if found && mode == DBModeCluster { - shards, _, err := unstructured.NestedInt64(obj, "spec", "cluster", "master") - if err != nil { - return nil, err - } - shardReplicas, _, err := unstructured.NestedInt64(obj, "spec", "cluster", "replicas") - if err != nil { - return nil, err - } - return api.ReplicaList{ - api.PodRoleTotalShard: shards * shardReplicas, - api.PodRoleDefault: shards * shardReplicas, - api.PodRoleShard: shards, - api.PodRoleReplicasPerShard: shardReplicas, - }, nil - } - - // Standalone or sentinel - replicas, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return nil, fmt.Errorf("failed to read spec.replicas %v: %w", obj, err) - } - if !found { - return api.ReplicaList{api.PodRoleDefault: 1}, nil - } - return api.ReplicaList{api.PodRoleDefault: replicas}, nil -} - -func (r Redis) modeFn(obj map[string]interface{}) (string, error) { - mode, found, err := unstructured.NestedString(obj, "spec", "mode") - if err != nil { - return "", err - } - if found { - return mode, nil - } - return DBModeStandalone, nil -} - -func (r Redis) usesTLSFn(obj map[string]interface{}) (bool, error) { - _, found, err := unstructured.NestedFieldNoCopy(obj, "spec", "tls") - return found, err -} - -func (r Redis) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - exporter, err := api.ContainerResources(obj, fn, "spec", "monitor", "prometheus", "exporter") - if err != nil { - return nil, err - } - - // Redis Sentinel or Standalone - container, replicas, err := api.AppNodeResources(obj, fn, "spec") - if err != nil { - return nil, err - } - - mode, found, err := unstructured.NestedString(obj, "spec", "mode") - if err != nil { - return nil, err - } - if found && mode == DBModeCluster { - shards, _, err := unstructured.NestedInt64(obj, "spec", "cluster", "master") - if err != nil { - return nil, err - } - shardReplicas, _, err := unstructured.NestedInt64(obj, "spec", "cluster", "replicas") - if err != nil { - return nil, err - } - // If spec.cluster.replicas = x - // That means in each shard there are (x+1) redis replicas - shardReplicas += 1 - replicas = shards * shardReplicas - } - - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: api.MulResourceList(container, replicas), - api.PodRoleExporter: api.MulResourceList(exporter, replicas), - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/redissentinel.go b/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/redissentinel.go deleted file mode 100644 index e12d64151..000000000 --- a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/redissentinel.go +++ /dev/null @@ -1,82 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha2 - -import ( - "fmt" - - "kmodules.xyz/resource-metrics/api" - - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func init() { - api.Register(schema.GroupVersionKind{ - Group: "kubedb.com", - Version: "v1alpha2", - Kind: "RedisSentinel", - }, RedisSentinel{}.ResourceCalculator()) -} - -type RedisSentinel struct{} - -func (r RedisSentinel) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault, api.PodRoleExporter}, - RoleReplicasFn: r.roleReplicasFn, - ModeFn: r.modeFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (r RedisSentinel) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - replicas, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return nil, fmt.Errorf("failed to read spec.replicas %v: %w", obj, err) - } - if !found { - return api.ReplicaList{api.PodRoleDefault: 1}, nil - } - return api.ReplicaList{api.PodRoleDefault: replicas}, nil -} - -func (r RedisSentinel) modeFn(obj map[string]interface{}) (string, error) { - return DBModeCluster, nil -} - -func (r RedisSentinel) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - exporter, err := api.ContainerResources(obj, fn, "spec", "monitor", "prometheus", "exporter") - if err != nil { - return nil, err - } - - container, replicas, err := api.AppNodeResources(obj, fn, "spec") - if err != nil { - return nil, err - } - - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: api.MulResourceList(container, replicas), - api.PodRoleExporter: api.MulResourceList(exporter, replicas), - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/singlestore.go b/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/singlestore.go deleted file mode 100644 index 0e71f7ba6..000000000 --- a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/singlestore.go +++ /dev/null @@ -1,142 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha2 - -import ( - "fmt" - "reflect" - - "kmodules.xyz/resource-metrics/api" - - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func init() { - api.Register(schema.GroupVersionKind{ - Group: "kubedb.com", - Version: "v1alpha2", - Kind: "Singlestore", - }, Singlestore{}.ResourceCalculator()) -} - -type Singlestore struct{} - -func (r Singlestore) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault, api.PodRoleAggregator, api.PodRoleLeaf}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault, api.PodRoleAggregator, api.PodRoleLeaf, api.PodRoleExporter}, - RoleReplicasFn: r.roleReplicasFn, - ModeFn: r.modeFn, - UsesTLSFn: r.usesTLSFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (r Singlestore) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - result := api.ReplicaList{} - - topology, found, err := unstructured.NestedMap(obj, "spec", "topology") - if err != nil { - return nil, err - } - if found && topology != nil { - // dedicated topology mode - var replicas int64 = 0 - for role, roleSpec := range topology { - roleReplicas, found, err := unstructured.NestedInt64(roleSpec.(map[string]interface{}), "replicas") - if err != nil { - return nil, err - } - if found { - result[api.PodRole(role)] = roleReplicas - replicas += roleReplicas - } - } - } else { - // Combined mode - replicas, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return nil, fmt.Errorf("failed to read spec.replicas %v: %w", obj, err) - } - if !found { - result[api.PodRoleDefault] = 1 - } else { - result[api.PodRoleDefault] = replicas - } - } - return result, nil -} - -func (r Singlestore) modeFn(obj map[string]interface{}) (string, error) { - topology, found, err := unstructured.NestedFieldNoCopy(obj, "spec", "topology") - if err != nil { - return "", err - } - if found && !reflect.ValueOf(topology).IsNil() { - return DBModeDedicated, nil - } - return DBModeCombined, nil -} - -func (r Singlestore) usesTLSFn(obj map[string]interface{}) (bool, error) { - _, found, err := unstructured.NestedFieldNoCopy(obj, "spec", "tls") - return found, err -} - -func (r Singlestore) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - exporter, err := api.ContainerResources(obj, fn, "spec", "monitor", "prometheus", "exporter") - if err != nil { - return nil, err - } - - topology, found, err := unstructured.NestedMap(obj, "spec", "topology") - if err != nil { - return nil, err - } - if found && topology != nil { - aggregator, aggregatorReplicas, err := api.AppNodeResourcesV2(topology, fn, SinglestoreContainerName, "aggregator") - if err != nil { - return nil, err - } - - leaf, leafReplicas, err := api.AppNodeResourcesV2(topology, fn, SinglestoreContainerName, "leaf") - if err != nil { - return nil, err - } - - return map[api.PodRole]core.ResourceList{ - api.PodRoleAggregator: api.MulResourceList(aggregator, aggregatorReplicas), - api.PodRoleLeaf: api.MulResourceList(leaf, leafReplicas), - api.PodRoleExporter: api.MulResourceList(exporter, aggregatorReplicas+leafReplicas), - }, nil - } - - container, replicas, err := api.AppNodeResourcesV2(obj, fn, SinglestoreContainerName, "spec") - if err != nil { - return nil, err - } - - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: api.MulResourceList(container, replicas), - api.PodRoleExporter: api.MulResourceList(exporter, replicas), - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/zookeeper.go b/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/zookeeper.go deleted file mode 100644 index 98d2307ee..000000000 --- a/vendor/kmodules.xyz/resource-metrics/kubedb.com/v1alpha2/zookeeper.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha2 - -import ( - "fmt" - - "kmodules.xyz/resource-metrics/api" - - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func init() { - api.Register(schema.GroupVersionKind{ - Group: "kubedb.com", - Version: "v1alpha2", - Kind: "ZooKeeper", - }, ZooKeeper{}.ResourceCalculator()) -} - -type ZooKeeper struct{} - -func (z ZooKeeper) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault, api.PodRoleExporter}, - RoleReplicasFn: z.roleReplicasFn, - ModeFn: z.modeFn, - UsesTLSFn: z.usesTLSFn, - RoleResourceLimitsFn: z.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: z.roleResourceFn(api.ResourceRequests), - } -} - -func (z ZooKeeper) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - replicas, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return nil, fmt.Errorf("failed to read spec.replicas %v: %w", obj, err) - } - if !found { - return api.ReplicaList{api.PodRoleDefault: 1}, nil - } - return api.ReplicaList{api.PodRoleDefault: replicas}, nil -} - -func (z ZooKeeper) modeFn(obj map[string]interface{}) (string, error) { - replicas, _, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return "", err - } - if replicas > 1 { - return DBModeEnsemble, nil - } - return DBModeStandalone, nil -} - -func (z ZooKeeper) usesTLSFn(obj map[string]interface{}) (bool, error) { - _, found, err := unstructured.NestedFieldNoCopy(obj, "spec", "tls") - return found, err -} - -func (z ZooKeeper) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - container, replicas, err := api.AppNodeResourcesV2(obj, fn, ZooKeeperContainerName, "spec") - if err != nil { - return nil, err - } - - exporter, err := api.ContainerResources(obj, fn, "spec", "monitor", "prometheus", "exporter") - if err != nil { - return nil, err - } - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: api.MulResourceList(container, replicas), - api.PodRoleExporter: api.MulResourceList(exporter, replicas), - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/kubevault.com/v1alpha2/constant.go b/vendor/kmodules.xyz/resource-metrics/kubevault.com/v1alpha2/constant.go deleted file mode 100644 index 88f872cd9..000000000 --- a/vendor/kmodules.xyz/resource-metrics/kubevault.com/v1alpha2/constant.go +++ /dev/null @@ -1,19 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha2 - -const VaultModeDefault = "Default" diff --git a/vendor/kmodules.xyz/resource-metrics/kubevault.com/v1alpha2/vaultserver.go b/vendor/kmodules.xyz/resource-metrics/kubevault.com/v1alpha2/vaultserver.go deleted file mode 100644 index 13e2c2516..000000000 --- a/vendor/kmodules.xyz/resource-metrics/kubevault.com/v1alpha2/vaultserver.go +++ /dev/null @@ -1,96 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha2 - -import ( - "fmt" - - "kmodules.xyz/resource-metrics/api" - - core "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func init() { - api.Register(schema.GroupVersionKind{ - Group: "kubevault.com", - Version: "v1alpha2", - Kind: "VaultServer", - }, VaultServer{}.ResourceCalculator()) -} - -type VaultServer struct{} - -func (r VaultServer) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault, api.PodRoleExporter}, - RoleReplicasFn: r.roleReplicasFn, - ModeFn: r.modeFn, - UsesTLSFn: r.usesTLSFn, - RoleResourceLimitsFn: r.roleResourceFn(api.ResourceLimits), - RoleResourceRequestsFn: r.roleResourceFn(api.ResourceRequests), - } -} - -func (r VaultServer) roleReplicasFn(obj map[string]interface{}) (api.ReplicaList, error) { - replicas, found, err := unstructured.NestedInt64(obj, "spec", "replicas") - if err != nil { - return nil, fmt.Errorf("failed to read spec.replicas %v: %w", obj, err) - } - if !found { - return api.ReplicaList{api.PodRoleDefault: 1}, nil - } - return api.ReplicaList{api.PodRoleDefault: replicas}, nil -} - -func (r VaultServer) modeFn(obj map[string]interface{}) (string, error) { - return VaultModeDefault, nil -} - -func (r VaultServer) usesTLSFn(obj map[string]interface{}) (bool, error) { - _, found, err := unstructured.NestedFieldNoCopy(obj, "spec", "tls") - return found, err -} - -func (r VaultServer) roleResourceFn(fn func(rr core.ResourceRequirements) core.ResourceList) func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - return func(obj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - exporter, err := api.ContainerResources(obj, fn, "spec", "monitor", "prometheus", "exporter") - if err != nil { - return nil, err - } - - container, replicas, err := api.AppNodeResources(obj, fn, "spec") - if err != nil { - return nil, err - } - - raftBackend, _, err := api.AppNodeResources(obj, fn, "spec", "backend", "raft") - if err != nil { - return nil, err - } - if raftBackend != nil { - container[core.ResourceStorage] = raftBackend[core.ResourceStorage] - } - - return map[api.PodRole]core.ResourceList{ - api.PodRoleDefault: api.MulResourceList(container, replicas), - api.PodRoleExporter: api.MulResourceList(exporter, replicas), - }, nil - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/calculator.go b/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/calculator.go deleted file mode 100644 index 253cd9e86..000000000 --- a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/calculator.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import ( - "kmodules.xyz/resource-metrics/api" - - core "k8s.io/api/core/v1" -) - -type OpsResourceCalculator struct{} - -func (r OpsResourceCalculator) ResourceCalculator() api.ResourceCalculator { - return &api.ResourceCalculatorFuncs{ - AppRoles: []api.PodRole{api.PodRoleDefault}, - RuntimeRoles: []api.PodRole{api.PodRoleDefault, api.PodRoleExporter}, - RoleReplicasFn: r.roleReplicasFn, - ModeFn: r.modeFn, - UsesTLSFn: r.usesTLSFn, - RoleResourceLimitsFn: r.roleResourceLimitsFn, - RoleResourceRequestsFn: r.roleResourceRequestsFn, - } -} - -func (r OpsResourceCalculator) roleReplicasFn(opsObj map[string]interface{}) (api.ReplicaList, error) { - scaledObject, err := GetScaledObject(opsObj) - if err != nil { - return nil, err - } - - c, err := api.Load(scaledObject) - if err != nil { - return nil, err - } - return c.RoleReplicas(scaledObject) -} - -func (r OpsResourceCalculator) modeFn(opsObj map[string]interface{}) (string, error) { - scaledObject, err := GetScaledObject(opsObj) - if err != nil { - return "", err - } - - c, err := api.Load(scaledObject) - if err != nil { - return "", err - } - return c.Mode(scaledObject) -} - -func (r OpsResourceCalculator) usesTLSFn(opsObj map[string]interface{}) (bool, error) { - scaledObject, err := GetScaledObject(opsObj) - if err != nil { - return false, err - } - - c, err := api.Load(scaledObject) - if err != nil { - return false, err - } - return c.UsesTLS(scaledObject) -} - -func (r OpsResourceCalculator) roleResourceLimitsFn(opsObj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - scaledObject, err := GetScaledObject(opsObj) - if err != nil { - return nil, err - } - - c, err := api.Load(scaledObject) - if err != nil { - return nil, err - } - return c.RoleResourceLimits(scaledObject) -} - -func (r OpsResourceCalculator) roleResourceRequestsFn(opsObj map[string]interface{}) (map[api.PodRole]core.ResourceList, error) { - scaledObject, err := GetScaledObject(opsObj) - if err != nil { - return nil, err - } - - c, err := api.Load(scaledObject) - if err != nil { - return nil, err - } - return c.RoleResourceRequests(scaledObject) -} diff --git a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/constansts.go b/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/constansts.go deleted file mode 100644 index 7ace8fb72..000000000 --- a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/constansts.go +++ /dev/null @@ -1,27 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -const ( - DBModeCluster = "Cluster" - DBModeSharded = "Sharded" - DBStandalone = "Standalone" - DBModeReplicaSet = "ReplicaSet" - ScalingTypeHorizontal = "HorizontalScaling" - ScalingTypeVertical = "VerticalScaling" - ScalingTypeVolumeExpansion = "VolumeExpansion" -) diff --git a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/elasticsearch_mapping.go b/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/elasticsearch_mapping.go deleted file mode 100644 index 43b7705bb..000000000 --- a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/elasticsearch_mapping.go +++ /dev/null @@ -1,91 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import "k8s.io/apimachinery/pkg/runtime/schema" - -func init() { - RegisterOpsPathMapperToPlugins(&ElasticsearchOpsRequest{}) -} - -type ElasticsearchOpsRequest struct{} - -var _ OpsPathMapper = (*ElasticsearchOpsRequest)(nil) - -func (m *ElasticsearchOpsRequest) HorizontalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.horizontalScaling.node": "spec.replicas", - "spec.horizontalScaling.topology.master": "spec.topology.master.replicas", - "spec.horizontalScaling.topology.ingest": "spec.topology.ingest.replicas", - "spec.horizontalScaling.topology.data": "spec.topology.data.replicas", - "spec.horizontalScaling.topology.dataContent": "spec.topology.dataContent.replicas", - "spec.horizontalScaling.topology.dataHot": "spec.topology.dataHot.replicas", - "spec.horizontalScaling.topology.dataWarm": "spec.topology.dataWarm.replicas", - "spec.horizontalScaling.topology.dataCold": "spec.topology.dataCold.replicas", - "spec.horizontalScaling.topology.dataFrozen": "spec.topology.dataFrozen.replicas", - "spec.horizontalScaling.topology.ml": "spec.topology.ml.replicas", - "spec.horizontalScaling.topology.transform": "spec.topology.transform.replicas", - "spec.horizontalScaling.topology.coordinating": "spec.topology.coordinating.replicas", - } -} - -func (m *ElasticsearchOpsRequest) VerticalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.verticalScaling.node": "spec.resources", - "spec.verticalScaling.exporter": "spec.topology.exporter.resources", - "spec.verticalScaling.topology.master": "spec.topology.master.resources", - "spec.verticalScaling.topology.ingest": "spec.topology.ingest.resources", - "spec.verticalScaling.topology.data": "spec.topology.data.resources", - "spec.verticalScaling.topology.dataContent": "spec.topology.dataContent.resources", - "spec.verticalScaling.topology.dataHot": "spec.topology.dataHot.resources", - "spec.verticalScaling.topology.dataWarm": "spec.topology.dataWarm.resources", - "spec.verticalScaling.topology.dataCold": "spec.topology.dataCold.resources", - "spec.verticalScaling.topology.dataFrozen": "spec.topology.dataFrozen.resources", - "spec.verticalScaling.topology.ml": "spec.topology.ml.resources", - "spec.verticalScaling.topology.transform": "spec.topology.transform.resources", - "spec.verticalScaling.topology.coordinating": "spec.topology.coordinating.resources", - } -} - -func (m *ElasticsearchOpsRequest) VolumeExpansionPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.volumeExpansion.node": "spec.storage.resources.requests.storage", - "spec.volumeExpansion.topology.master": "spec.topology.master.storage.resources.requests.storage", - "spec.volumeExpansion.topology.ingest": "spec.topology.ingest.storage.resources.requests.storage", - "spec.volumeExpansion.topology.data": "spec.topology.data.storage.resources.requests.storage", - "spec.volumeExpansion.topology.dataContent": "spec.topology.dataContent.storage.resources.requests.storage", - "spec.volumeExpansion.topology.dataHot": "spec.topology.dataHot.storage.resources.requests.storage", - "spec.volumeExpansion.topology.dataWarm": "spec.topology.dataWarm.storage.resources.requests.storage", - "spec.volumeExpansion.topology.dataCold": "spec.topology.dataCold.storage.resources.requests.storage", - "spec.volumeExpansion.topology.dataFrozen": "spec.topology.dataFrozen.storage.resources.requests.storage", - "spec.volumeExpansion.topology.ml": "spec.topology.ml.storage.resources.requests.storage", - "spec.volumeExpansion.topology.transform": "spec.topology.transform.storage.resources.requests.storage", - "spec.volumeExpansion.topology.coordinating": "spec.topology.coordinating.storage.resources.requests.storage", - } -} - -func (m *ElasticsearchOpsRequest) GetReferencedDbObjectPath() []string { - return []string{"spec", "databaseRef", "referencedDB"} -} - -func (m *ElasticsearchOpsRequest) GroupVersionKind() schema.GroupVersionKind { - return schema.GroupVersionKind{ - Group: "ops.kubedb.com", - Version: "v1alpha1", - Kind: "ElasticsearchOpsRequest", - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/kafka_mapping.go b/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/kafka_mapping.go deleted file mode 100644 index 3ee45b21e..000000000 --- a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/kafka_mapping.go +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import "k8s.io/apimachinery/pkg/runtime/schema" - -func init() { - RegisterOpsPathMapperToPlugins(&kafkaOpsRequest{}) -} - -type kafkaOpsRequest struct{} - -var _ OpsPathMapper = (*kafkaOpsRequest)(nil) - -func (m *kafkaOpsRequest) HorizontalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.horizontalScaling.node": "spec.replicas", - "spec.horizontalScaling.topology.broker": "spec.topology.broker.replicas", - "spec.horizontalScaling.topology.controller": "spec.topology.controller.replicas", - } -} - -func (m *kafkaOpsRequest) VerticalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.verticalScaling.node": "spec.podTemplate.spec.resources", - "spec.verticalScaling.topology.broker": "spec.topology.broker.resources", - "spec.verticalScaling.topology.controller": "spec.topology.controller.resources", - } -} - -func (m *kafkaOpsRequest) VolumeExpansionPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.volumeExpansion.node": "spec.storage.resources.requests.storage", - "spec.volumeExpansion.topology.broker": "spec.topology.broker.storage.resources.requests.storage", - "spec.volumeExpansion.topology.controller": "spec.topology.controller.storage.resources.requests.storage", - } -} - -func (m *kafkaOpsRequest) GetReferencedDbObjectPath() []string { - return []string{"spec", "databaseRef", "referencedDB"} -} - -func (m *kafkaOpsRequest) GroupVersionKind() schema.GroupVersionKind { - return schema.GroupVersionKind{ - Group: "ops.kubedb.com", - Version: "v1alpha1", - Kind: "KafkaOpsRequest", - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/mapper.go b/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/mapper.go deleted file mode 100644 index 0a369428b..000000000 --- a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/mapper.go +++ /dev/null @@ -1,69 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import ( - "errors" - "sync" - - "kmodules.xyz/resource-metrics/api" - - "k8s.io/apimachinery/pkg/runtime/schema" -) - -type OpsPathMapper interface { - HorizontalPathMapping() map[OpsReqPath]ReferencedObjPath - VerticalPathMapping() map[OpsReqPath]ReferencedObjPath - VolumeExpansionPathMapping() map[OpsReqPath]ReferencedObjPath - GetReferencedDbObjectPath() []string - GroupVersionKind() schema.GroupVersionKind -} - -type ( - OpsReqPath string - ReferencedObjPath string - ScaledObject map[string]interface{} - OpsReqObject map[string]interface{} -) - -var ( - PathMapperPlugin = map[schema.GroupVersionKind]OpsPathMapper{} - OpsCalculator = OpsResourceCalculator{}.ResourceCalculator() - lock sync.RWMutex -) - -func RegisterToPathMapperPlugin(opsObj OpsPathMapper) { - PathMapperPlugin[opsObj.GroupVersionKind()] = opsObj -} - -func RegisterOpsPathMapperToPlugins(opsObj OpsPathMapper) { - RegisterToPathMapperPlugin(opsObj) - api.Register(opsObj.GroupVersionKind(), OpsCalculator) -} - -func LoadOpsPathMapper(opsObj OpsReqObject) (OpsPathMapper, error) { - gvk := getGVK(opsObj) - - lock.RLock() - opsMapperObj, found := PathMapperPlugin[gvk] - lock.RUnlock() - if !found { - return nil, errors.New("gvk not registered") - } - - return opsMapperObj, nil -} diff --git a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/mariadb_mapping.go b/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/mariadb_mapping.go deleted file mode 100644 index 30812bc85..000000000 --- a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/mariadb_mapping.go +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import "k8s.io/apimachinery/pkg/runtime/schema" - -func init() { - RegisterOpsPathMapperToPlugins(&MariaDBOpsRequest{}) -} - -type MariaDBOpsRequest struct{} - -var _ OpsPathMapper = (*MariaDBOpsRequest)(nil) - -func (m *MariaDBOpsRequest) HorizontalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{} -} - -func (m *MariaDBOpsRequest) VerticalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{} -} - -func (m *MariaDBOpsRequest) VolumeExpansionPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{} -} - -func (m *MariaDBOpsRequest) GetReferencedDbObjectPath() []string { - return []string{"spec", "databaseRef", "referencedDB"} -} - -func (m *MariaDBOpsRequest) GroupVersionKind() schema.GroupVersionKind { - return schema.GroupVersionKind{ - Group: "ops.kubedb.com", - Version: "v1alpha1", - Kind: "MariaDBOpsRequest", - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/memcached_mapping.go b/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/memcached_mapping.go deleted file mode 100644 index e536d0fda..000000000 --- a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/memcached_mapping.go +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import "k8s.io/apimachinery/pkg/runtime/schema" - -func init() { - RegisterOpsPathMapperToPlugins(&MemcachedOpsRequest{}) -} - -type MemcachedOpsRequest struct{} - -var _ OpsPathMapper = (*MemcachedOpsRequest)(nil) - -func (m *MemcachedOpsRequest) HorizontalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{} -} - -func (m *MemcachedOpsRequest) VerticalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{} -} - -func (m *MemcachedOpsRequest) VolumeExpansionPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{} -} - -func (m *MemcachedOpsRequest) GetReferencedDbObjectPath() []string { - return []string{"spec", "databaseRef", "referencedDB"} -} - -func (m *MemcachedOpsRequest) GroupVersionKind() schema.GroupVersionKind { - return schema.GroupVersionKind{ - Group: "ops.kubedb.com", - Version: "v1alpha1", - Kind: "MemcachedOpsRequest", - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/mongodb_mapping.go b/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/mongodb_mapping.go deleted file mode 100644 index b078d8d74..000000000 --- a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/mongodb_mapping.go +++ /dev/null @@ -1,76 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import ( - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func init() { - RegisterOpsPathMapperToPlugins(&MongoDBOpsRequest{}) -} - -type MongoDBOpsRequest struct{} - -var _ OpsPathMapper = (*MongoDBOpsRequest)(nil) - -func (m *MongoDBOpsRequest) HorizontalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.horizontalScaling.shard.shards": "spec.shardTopology.shard.shards", - "spec.horizontalScaling.shard.replicas": "spec.shardTopology.shard.replicas", - "spec.horizontalScaling.configServer.replicas": "spec.shardTopology.configServer.replicas", - "spec.horizontalScaling.mongos.replicas": "spec.shardTopology.mongos.replicas", - "spec.horizontalScaling.hidden.replicas": "spec.hidden.replicas", - "spec.horizontalScaling.replicas": "spec.replicas", - } -} - -func (m *MongoDBOpsRequest) VerticalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.verticalScaling.standalone": "spec.podTemplate.spec.resources", - "spec.verticalScaling.replicaSet": "spec.podTemplate.spec.resources", - "spec.verticalScaling.mongos": "spec.shardTopology.mongos.podTemplate.spec.resources", - "spec.verticalScaling.configServer": "spec.shardTopology.configServer.podTemplate.spec.resources", - "spec.verticalScaling.shard": "spec.shardTopology.shard.podTemplate.spec.resources", - "spec.verticalScaling.arbiter": "spec.arbiter.podTemplate.spec.resources", - "spec.verticalScaling.hidden": "spec.hidden.podTemplate.spec.resources", - "spec.verticalScaling.exporter": "spec.monitor.prometheus.exporter.resources", - //"spec.verticalScaling.coordinator": "spec.coordinator.resources", - } -} - -func (m *MongoDBOpsRequest) VolumeExpansionPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.volumeExpansion.standalone": "spec.storage.resources.requests.storage", - "spec.volumeExpansion.replicaSet": "spec.storage.resources.requests.storage", - "spec.volumeExpansion.configServer": "spec.shardTopology.configServer.storage.resources.requests.storage", - "spec.volumeExpansion.shard": "spec.shardTopology.shard.storage.resources.requests.storage", - "spec.volumeExpansion.hidden": "spec.hidden.storage.resources.requests.storage", - } -} - -func (m *MongoDBOpsRequest) GetReferencedDbObjectPath() []string { - return []string{"spec", "databaseRef", "referencedDB"} -} - -func (m *MongoDBOpsRequest) GroupVersionKind() schema.GroupVersionKind { - return schema.GroupVersionKind{ - Group: "ops.kubedb.com", - Version: "v1alpha1", - Kind: "MongoDBOpsRequest", - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/mysql_mapping.go b/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/mysql_mapping.go deleted file mode 100644 index dee99e73c..000000000 --- a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/mysql_mapping.go +++ /dev/null @@ -1,59 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import "k8s.io/apimachinery/pkg/runtime/schema" - -func init() { - RegisterOpsPathMapperToPlugins(&MySqlOpsRequest{}) -} - -type MySqlOpsRequest struct{} - -var _ OpsPathMapper = (*MySqlOpsRequest)(nil) - -func (m *MySqlOpsRequest) HorizontalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.horizontalScaling.member": "spec.replicas", - } -} - -func (m *MySqlOpsRequest) VerticalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.verticalScaling.mysql": "spec.podTemplate.spec.resources", - "spec.verticalScaling.exporter": "spec.monitor.prometheus.exporter.resources", - "spec.verticalScaling.coordinator": "spec.coordinator.resources", - } -} - -func (m *MySqlOpsRequest) VolumeExpansionPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.volumeExpansion.mysql": "spec.storage.resources.requests.storage", - } -} - -func (m *MySqlOpsRequest) GetReferencedDbObjectPath() []string { - return []string{"spec", "databaseRef", "referencedDB"} -} - -func (m *MySqlOpsRequest) GroupVersionKind() schema.GroupVersionKind { - return schema.GroupVersionKind{ - Group: "ops.kubedb.com", - Version: "v1alpha1", - Kind: "MySQLOpsRequest", - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/pgbouncer_mapping.go b/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/pgbouncer_mapping.go deleted file mode 100644 index 8e10ac9b5..000000000 --- a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/pgbouncer_mapping.go +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import "k8s.io/apimachinery/pkg/runtime/schema" - -func init() { - RegisterOpsPathMapperToPlugins(&PgBouncerOpsRequest{}) -} - -type PgBouncerOpsRequest struct{} - -var _ OpsPathMapper = (*PgBouncerOpsRequest)(nil) - -func (m *PgBouncerOpsRequest) HorizontalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{} -} - -func (m *PgBouncerOpsRequest) VerticalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{} -} - -func (m *PgBouncerOpsRequest) VolumeExpansionPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{} -} - -func (m *PgBouncerOpsRequest) GetReferencedDbObjectPath() []string { - return []string{"spec", "databaseRef", "referencedDB"} -} - -func (m *PgBouncerOpsRequest) GroupVersionKind() schema.GroupVersionKind { - return schema.GroupVersionKind{ - Group: "ops.kubedb.com", - Version: "v1alpha1", - Kind: "PgBouncerOpsRequest", - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/postgres_mapping.go b/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/postgres_mapping.go deleted file mode 100644 index 08755662e..000000000 --- a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/postgres_mapping.go +++ /dev/null @@ -1,61 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import "k8s.io/apimachinery/pkg/runtime/schema" - -func init() { - RegisterOpsPathMapperToPlugins(&PostgresOpsRequest{}) -} - -type PostgresOpsRequest struct{} - -var _ OpsPathMapper = (*PostgresOpsRequest)(nil) - -func (m *PostgresOpsRequest) HorizontalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.horizontalScaling.replicas": "spec.replicas", - "spec.horizontalScaling.standbyMode": "spec.standbyMode", - "spec.horizontalScaling.streamingMode": "spec.streamingMode", - } -} - -func (m *PostgresOpsRequest) VerticalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.verticalScaling.postgres": "spec.podTemplate.spec.resources", - "spec.verticalScaling.exporter": "spec.monitor.prometheus.exporter.resources", - "spec.verticalScaling.coordinator": "spec.coordinator.resources", - } -} - -func (m *PostgresOpsRequest) VolumeExpansionPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.volumeExpansion.postgres": "spec.storage.resources.requests.storage", - } -} - -func (m *PostgresOpsRequest) GetReferencedDbObjectPath() []string { - return []string{"spec", "databaseRef", "referencedDB"} -} - -func (m *PostgresOpsRequest) GroupVersionKind() schema.GroupVersionKind { - return schema.GroupVersionKind{ - Group: "ops.kubedb.com", - Version: "v1alpha1", - Kind: "PostgresOpsRequest", - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/proxysql_mapping.go b/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/proxysql_mapping.go deleted file mode 100644 index eef128402..000000000 --- a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/proxysql_mapping.go +++ /dev/null @@ -1,55 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import "k8s.io/apimachinery/pkg/runtime/schema" - -func init() { - RegisterOpsPathMapperToPlugins(&ProxySQLOpsRequest{}) -} - -type ProxySQLOpsRequest struct{} - -var _ OpsPathMapper = (*ProxySQLOpsRequest)(nil) - -func (m *ProxySQLOpsRequest) HorizontalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.horizontalScaling.member": "spec.replicas", - } -} - -func (m *ProxySQLOpsRequest) VerticalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.verticalScaling.proxysql": "spec.podTemplate.spec.resources", - } -} - -func (m *ProxySQLOpsRequest) VolumeExpansionPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{} -} - -func (m *ProxySQLOpsRequest) GetReferencedDbObjectPath() []string { - return []string{"spec", "proxyRef", "referencedDB"} -} - -func (m *ProxySQLOpsRequest) GroupVersionKind() schema.GroupVersionKind { - return schema.GroupVersionKind{ - Group: "ops.kubedb.com", - Version: "v1alpha1", - Kind: "ProxySQLOpsRequest", - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/redis_mapping.go b/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/redis_mapping.go deleted file mode 100644 index 1323442e1..000000000 --- a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/redis_mapping.go +++ /dev/null @@ -1,60 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import "k8s.io/apimachinery/pkg/runtime/schema" - -func init() { - RegisterOpsPathMapperToPlugins(&RedisOpsRequest{}) -} - -type RedisOpsRequest struct{} - -var _ OpsPathMapper = (*RedisOpsRequest)(nil) - -func (m *RedisOpsRequest) HorizontalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.horizontalScaling.master": "spec.cluster.master", - "spec.horizontalScaling.replicas": "spec.cluster.replicas", - } -} - -func (m *RedisOpsRequest) VerticalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.verticalScaling.redis": "spec.podTemplate.spec.resources", - "spec.verticalScaling.exporter": "spec.monitor.prometheus.exporter.resources", - "spec.verticalScaling.coordinator": "spec.coordinator.resources", - } -} - -func (m *RedisOpsRequest) VolumeExpansionPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.volumeExpansion.redis": "spec.storage.resources.requests.storage", - } -} - -func (m *RedisOpsRequest) GetReferencedDbObjectPath() []string { - return []string{"spec", "databaseRef", "referencedDB"} -} - -func (m *RedisOpsRequest) GroupVersionKind() schema.GroupVersionKind { - return schema.GroupVersionKind{ - Group: "ops.kubedb.com", - Version: "v1alpha1", - Kind: "RedisOpsRequest", - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/redissentinel_mapping.go b/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/redissentinel_mapping.go deleted file mode 100644 index 36a1da85f..000000000 --- a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/redissentinel_mapping.go +++ /dev/null @@ -1,59 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import "k8s.io/apimachinery/pkg/runtime/schema" - -func init() { - RegisterOpsPathMapperToPlugins(&RedisSentinelOpsRequest{}) -} - -type RedisSentinelOpsRequest struct{} - -var _ OpsPathMapper = (*RedisSentinelOpsRequest)(nil) - -func (m *RedisSentinelOpsRequest) HorizontalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.horizontalScaling.replicas": "spec.replicas", - } -} - -func (m *RedisSentinelOpsRequest) VerticalPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.verticalScaling.redissentinel": "spec.podTemplate.spec.resources", - "spec.verticalScaling.exporter": "spec.monitor.prometheus.exporter.resources", - "spec.verticalScaling.coordinator": "spec.coordinator.resources", - } -} - -func (m *RedisSentinelOpsRequest) VolumeExpansionPathMapping() map[OpsReqPath]ReferencedObjPath { - return map[OpsReqPath]ReferencedObjPath{ - "spec.volumeExpansion.redissentinel": "spec.storage.resources.requests.storage", - } -} - -func (m *RedisSentinelOpsRequest) GetReferencedDbObjectPath() []string { - return []string{"spec", "databaseRef", "referencedDB"} -} - -func (m *RedisSentinelOpsRequest) GroupVersionKind() schema.GroupVersionKind { - return schema.GroupVersionKind{ - Group: "ops.kubedb.com", - Version: "v1alpha1", - Kind: "RedisSentinelOpsRequest", - } -} diff --git a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/scale.go b/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/scale.go deleted file mode 100644 index b3862d421..000000000 --- a/vendor/kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1/scale.go +++ /dev/null @@ -1,110 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import ( - "errors" - "fmt" - "strings" - - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func GetScaledObject(opsObj map[string]interface{}) (ScaledObject, error) { - opsPathMapper, err := LoadOpsPathMapper(opsObj) - if err != nil { - return nil, err - } - dbObj, err := extractReferencedObject(opsObj, opsPathMapper.GetReferencedDbObjectPath()...) - if err != nil { - return nil, err - } - - // Merge opsObj scaling information with dbObj - mapping, err := getMapping(opsObj, opsPathMapper) - if err != nil { - return nil, err - } - - for opsPath, dbPath := range mapping { - sop := splitPathToSlice(string(opsPath)) - sdp := splitPathToSlice(string(dbPath)) - - opsVal, found, err := unstructured.NestedFieldCopy(opsObj, sop...) - if err != nil { - return nil, err - } - if found { - if err := unstructured.SetNestedField(dbObj, opsVal, sdp...); err != nil { - return nil, err - } - } - } - - return dbObj, nil -} - -func splitPathToSlice(path string) []string { - return strings.Split(path, ".") -} - -func extractReferencedObject(opsObj map[string]interface{}, refDbPath ...string) (map[string]interface{}, error) { - if len(refDbPath) == 0 { - refDbPath = []string{"spec", "databaseRef", "referencedDB"} - } - dbObj, found, _ := unstructured.NestedMap(opsObj, refDbPath...) - if !found { - return nil, errors.New("referenced db object not found") - } - - return dbObj, nil -} - -func getGVK(obj map[string]interface{}) schema.GroupVersionKind { - var unObj unstructured.Unstructured - unObj.SetUnstructuredContent(obj) - - return unObj.GroupVersionKind() -} - -func getScalingType(opsObj map[string]interface{}) (string, error) { - tp, found, _ := unstructured.NestedString(opsObj, "spec", "type") - if !found { - return "", errors.New("scaling type not found") - } - - return tp, nil -} - -func getMapping(opsObj OpsReqObject, opsMapper OpsPathMapper) (map[OpsReqPath]ReferencedObjPath, error) { - scalingType, err := getScalingType(opsObj) - if err != nil { - return nil, err - } - - switch scalingType { - case ScalingTypeHorizontal: - return opsMapper.HorizontalPathMapping(), nil - case ScalingTypeVertical: - return opsMapper.VerticalPathMapping(), nil - case ScalingTypeVolumeExpansion: - return opsMapper.VolumeExpansionPathMapping(), nil - } - - return nil, fmt.Errorf("scaling type `%s` not supported", scalingType) -} diff --git a/vendor/kmodules.xyz/resource-metrics/template.go b/vendor/kmodules.xyz/resource-metrics/template.go deleted file mode 100644 index 505b4c8ce..000000000 --- a/vendor/kmodules.xyz/resource-metrics/template.go +++ /dev/null @@ -1,194 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 resourcemetrics - -import ( - "fmt" - "html/template" - "reflect" - ttemplate "text/template" - - "kmodules.xyz/resource-metrics/api" - - "gomodules.xyz/encoding/json" - core "k8s.io/api/core/v1" -) - -// TxtFuncMap returns a 'text/template'.FuncMap -func TxtFuncMap() ttemplate.FuncMap { - return ttemplate.FuncMap(GenericFuncMap()) -} - -// HtmlFuncMap returns an 'html/template'.Funcmap -func HtmlFuncMap() template.FuncMap { - return template.FuncMap(GenericFuncMap()) -} - -// GenericFuncMap returns a copy of the basic function map as a map[string]interface{}. -func GenericFuncMap() map[string]interface{} { - return map[string]interface{}{ - "k8s_resource_replicas": tplReplicaFn, - "k8s_resource_replicas_by_roles": tplRoleReplicaFn, - "k8s_resource_mode": tplModeFn, - "k8s_resource_uses_tls": tplUsesTLSFn, - "k8s_total_resource_limits": tplTotalResourceLimitsFn, - "k8s_total_resource_requests": tplTotalResourceRequestsFn, - "k8s_app_resource_limits": tplAppResourceLimitsFn, - "k8s_app_resource_requests": tplAppResourceRequestsFn, - } -} - -func tplReplicaFn(data interface{}) (int64, error) { - obj, err := toObject(data) - if err != nil { - return 0, err - } - - c, err := api.Load(obj) - if err != nil { - return 0, err - } - return c.Replicas(obj) -} - -func tplRoleReplicaFn(data interface{}) (interface{}, error) { - obj, err := toObject(data) - if err != nil { - return nil, err - } - - c, err := api.Load(obj) - if err != nil { - return nil, err - } - replicaList, err := c.RoleReplicas(obj) - if err != nil { - return nil, err - } - - has := func(role api.PodRole) bool { - _, ok := replicaList[role] - return ok - } - if has(api.PodRoleDefault) { - if len(replicaList) == 1 { - return replicaList[api.PodRoleDefault], nil - } else { - // case: elasticsearch - delete(replicaList, api.PodRoleDefault) - return replicaList, nil - } - } else if has(api.PodRoleTotalShard) { - // case: mongodb, redis - delete(replicaList, api.PodRoleTotalShard) - return replicaList, nil - } - return replicaList, nil -} - -func tplModeFn(data interface{}) (string, error) { - obj, err := toObject(data) - if err != nil { - return "", err - } - - c, err := api.Load(obj) - if err != nil { - return "", err - } - return c.Mode(obj) -} - -func tplUsesTLSFn(data interface{}) (bool, error) { - obj, err := toObject(data) - if err != nil { - return false, err - } - - c, err := api.Load(obj) - if err != nil { - return false, err - } - return c.UsesTLS(obj) -} - -func tplTotalResourceLimitsFn(data interface{}) (core.ResourceList, error) { - obj, err := toObject(data) - if err != nil { - return nil, err - } - - c, err := api.Load(obj) - if err != nil { - return nil, err - } - return c.TotalResourceLimits(obj) -} - -func tplTotalResourceRequestsFn(data interface{}) (core.ResourceList, error) { - obj, err := toObject(data) - if err != nil { - return nil, err - } - - c, err := api.Load(obj) - if err != nil { - return nil, err - } - return c.TotalResourceRequests(obj) -} - -func tplAppResourceLimitsFn(data interface{}) (core.ResourceList, error) { - obj, err := toObject(data) - if err != nil { - return nil, err - } - - c, err := api.Load(obj) - if err != nil { - return nil, err - } - return c.AppResourceLimits(obj) -} - -func tplAppResourceRequestsFn(data interface{}) (core.ResourceList, error) { - obj, err := toObject(data) - if err != nil { - return nil, err - } - - c, err := api.Load(obj) - if err != nil { - return nil, err - } - return c.AppResourceRequests(obj) -} - -func toObject(data interface{}) (map[string]interface{}, error) { - var obj map[string]interface{} - if v, ok := data.(map[string]interface{}); ok { - obj = v - } else if str, ok := data.(string); ok { - err := json.Unmarshal([]byte(str), &obj) - if err != nil { - return nil, err - } - } else { - return nil, fmt.Errorf("unknown obj type %v", reflect.TypeOf(data).String()) - } - return obj, nil -} diff --git a/vendor/modules.txt b/vendor/modules.txt index c8aba0506..400ae63b1 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -47,7 +47,6 @@ github.com/Masterminds/sprig/v3 github.com/NYTimes/gziphandler # github.com/PuerkitoBio/purell v1.2.1 ## explicit; go 1.21 -github.com/PuerkitoBio/purell # github.com/antlr/antlr4/runtime/Go/antlr/v4 v4.0.0-20230305170008-8188dc5388df ## explicit; go 1.18 github.com/antlr/antlr4/runtime/Go/antlr/v4 @@ -126,27 +125,11 @@ github.com/cenkalti/backoff/v4 github.com/cespare/xxhash/v2 # github.com/cloudevents/sdk-go/v2 v2.15.2 ## explicit; go 1.18 -github.com/cloudevents/sdk-go/v2 -github.com/cloudevents/sdk-go/v2/binding -github.com/cloudevents/sdk-go/v2/binding/format -github.com/cloudevents/sdk-go/v2/binding/spec -github.com/cloudevents/sdk-go/v2/client -github.com/cloudevents/sdk-go/v2/context -github.com/cloudevents/sdk-go/v2/event -github.com/cloudevents/sdk-go/v2/event/datacodec -github.com/cloudevents/sdk-go/v2/event/datacodec/json -github.com/cloudevents/sdk-go/v2/event/datacodec/text -github.com/cloudevents/sdk-go/v2/event/datacodec/xml -github.com/cloudevents/sdk-go/v2/protocol -github.com/cloudevents/sdk-go/v2/protocol/http -github.com/cloudevents/sdk-go/v2/types # github.com/codegangsta/inject v0.0.0-20150114235600-33e0aa1cb7c0 ## explicit github.com/codegangsta/inject # github.com/containerd/stargz-snapshotter/estargz v0.14.3 ## explicit; go 1.19 -github.com/containerd/stargz-snapshotter/estargz -github.com/containerd/stargz-snapshotter/estargz/errorutil # github.com/coreos/go-semver v0.3.1 ## explicit; go 1.8 github.com/coreos/go-semver/semver @@ -165,20 +148,12 @@ github.com/davecgh/go-spew/spew github.com/distribution/reference # github.com/docker/cli v24.0.9+incompatible ## explicit -github.com/docker/cli/cli/config -github.com/docker/cli/cli/config/configfile -github.com/docker/cli/cli/config/credentials -github.com/docker/cli/cli/config/types # github.com/docker/distribution v2.8.2+incompatible ## explicit -github.com/docker/distribution/registry/client/auth/challenge # github.com/docker/docker v24.0.9+incompatible ## explicit -github.com/docker/docker/pkg/homedir # github.com/docker/docker-credential-helpers v0.7.0 ## explicit; go 1.18 -github.com/docker/docker-credential-helpers/client -github.com/docker/docker-credential-helpers/credentials # github.com/dustin/go-humanize v1.0.1 ## explicit; go 1.16 github.com/dustin/go-humanize @@ -300,34 +275,6 @@ github.com/google/go-cmp/cmp/internal/function github.com/google/go-cmp/cmp/internal/value # github.com/google/go-containerregistry v0.19.0 ## explicit; go 1.18 -github.com/google/go-containerregistry/internal/and -github.com/google/go-containerregistry/internal/compression -github.com/google/go-containerregistry/internal/estargz -github.com/google/go-containerregistry/internal/gzip -github.com/google/go-containerregistry/internal/redact -github.com/google/go-containerregistry/internal/retry -github.com/google/go-containerregistry/internal/retry/wait -github.com/google/go-containerregistry/internal/verify -github.com/google/go-containerregistry/internal/windows -github.com/google/go-containerregistry/internal/zstd -github.com/google/go-containerregistry/pkg/authn -github.com/google/go-containerregistry/pkg/compression -github.com/google/go-containerregistry/pkg/crane -github.com/google/go-containerregistry/pkg/legacy -github.com/google/go-containerregistry/pkg/legacy/tarball -github.com/google/go-containerregistry/pkg/logs -github.com/google/go-containerregistry/pkg/name -github.com/google/go-containerregistry/pkg/v1 -github.com/google/go-containerregistry/pkg/v1/empty -github.com/google/go-containerregistry/pkg/v1/layout -github.com/google/go-containerregistry/pkg/v1/match -github.com/google/go-containerregistry/pkg/v1/mutate -github.com/google/go-containerregistry/pkg/v1/partial -github.com/google/go-containerregistry/pkg/v1/remote -github.com/google/go-containerregistry/pkg/v1/remote/transport -github.com/google/go-containerregistry/pkg/v1/stream -github.com/google/go-containerregistry/pkg/v1/tarball -github.com/google/go-containerregistry/pkg/v1/types # github.com/google/gofuzz v1.2.0 ## explicit; go 1.12 github.com/google/gofuzz @@ -403,7 +350,6 @@ github.com/inconshreveable/mousetrap github.com/jmespath/go-jmespath # github.com/jonboulle/clockwork v0.4.0 ## explicit; go 1.15 -github.com/jonboulle/clockwork # github.com/josharian/intern v1.0.0 ## explicit; go 1.5 github.com/josharian/intern @@ -412,14 +358,6 @@ github.com/josharian/intern github.com/json-iterator/go # github.com/klauspost/compress v1.17.2 ## explicit; go 1.18 -github.com/klauspost/compress -github.com/klauspost/compress/flate -github.com/klauspost/compress/fse -github.com/klauspost/compress/huff0 -github.com/klauspost/compress/internal/cpuinfo -github.com/klauspost/compress/internal/snapref -github.com/klauspost/compress/zstd -github.com/klauspost/compress/zstd/internal/xxhash # github.com/klauspost/cpuid/v2 v2.0.9 ## explicit; go 1.13 github.com/klauspost/cpuid/v2 @@ -450,7 +388,6 @@ github.com/matttproud/golang_protobuf_extensions/v2/pbutil github.com/mitchellh/copystructure # github.com/mitchellh/go-homedir v1.1.0 ## explicit -github.com/mitchellh/go-homedir # github.com/mitchellh/mapstructure v1.5.0 ## explicit; go 1.14 github.com/mitchellh/mapstructure @@ -482,16 +419,10 @@ github.com/munnerz/goautoneg github.com/mxk/go-flowrate/flowrate # github.com/nats-io/nats.go v1.33.1 ## explicit; go 1.20 -github.com/nats-io/nats.go -github.com/nats-io/nats.go/encoders/builtin -github.com/nats-io/nats.go/internal/parser -github.com/nats-io/nats.go/util # github.com/nats-io/nkeys v0.4.7 ## explicit; go 1.20 -github.com/nats-io/nkeys # github.com/nats-io/nuid v1.0.1 ## explicit -github.com/nats-io/nuid # github.com/ncw/swift v1.0.49 ## explicit github.com/ncw/swift @@ -534,8 +465,6 @@ github.com/onsi/gomega/types github.com/opencontainers/go-digest # github.com/opencontainers/image-spec v1.1.0-rc3 ## explicit; go 1.18 -github.com/opencontainers/image-spec/specs-go -github.com/opencontainers/image-spec/specs-go/v1 # github.com/peterbourgon/diskv v2.0.1+incompatible ## explicit github.com/peterbourgon/diskv @@ -576,7 +505,6 @@ github.com/sergi/go-diff/diffmatchpatch github.com/shopspring/decimal # github.com/sirupsen/logrus v1.9.3 ## explicit; go 1.13 -github.com/sirupsen/logrus # github.com/spf13/cast v1.5.0 ## explicit; go 1.18 github.com/spf13/cast @@ -592,7 +520,6 @@ github.com/spf13/pflag github.com/stoewer/go-strcase # github.com/vbatts/tar-split v0.11.3 ## explicit; go 1.15 -github.com/vbatts/tar-split/archive/tar # github.com/xlab/treeprint v1.2.0 ## explicit; go 1.13 github.com/xlab/treeprint @@ -608,24 +535,6 @@ github.com/yudai/golcs github.com/zeebo/xxh3 # go.bytebuilders.dev/audit v0.0.33 ## explicit; go 1.22.0 -go.bytebuilders.dev/audit/api/v1 -go.bytebuilders.dev/audit/lib -# go.bytebuilders.dev/license-proxyserver v0.0.9 -## explicit; go 1.22.0 -go.bytebuilders.dev/license-proxyserver/apis/proxyserver -go.bytebuilders.dev/license-proxyserver/apis/proxyserver/v1alpha1 -go.bytebuilders.dev/license-proxyserver/client/clientset/versioned -go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/scheme -go.bytebuilders.dev/license-proxyserver/client/clientset/versioned/typed/proxyserver/v1alpha1 -# go.bytebuilders.dev/license-verifier v0.14.0 -## explicit; go 1.21 -go.bytebuilders.dev/license-verifier -go.bytebuilders.dev/license-verifier/apis/licenses -go.bytebuilders.dev/license-verifier/apis/licenses/v1alpha1 -go.bytebuilders.dev/license-verifier/info -# go.bytebuilders.dev/license-verifier/kubernetes v0.14.0 -## explicit; go 1.21.5 -go.bytebuilders.dev/license-verifier/kubernetes # go.etcd.io/etcd/api/v3 v3.5.10 ## explicit; go 1.20 go.etcd.io/etcd/api/v3/authpb @@ -762,19 +671,14 @@ gocloud.dev/internal/retry # golang.org/x/crypto v0.21.0 ## explicit; go 1.18 golang.org/x/crypto/bcrypt -golang.org/x/crypto/blake2b golang.org/x/crypto/blowfish golang.org/x/crypto/chacha20 golang.org/x/crypto/chacha20poly1305 golang.org/x/crypto/cryptobyte golang.org/x/crypto/cryptobyte/asn1 -golang.org/x/crypto/curve25519 -golang.org/x/crypto/curve25519/internal/field -golang.org/x/crypto/ed25519 golang.org/x/crypto/hkdf golang.org/x/crypto/internal/alias golang.org/x/crypto/internal/poly1305 -golang.org/x/crypto/nacl/box golang.org/x/crypto/nacl/secretbox golang.org/x/crypto/pbkdf2 golang.org/x/crypto/pkcs12 @@ -819,7 +723,6 @@ golang.org/x/sync/singleflight # golang.org/x/sys v0.18.0 ## explicit; go 1.18 golang.org/x/sys/cpu -golang.org/x/sys/execabs golang.org/x/sys/plan9 golang.org/x/sys/unix golang.org/x/sys/windows @@ -881,7 +784,6 @@ gomodules.xyz/cert/certstore gomodules.xyz/clock # gomodules.xyz/counter v0.0.1 ## explicit; go 1.21.5 -gomodules.xyz/counter/hourly # gomodules.xyz/encoding v0.0.7 ## explicit; go 1.17 gomodules.xyz/encoding/json @@ -1840,7 +1742,6 @@ kmodules.xyz/client-go/dynamic kmodules.xyz/client-go/meta kmodules.xyz/client-go/rbac/v1 kmodules.xyz/client-go/tools/clientcmd -kmodules.xyz/client-go/tools/clusterid kmodules.xyz/client-go/tools/exec kmodules.xyz/client-go/tools/portforward kmodules.xyz/client-go/tools/queue @@ -1869,10 +1770,8 @@ kmodules.xyz/custom-resources/client/clientset/versioned/typed/appcatalog/v1alph kmodules.xyz/custom-resources/client/clientset/versioned/typed/auditor/v1alpha1 kmodules.xyz/custom-resources/client/clientset/versioned/typed/metrics/v1alpha1 kmodules.xyz/custom-resources/crds -kmodules.xyz/custom-resources/util/siteinfo # kmodules.xyz/go-containerregistry v0.0.12 ## explicit; go 1.21.5 -kmodules.xyz/go-containerregistry/name # kmodules.xyz/objectstore-api v0.29.1 ## explicit; go 1.21 kmodules.xyz/objectstore-api/api/v1 @@ -1880,7 +1779,6 @@ kmodules.xyz/objectstore-api/osm # kmodules.xyz/offshoot-api v0.29.0 ## explicit; go 1.21.5 kmodules.xyz/offshoot-api/api/v1 -kmodules.xyz/offshoot-api/api/v2 kmodules.xyz/offshoot-api/util # kmodules.xyz/openshift v0.29.0 ## explicit; go 1.21.5 @@ -1912,19 +1810,8 @@ kmodules.xyz/prober/probe/http kmodules.xyz/prober/probe/tcp # kmodules.xyz/resource-metadata v0.18.2 ## explicit; go 1.22.0 -kmodules.xyz/resource-metadata/apis/core/v1alpha1 -kmodules.xyz/resource-metadata/apis/shared # kmodules.xyz/resource-metrics v0.29.1 ## explicit; go 1.21.5 -kmodules.xyz/resource-metrics -kmodules.xyz/resource-metrics/api -kmodules.xyz/resource-metrics/apps/v1 -kmodules.xyz/resource-metrics/batch/v1 -kmodules.xyz/resource-metrics/batch/v1beta1 -kmodules.xyz/resource-metrics/core/v1 -kmodules.xyz/resource-metrics/kubedb.com/v1alpha2 -kmodules.xyz/resource-metrics/kubevault.com/v1alpha2 -kmodules.xyz/resource-metrics/ops.kubedb.com/v1alpha1 # kmodules.xyz/webhook-runtime v0.29.1 ## explicit; go 1.21.5 kmodules.xyz/webhook-runtime/admission @@ -1943,7 +1830,6 @@ sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/common/metrics sigs.k8s.io/apiserver-network-proxy/konnectivity-client/proto/client # sigs.k8s.io/cli-utils v0.34.0 ## explicit; go 1.18 -sigs.k8s.io/cli-utils/pkg/kstatus/status # sigs.k8s.io/controller-runtime v0.17.2 => github.com/kmodules/controller-runtime v0.16.1-0.20240128092212-43c4e15c56b1 ## explicit; go 1.21 sigs.k8s.io/controller-runtime @@ -2127,9 +2013,6 @@ stash.appscode.dev/apimachinery/pkg/restic stash.appscode.dev/apimachinery/pkg/util # x-helm.dev/apimachinery v0.0.16 ## explicit; go 1.21.5 -x-helm.dev/apimachinery/apis/releases/v1alpha1 -x-helm.dev/apimachinery/apis/shared -x-helm.dev/apimachinery/crds # github.com/Masterminds/sprig/v3 => github.com/gomodules/sprig/v3 v3.2.3-0.20220405051441-0a8a99bac1b8 # sigs.k8s.io/controller-runtime => github.com/kmodules/controller-runtime v0.16.1-0.20240128092212-43c4e15c56b1 # github.com/imdario/mergo => github.com/imdario/mergo v0.3.6 diff --git a/vendor/sigs.k8s.io/cli-utils/LICENSE b/vendor/sigs.k8s.io/cli-utils/LICENSE deleted file mode 100644 index 8dada3eda..000000000 --- a/vendor/sigs.k8s.io/cli-utils/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - 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 "{}" - 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 - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - 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. diff --git a/vendor/sigs.k8s.io/cli-utils/LICENSE_TEMPLATE b/vendor/sigs.k8s.io/cli-utils/LICENSE_TEMPLATE deleted file mode 100644 index 0c2b3b655..000000000 --- a/vendor/sigs.k8s.io/cli-utils/LICENSE_TEMPLATE +++ /dev/null @@ -1,2 +0,0 @@ -Copyright {{.Year}} {{.Holder}} -SPDX-License-Identifier: Apache-2.0 diff --git a/vendor/sigs.k8s.io/cli-utils/LICENSE_TEMPLATE_GO b/vendor/sigs.k8s.io/cli-utils/LICENSE_TEMPLATE_GO deleted file mode 100644 index ef790b661..000000000 --- a/vendor/sigs.k8s.io/cli-utils/LICENSE_TEMPLATE_GO +++ /dev/null @@ -1,2 +0,0 @@ -// Copyright YEAR The Kubernetes Authors. -// SPDX-License-Identifier: Apache-2.0 diff --git a/vendor/sigs.k8s.io/cli-utils/pkg/kstatus/status/core.go b/vendor/sigs.k8s.io/cli-utils/pkg/kstatus/status/core.go deleted file mode 100644 index 4cd6704e4..000000000 --- a/vendor/sigs.k8s.io/cli-utils/pkg/kstatus/status/core.go +++ /dev/null @@ -1,627 +0,0 @@ -// Copyright 2019 The Kubernetes Authors. -// SPDX-License-Identifier: Apache-2.0 - -package status - -import ( - "fmt" - "math" - "strings" - "time" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" -) - -// GetConditionsFn defines the signature for functions to compute the -// status of a built-in resource. -type GetConditionsFn func(*unstructured.Unstructured) (*Result, error) - -// legacyTypes defines the mapping from GroupKind to a function that can -// compute the status for the given resource. -var legacyTypes = map[string]GetConditionsFn{ - "Service": serviceConditions, - "Pod": podConditions, - "Secret": alwaysReady, - "PersistentVolumeClaim": pvcConditions, - "apps/StatefulSet": stsConditions, - "apps/DaemonSet": daemonsetConditions, - "extensions/DaemonSet": daemonsetConditions, - "apps/Deployment": deploymentConditions, - "extensions/Deployment": deploymentConditions, - "apps/ReplicaSet": replicasetConditions, - "extensions/ReplicaSet": replicasetConditions, - "policy/PodDisruptionBudget": pdbConditions, - "batch/CronJob": alwaysReady, - "ConfigMap": alwaysReady, - "batch/Job": jobConditions, - "apiextensions.k8s.io/CustomResourceDefinition": crdConditions, -} - -const ( - tooFewReady = "LessReady" - tooFewAvailable = "LessAvailable" - tooFewUpdated = "LessUpdated" - tooFewReplicas = "LessReplicas" - extraPods = "ExtraPods" - - onDeleteUpdateStrategy = "OnDelete" - - // How long a pod can be unscheduled before it is reported as - // unschedulable. - ScheduleWindow = 15 * time.Second -) - -// GetLegacyConditionsFn returns a function that can compute the status for the -// given resource, or nil if the resource type is not known. -func GetLegacyConditionsFn(u *unstructured.Unstructured) GetConditionsFn { - gvk := u.GroupVersionKind() - g := gvk.Group - k := gvk.Kind - key := g + "/" + k - if g == "" { - key = k - } - return legacyTypes[key] -} - -// alwaysReady Used for resources that are always ready -func alwaysReady(u *unstructured.Unstructured) (*Result, error) { - return &Result{ - Status: CurrentStatus, - Message: "Resource is always ready", - Conditions: []Condition{}, - }, nil -} - -// stsConditions return standardized Conditions for Statefulset -// -// StatefulSet does define the .status.conditions property, but the controller never -// actually sets any Conditions. Thus, status must be computed only based on the other -// properties under .status. We don't have any way to find out if a reconcile for a -// StatefulSet has failed. -func stsConditions(u *unstructured.Unstructured) (*Result, error) { - obj := u.UnstructuredContent() - - // updateStrategy==ondelete is a user managed statefulset. - updateStrategy := GetStringField(obj, ".spec.updateStrategy.type", "") - if updateStrategy == onDeleteUpdateStrategy { - return &Result{ - Status: CurrentStatus, - Message: "StatefulSet is using the ondelete update strategy", - Conditions: []Condition{}, - }, nil - } - - // Replicas - specReplicas := GetIntField(obj, ".spec.replicas", 1) - readyReplicas := GetIntField(obj, ".status.readyReplicas", 0) - currentReplicas := GetIntField(obj, ".status.currentReplicas", 0) - updatedReplicas := GetIntField(obj, ".status.updatedReplicas", 0) - statusReplicas := GetIntField(obj, ".status.replicas", 0) - partition := GetIntField(obj, ".spec.updateStrategy.rollingUpdate.partition", -1) - - if specReplicas > statusReplicas { - message := fmt.Sprintf("Replicas: %d/%d", statusReplicas, specReplicas) - return newInProgressStatus(tooFewReplicas, message), nil - } - - if specReplicas > readyReplicas { - message := fmt.Sprintf("Ready: %d/%d", readyReplicas, specReplicas) - return newInProgressStatus(tooFewReady, message), nil - } - - if statusReplicas > specReplicas { - message := fmt.Sprintf("Pending termination: %d", statusReplicas-specReplicas) - return newInProgressStatus(extraPods, message), nil - } - - // https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#partitions - if partition != -1 { - if updatedReplicas < (specReplicas - partition) { - message := fmt.Sprintf("updated: %d/%d", updatedReplicas, specReplicas-partition) - return newInProgressStatus("PartitionRollout", message), nil - } - // Partition case All ok - return &Result{ - Status: CurrentStatus, - Message: fmt.Sprintf("Partition rollout complete. updated: %d", updatedReplicas), - Conditions: []Condition{}, - }, nil - } - - if specReplicas > currentReplicas { - message := fmt.Sprintf("current: %d/%d", currentReplicas, specReplicas) - return newInProgressStatus("LessCurrent", message), nil - } - - // Revision - currentRevision := GetStringField(obj, ".status.currentRevision", "") - updatedRevision := GetStringField(obj, ".status.updateRevision", "") - if currentRevision != updatedRevision { - message := "Waiting for updated revision to match current" - return newInProgressStatus("RevisionMismatch", message), nil - } - - // All ok - return &Result{ - Status: CurrentStatus, - Message: fmt.Sprintf("All replicas scheduled as expected. Replicas: %d", statusReplicas), - Conditions: []Condition{}, - }, nil -} - -// deploymentConditions return standardized Conditions for Deployment. -// -// For Deployments, we look at .status.conditions as well as the other properties -// under .status. Status will be Failed if the progress deadline has been exceeded. -func deploymentConditions(u *unstructured.Unstructured) (*Result, error) { - obj := u.UnstructuredContent() - - progressing := false - - // Check if progressDeadlineSeconds is set. If not, the controller will not set - // the `Progressing` condition, so it will always consider a deployment to be - // progressing. The use of math.MaxInt32 is due to special handling in the - // controller: - // https://github.com/kubernetes/kubernetes/blob/a3ccea9d8743f2ff82e41b6c2af6dc2c41dc7b10/pkg/controller/deployment/util/deployment_util.go#L886 - progressDeadline := GetIntField(obj, ".spec.progressDeadlineSeconds", math.MaxInt32) - if progressDeadline == math.MaxInt32 { - progressing = true - } - - available := false - - objc, err := GetObjectWithConditions(obj) - if err != nil { - return nil, err - } - - for _, c := range objc.Status.Conditions { - switch c.Type { - case "Progressing": // appsv1.DeploymentProgressing: - // https://github.com/kubernetes/kubernetes/blob/a3ccea9d8743f2ff82e41b6c2af6dc2c41dc7b10/pkg/controller/deployment/progress.go#L52 - if c.Reason == "ProgressDeadlineExceeded" { - return &Result{ - Status: FailedStatus, - Message: "Progress deadline exceeded", - Conditions: []Condition{{ConditionStalled, corev1.ConditionTrue, c.Reason, c.Message}}, - }, nil - } - if c.Status == corev1.ConditionTrue && c.Reason == "NewReplicaSetAvailable" { - progressing = true - } - case "Available": // appsv1.DeploymentAvailable: - if c.Status == corev1.ConditionTrue { - available = true - } - } - } - - // replicas - specReplicas := GetIntField(obj, ".spec.replicas", 1) // Controller uses 1 as default if not specified. - statusReplicas := GetIntField(obj, ".status.replicas", 0) - updatedReplicas := GetIntField(obj, ".status.updatedReplicas", 0) - readyReplicas := GetIntField(obj, ".status.readyReplicas", 0) - availableReplicas := GetIntField(obj, ".status.availableReplicas", 0) - - // TODO spec.replicas zero case ?? - - if specReplicas > statusReplicas { - message := fmt.Sprintf("Replicas: %d/%d", statusReplicas, specReplicas) - return newInProgressStatus(tooFewReplicas, message), nil - } - - if specReplicas > updatedReplicas { - message := fmt.Sprintf("Updated: %d/%d", updatedReplicas, specReplicas) - return newInProgressStatus(tooFewUpdated, message), nil - } - - if statusReplicas > specReplicas { - message := fmt.Sprintf("Pending termination: %d", statusReplicas-specReplicas) - return newInProgressStatus(extraPods, message), nil - } - - if updatedReplicas > availableReplicas { - message := fmt.Sprintf("Available: %d/%d", availableReplicas, updatedReplicas) - return newInProgressStatus(tooFewAvailable, message), nil - } - - if specReplicas > readyReplicas { - message := fmt.Sprintf("Ready: %d/%d", readyReplicas, specReplicas) - return newInProgressStatus(tooFewReady, message), nil - } - - // check conditions - if !progressing { - message := "ReplicaSet not Available" - return newInProgressStatus("ReplicaSetNotAvailable", message), nil - } - if !available { - message := "Deployment not Available" - return newInProgressStatus("DeploymentNotAvailable", message), nil - } - // All ok - return &Result{ - Status: CurrentStatus, - Message: fmt.Sprintf("Deployment is available. Replicas: %d", statusReplicas), - Conditions: []Condition{}, - }, nil -} - -// replicasetConditions return standardized Conditions for Replicaset -func replicasetConditions(u *unstructured.Unstructured) (*Result, error) { - obj := u.UnstructuredContent() - - // Conditions - objc, err := GetObjectWithConditions(obj) - if err != nil { - return nil, err - } - - for _, c := range objc.Status.Conditions { - // https://github.com/kubernetes/kubernetes/blob/a3ccea9d8743f2ff82e41b6c2af6dc2c41dc7b10/pkg/controller/replicaset/replica_set_utils.go - if c.Type == "ReplicaFailure" && c.Status == corev1.ConditionTrue { - message := "Replica Failure condition. Check Pods" - return newInProgressStatus("ReplicaFailure", message), nil - } - } - - // Replicas - specReplicas := GetIntField(obj, ".spec.replicas", 1) // Controller uses 1 as default if not specified. - statusReplicas := GetIntField(obj, ".status.replicas", 0) - readyReplicas := GetIntField(obj, ".status.readyReplicas", 0) - availableReplicas := GetIntField(obj, ".status.availableReplicas", 0) - fullyLabelledReplicas := GetIntField(obj, ".status.fullyLabeledReplicas", 0) - - if specReplicas > fullyLabelledReplicas { - message := fmt.Sprintf("Labelled: %d/%d", fullyLabelledReplicas, specReplicas) - return newInProgressStatus("LessLabelled", message), nil - } - - if specReplicas > availableReplicas { - message := fmt.Sprintf("Available: %d/%d", availableReplicas, specReplicas) - return newInProgressStatus(tooFewAvailable, message), nil - } - - if specReplicas > readyReplicas { - message := fmt.Sprintf("Ready: %d/%d", readyReplicas, specReplicas) - return newInProgressStatus(tooFewReady, message), nil - } - - if statusReplicas > specReplicas { - message := fmt.Sprintf("Pending termination: %d", statusReplicas-specReplicas) - return newInProgressStatus(extraPods, message), nil - } - // All ok - return &Result{ - Status: CurrentStatus, - Message: fmt.Sprintf("ReplicaSet is available. Replicas: %d", statusReplicas), - Conditions: []Condition{}, - }, nil -} - -// daemonsetConditions return standardized Conditions for DaemonSet -func daemonsetConditions(u *unstructured.Unstructured) (*Result, error) { - // We check that the latest generation is equal to observed generation as - // part of checking generic properties but in that case, we are lenient and - // skip the check if those fields are unset. For daemonset, we know that if - // the daemonset controller has acted on a resource, these fields would not - // be unset. So, we ensure that here. - res, err := checkGenerationSet(u) - if err != nil || res != nil { - return res, err - } - - obj := u.UnstructuredContent() - - // replicas - desiredNumberScheduled := GetIntField(obj, ".status.desiredNumberScheduled", -1) - currentNumberScheduled := GetIntField(obj, ".status.currentNumberScheduled", 0) - updatedNumberScheduled := GetIntField(obj, ".status.updatedNumberScheduled", 0) - numberAvailable := GetIntField(obj, ".status.numberAvailable", 0) - numberReady := GetIntField(obj, ".status.numberReady", 0) - - if desiredNumberScheduled == -1 { - message := "Missing .status.desiredNumberScheduled" - return newInProgressStatus("NoDesiredNumber", message), nil - } - - if desiredNumberScheduled > currentNumberScheduled { - message := fmt.Sprintf("Current: %d/%d", currentNumberScheduled, desiredNumberScheduled) - return newInProgressStatus("LessCurrent", message), nil - } - - if desiredNumberScheduled > updatedNumberScheduled { - message := fmt.Sprintf("Updated: %d/%d", updatedNumberScheduled, desiredNumberScheduled) - return newInProgressStatus(tooFewUpdated, message), nil - } - - if desiredNumberScheduled > numberAvailable { - message := fmt.Sprintf("Available: %d/%d", numberAvailable, desiredNumberScheduled) - return newInProgressStatus(tooFewAvailable, message), nil - } - - if desiredNumberScheduled > numberReady { - message := fmt.Sprintf("Ready: %d/%d", numberReady, desiredNumberScheduled) - return newInProgressStatus(tooFewReady, message), nil - } - - // All ok - return &Result{ - Status: CurrentStatus, - Message: fmt.Sprintf("All replicas scheduled as expected. Replicas: %d", desiredNumberScheduled), - Conditions: []Condition{}, - }, nil -} - -// checkGenerationSet checks that the metadata.generation and -// status.observedGeneration fields are set. -func checkGenerationSet(u *unstructured.Unstructured) (*Result, error) { - _, found, err := unstructured.NestedInt64(u.Object, "metadata", "generation") - if err != nil { - return nil, fmt.Errorf("looking up metadata.generation from resource: %w", err) - } - if !found { - message := fmt.Sprintf("%s metadata.generation not found", u.GetKind()) - return &Result{ - Status: InProgressStatus, - Message: message, - Conditions: []Condition{newReconcilingCondition("NoGeneration", message)}, - }, nil - } - - _, found, err = unstructured.NestedInt64(u.Object, "status", "observedGeneration") - if err != nil { - return nil, fmt.Errorf("looking up status.observedGeneration from resource: %w", err) - } - if !found { - message := fmt.Sprintf("%s status.observedGeneration not found", u.GetKind()) - return &Result{ - Status: InProgressStatus, - Message: message, - Conditions: []Condition{newReconcilingCondition("NoObservedGeneration", message)}, - }, nil - } - - return nil, nil -} - -// pvcConditions return standardized Conditions for PVC -func pvcConditions(u *unstructured.Unstructured) (*Result, error) { - obj := u.UnstructuredContent() - - phase := GetStringField(obj, ".status.phase", "unknown") - if phase != "Bound" { // corev1.ClaimBound - message := fmt.Sprintf("PVC is not Bound. phase: %s", phase) - return newInProgressStatus("NotBound", message), nil - } - // All ok - return &Result{ - Status: CurrentStatus, - Message: "PVC is Bound", - Conditions: []Condition{}, - }, nil -} - -// podConditions return standardized Conditions for Pod -func podConditions(u *unstructured.Unstructured) (*Result, error) { - obj := u.UnstructuredContent() - objc, err := GetObjectWithConditions(obj) - if err != nil { - return nil, err - } - phase := GetStringField(obj, ".status.phase", "") - - switch phase { - case "Succeeded": - return &Result{ - Status: CurrentStatus, - Message: "Pod has completed successfully", - Conditions: []Condition{}, - }, nil - case "Failed": - return &Result{ - Status: CurrentStatus, - Message: "Pod has completed, but not successfully", - Conditions: []Condition{}, - }, nil - case "Running": - if hasConditionWithStatus(objc.Status.Conditions, "Ready", corev1.ConditionTrue) { - return &Result{ - Status: CurrentStatus, - Message: "Pod is Ready", - Conditions: []Condition{}, - }, nil - } - - containerNames, isCrashLooping, err := getCrashLoopingContainers(obj) - if err != nil { - return nil, err - } - if isCrashLooping { - return newFailedStatus("ContainerCrashLooping", - fmt.Sprintf("Containers in CrashLoop state: %s", strings.Join(containerNames, ","))), nil - } - - return newInProgressStatus("PodRunningNotReady", "Pod is running but is not Ready"), nil - case "Pending": - c, found := getConditionWithStatus(objc.Status.Conditions, "PodScheduled", corev1.ConditionFalse) - if found && c.Reason == "Unschedulable" { - if time.Now().Add(-ScheduleWindow).Before(u.GetCreationTimestamp().Time) { - // We give the pod 15 seconds to be scheduled before we report it - // as unschedulable. - return newInProgressStatus("PodNotScheduled", "Pod has not been scheduled"), nil - } - return newFailedStatus("PodUnschedulable", "Pod could not be scheduled"), nil - } - return newInProgressStatus("PodPending", "Pod is in the Pending phase"), nil - default: - // If the controller hasn't observed the pod yet, there is no phase. We consider this as it - // still being in progress. - if phase == "" { - return newInProgressStatus("PodNotObserved", "Pod phase not available"), nil - } - return nil, fmt.Errorf("unknown phase %s", phase) - } -} - -func getCrashLoopingContainers(obj map[string]interface{}) ([]string, bool, error) { - var containerNames []string - css, found, err := unstructured.NestedSlice(obj, "status", "containerStatuses") - if !found || err != nil { - return containerNames, found, err - } - for _, item := range css { - cs := item.(map[string]interface{}) - n, found := cs["name"] - if !found { - continue - } - name := n.(string) - s, found := cs["state"] - if !found { - continue - } - state := s.(map[string]interface{}) - - ws, found := state["waiting"] - if !found { - continue - } - waitingState := ws.(map[string]interface{}) - - r, found := waitingState["reason"] - if !found { - continue - } - reason := r.(string) - if reason == "CrashLoopBackOff" { - containerNames = append(containerNames, name) - } - } - if len(containerNames) > 0 { - return containerNames, true, nil - } - return containerNames, false, nil -} - -// pdbConditions computes the status for PodDisruptionBudgets. A PDB -// is currently considered Current if the disruption controller has -// observed the latest version of the PDB resource and has computed -// the AllowedDisruptions. PDBs do have ObservedGeneration in the -// Status object, so if this function gets called we know that -// the controller has observed the latest changes. -// The disruption controller does not set any conditions if -// computing the AllowedDisruptions fails (and there are many ways -// it can fail), but there is PR against OSS Kubernetes to address -// this: https://github.com/kubernetes/kubernetes/pull/86929 -func pdbConditions(_ *unstructured.Unstructured) (*Result, error) { - // All ok - return &Result{ - Status: CurrentStatus, - Message: "AllowedDisruptions has been computed.", - Conditions: []Condition{}, - }, nil -} - -// jobConditions return standardized Conditions for Job -// -// A job will have the InProgress status until it starts running. Then it will have the Current -// status while the job is running and after it has been completed successfully. It -// will have the Failed status if it the job has failed. -func jobConditions(u *unstructured.Unstructured) (*Result, error) { - obj := u.UnstructuredContent() - - parallelism := GetIntField(obj, ".spec.parallelism", 1) - completions := GetIntField(obj, ".spec.completions", parallelism) - succeeded := GetIntField(obj, ".status.succeeded", 0) - active := GetIntField(obj, ".status.active", 0) - failed := GetIntField(obj, ".status.failed", 0) - starttime := GetStringField(obj, ".status.startTime", "") - - // Conditions - // https://github.com/kubernetes/kubernetes/blob/master/pkg/controller/job/utils.go#L24 - objc, err := GetObjectWithConditions(obj) - if err != nil { - return nil, err - } - for _, c := range objc.Status.Conditions { - switch c.Type { - case "Complete": - if c.Status == corev1.ConditionTrue { - message := fmt.Sprintf("Job Completed. succeeded: %d/%d", succeeded, completions) - return &Result{ - Status: CurrentStatus, - Message: message, - Conditions: []Condition{}, - }, nil - } - case "Failed": - if c.Status == corev1.ConditionTrue { - return newFailedStatus("JobFailed", - fmt.Sprintf("Job Failed. failed: %d/%d", failed, completions)), nil - } - } - } - - // replicas - if starttime == "" { - message := "Job not started" - return newInProgressStatus("JobNotStarted", message), nil - } - return &Result{ - Status: CurrentStatus, - Message: fmt.Sprintf("Job in progress. success:%d, active: %d, failed: %d", succeeded, active, failed), - Conditions: []Condition{}, - }, nil -} - -// serviceConditions return standardized Conditions for Service -func serviceConditions(u *unstructured.Unstructured) (*Result, error) { - obj := u.UnstructuredContent() - - specType := GetStringField(obj, ".spec.type", "ClusterIP") - specClusterIP := GetStringField(obj, ".spec.clusterIP", "") - - if specType == "LoadBalancer" { - if specClusterIP == "" { - message := "ClusterIP not set. Service type: LoadBalancer" - return newInProgressStatus("NoIPAssigned", message), nil - } - } - - return &Result{ - Status: CurrentStatus, - Message: "Service is ready", - Conditions: []Condition{}, - }, nil -} - -func crdConditions(u *unstructured.Unstructured) (*Result, error) { - obj := u.UnstructuredContent() - - objc, err := GetObjectWithConditions(obj) - if err != nil { - return nil, err - } - - for _, c := range objc.Status.Conditions { - if c.Type == "NamesAccepted" && c.Status == corev1.ConditionFalse { - return newFailedStatus(c.Reason, c.Message), nil - } - if c.Type == "Established" { - if c.Status == corev1.ConditionFalse && c.Reason != "Installing" { - return newFailedStatus(c.Reason, c.Message), nil - } - if c.Status == corev1.ConditionTrue { - return &Result{ - Status: CurrentStatus, - Message: "CRD is established", - Conditions: []Condition{}, - }, nil - } - } - } - return newInProgressStatus("Installing", "Install in progress"), nil -} diff --git a/vendor/sigs.k8s.io/cli-utils/pkg/kstatus/status/doc.go b/vendor/sigs.k8s.io/cli-utils/pkg/kstatus/status/doc.go deleted file mode 100644 index 0506896f5..000000000 --- a/vendor/sigs.k8s.io/cli-utils/pkg/kstatus/status/doc.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2019 The Kubernetes Authors. -// SPDX-License-Identifier: Apache-2.0 - -// Package kstatus contains functionality for computing the status -// of Kubernetes resources. -// -// The statuses defined in this package are: -// - InProgress -// - Current -// - Failed -// - Terminating -// - NotFound -// - Unknown -// -// Computing the status of a resources can be done by calling the -// Compute function in the status package. -// -// import ( -// "sigs.k8s.io/cli-utils/pkg/kstatus/status" -// ) -// -// res, err := status.Compute(resource) -// -// The package also defines a set of new conditions: -// - InProgress -// - Failed -// -// These conditions have been chosen to follow the -// "abnormal-true" pattern where conditions should be set to true -// for error/abnormal conditions and the absence of a condition means -// things are normal. -// -// The Augment function augments any unstructured resource with -// the standard conditions described above. The values of -// these conditions are decided based on other status information -// available in the resources. -// -// import ( -// "sigs.k8s.io/cli-utils/pkg/kstatus/status -// ) -// -// err := status.Augment(resource) -package status diff --git a/vendor/sigs.k8s.io/cli-utils/pkg/kstatus/status/generic.go b/vendor/sigs.k8s.io/cli-utils/pkg/kstatus/status/generic.go deleted file mode 100644 index 6213d1b96..000000000 --- a/vendor/sigs.k8s.io/cli-utils/pkg/kstatus/status/generic.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2019 The Kubernetes Authors. -// SPDX-License-Identifier: Apache-2.0 - -package status - -import ( - "fmt" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" -) - -// checkGenericProperties looks at the properties that are available on -// all or most of the Kubernetes resources. If a decision can be made based -// on this information, there is no need to look at the resource-specidic -// rules. -// This also checks for the presence of the conditions defined in this package. -// If any of these are set on the resource, a decision is made solely based -// on this and none of the resource specific rules will be used. The goal here -// is that if controllers, built-in or custom, use these conditions, we can easily -// find status of resources. -func checkGenericProperties(u *unstructured.Unstructured) (*Result, error) { - obj := u.UnstructuredContent() - - // Check if the resource is scheduled for deletion - deletionTimestamp, found, err := unstructured.NestedString(obj, "metadata", "deletionTimestamp") - if err != nil { - return nil, fmt.Errorf("looking up metadata.deletionTimestamp from resource: %w", err) - } - if found && deletionTimestamp != "" { - return &Result{ - Status: TerminatingStatus, - Message: "Resource scheduled for deletion", - Conditions: []Condition{}, - }, nil - } - - res, err := checkGeneration(u) - if res != nil || err != nil { - return res, err - } - - // Check if the resource has any of the standard conditions. If so, we just use them - // and no need to look at anything else. - objWithConditions, err := GetObjectWithConditions(obj) - if err != nil { - return nil, err - } - - for _, cond := range objWithConditions.Status.Conditions { - if cond.Type == string(ConditionReconciling) && cond.Status == corev1.ConditionTrue { - return newInProgressStatus(cond.Reason, cond.Message), nil - } - if cond.Type == string(ConditionStalled) && cond.Status == corev1.ConditionTrue { - return &Result{ - Status: FailedStatus, - Message: cond.Message, - Conditions: []Condition{ - { - Type: ConditionStalled, - Status: corev1.ConditionTrue, - Reason: cond.Reason, - Message: cond.Message, - }, - }, - }, nil - } - } - - return nil, nil -} - -func checkGeneration(u *unstructured.Unstructured) (*Result, error) { - // ensure that the meta generation is observed - generation, found, err := unstructured.NestedInt64(u.Object, "metadata", "generation") - if err != nil { - return nil, fmt.Errorf("looking up metadata.generation from resource: %w", err) - } - if !found { - return nil, nil - } - observedGeneration, found, err := unstructured.NestedInt64(u.Object, "status", "observedGeneration") - if err != nil { - return nil, fmt.Errorf("looking up status.observedGeneration from resource: %w", err) - } - if found { - // Resource does not have this field, so we can't do this check. - // TODO(mortent): Verify behavior of not set vs does not exist. - if observedGeneration != generation { - message := fmt.Sprintf("%s generation is %d, but latest observed generation is %d", u.GetKind(), generation, observedGeneration) - return &Result{ - Status: InProgressStatus, - Message: message, - Conditions: []Condition{newReconcilingCondition("LatestGenerationNotObserved", message)}, - }, nil - } - } - return nil, nil -} diff --git a/vendor/sigs.k8s.io/cli-utils/pkg/kstatus/status/status.go b/vendor/sigs.k8s.io/cli-utils/pkg/kstatus/status/status.go deleted file mode 100644 index a8f2e28de..000000000 --- a/vendor/sigs.k8s.io/cli-utils/pkg/kstatus/status/status.go +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright 2019 The Kubernetes Authors. -// SPDX-License-Identifier: Apache-2.0 - -package status - -import ( - "errors" - "fmt" - "time" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" -) - -const ( - // The set of standard conditions defined in this package. These follow the "abnormality-true" - // convention where conditions should have a true value for abnormal/error situations and the absence - // of a condition should be interpreted as a false value, i.e. everything is normal. - ConditionStalled ConditionType = "Stalled" - ConditionReconciling ConditionType = "Reconciling" - - // The set of status conditions which can be assigned to resources. - InProgressStatus Status = "InProgress" - FailedStatus Status = "Failed" - CurrentStatus Status = "Current" - TerminatingStatus Status = "Terminating" - NotFoundStatus Status = "NotFound" - UnknownStatus Status = "Unknown" -) - -var ( - Statuses = []Status{InProgressStatus, FailedStatus, CurrentStatus, TerminatingStatus, UnknownStatus} -) - -// ConditionType defines the set of condition types allowed inside a Condition struct. -type ConditionType string - -// String returns the ConditionType as a string. -func (c ConditionType) String() string { - return string(c) -} - -// Status defines the set of statuses a resource can have. -type Status string - -// String returns the status as a string. -func (s Status) String() string { - return string(s) -} - -// StatusFromString turns a string into a Status. Will panic if the provided string is -// not a valid status. -func FromStringOrDie(text string) Status { - s := Status(text) - for _, r := range Statuses { - if s == r { - return s - } - } - panic(fmt.Errorf("string has invalid status: %s", s)) -} - -// Result contains the results of a call to compute the status of -// a resource. -type Result struct { - // Status - Status Status - // Message - Message string - // Conditions list of extracted conditions from Resource - Conditions []Condition -} - -// Condition defines the general format for conditions on Kubernetes resources. -// In practice, each kubernetes resource defines their own format for conditions, but -// most (maybe all) follows this structure. -type Condition struct { - // Type condition type - Type ConditionType `json:"type,omitempty"` - // Status String that describes the condition status - Status corev1.ConditionStatus `json:"status,omitempty"` - // Reason one work CamelCase reason - Reason string `json:"reason,omitempty"` - // Message Human readable reason string - Message string `json:"message,omitempty"` -} - -// Compute finds the status of a given unstructured resource. It does not -// fetch the state of the resource from a cluster, so the provided unstructured -// must have the complete state, including status. -// -// The returned result contains the status of the resource, which will be -// one of -// - InProgress -// - Current -// - Failed -// - Terminating -// -// It also contains a message that provides more information on why -// the resource has the given status. Finally, the result also contains -// a list of standard resources that would belong on the given resource. -func Compute(u *unstructured.Unstructured) (*Result, error) { - res, err := checkGenericProperties(u) - if err != nil { - return nil, err - } - - // If res is not nil, it means the generic checks was able to determine - // the status of the resource. We don't need to check the type-specific - // rules. - if res != nil { - return res, nil - } - - fn := GetLegacyConditionsFn(u) - if fn != nil { - return fn(u) - } - - // If neither the generic properties of the resource-specific rules - // can determine status, we do one last check to see if the resource - // does expose a Ready condition. Ready conditions do not adhere - // to the Kubernetes design recommendations, but they are pretty widely - // used. - res, err = checkReadyCondition(u) - if res != nil || err != nil { - return res, err - } - - // The resource is not one of the built-in types with specific - // rules and we were unable to make a decision based on the - // generic rules. In this case we assume that the absence of any known - // conditions means the resource is current. - return &Result{ - Status: CurrentStatus, - Message: "Resource is current", - Conditions: []Condition{}, - }, err -} - -// checkReadyCondition checks if a resource has a Ready condition, and -// if so, it will use the value of this condition to determine the -// status. -// There are a few challenges with this: -// - If a resource doesn't set the Ready condition until it is True, -// the library have no way of telling whether the resource is using the -// Ready condition, so it will fall back to the strategy for unknown -// resources, which is to assume they are always reconciled. -// - If the library sees the resource before the controller has had -// a chance to update the conditions, it also will not realize the -// resource use the Ready condition. -// - There is no way to determine if a resource with the Ready condition -// set to False is making progress or is doomed. -func checkReadyCondition(u *unstructured.Unstructured) (*Result, error) { - objWithConditions, err := GetObjectWithConditions(u.Object) - if err != nil { - return nil, err - } - - for _, cond := range objWithConditions.Status.Conditions { - if cond.Type != "Ready" { - continue - } - switch cond.Status { - case corev1.ConditionTrue: - return &Result{ - Status: CurrentStatus, - Message: "Resource is Ready", - Conditions: []Condition{}, - }, nil - case corev1.ConditionFalse: - return newInProgressStatus(cond.Reason, cond.Message), nil - case corev1.ConditionUnknown: - // For now we just treat an unknown condition value as - // InProgress. We should consider if there are better ways - // to handle it. - return newInProgressStatus(cond.Reason, cond.Message), nil - default: - // Do nothing in this case. - } - } - return nil, nil -} - -// Augment takes a resource and augments the resource with the -// standard status conditions. -func Augment(u *unstructured.Unstructured) error { - res, err := Compute(u) - if err != nil { - return err - } - - conditions, found, err := unstructured.NestedSlice(u.Object, "status", "conditions") - if err != nil { - return err - } - - if !found { - conditions = make([]interface{}, 0) - } - - currentTime := time.Now().UTC().Format(time.RFC3339) - - for _, resCondition := range res.Conditions { - present := false - for _, c := range conditions { - condition, ok := c.(map[string]interface{}) - if !ok { - return errors.New("condition does not have the expected structure") - } - conditionType, ok := condition["type"].(string) - if !ok { - return errors.New("condition type does not have the expected type") - } - if conditionType == string(resCondition.Type) { - conditionStatus, ok := condition["status"].(string) - if !ok { - return errors.New("condition status does not have the expected type") - } - if conditionStatus != string(resCondition.Status) { - condition["lastTransitionTime"] = currentTime - } - condition["status"] = string(resCondition.Status) - condition["lastUpdateTime"] = currentTime - condition["reason"] = resCondition.Reason - condition["message"] = resCondition.Message - present = true - } - } - if !present { - conditions = append(conditions, map[string]interface{}{ - "lastTransitionTime": currentTime, - "lastUpdateTime": currentTime, - "message": resCondition.Message, - "reason": resCondition.Reason, - "status": string(resCondition.Status), - "type": string(resCondition.Type), - }) - } - } - return unstructured.SetNestedSlice(u.Object, conditions, "status", "conditions") -} diff --git a/vendor/sigs.k8s.io/cli-utils/pkg/kstatus/status/util.go b/vendor/sigs.k8s.io/cli-utils/pkg/kstatus/status/util.go deleted file mode 100644 index b22152cc7..000000000 --- a/vendor/sigs.k8s.io/cli-utils/pkg/kstatus/status/util.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2019 The Kubernetes Authors. -// SPDX-License-Identifier: Apache-2.0 - -package status - -import ( - "strings" - - corev1 "k8s.io/api/core/v1" - apiunstructured "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" -) - -// newReconcilingCondition creates an reconciling condition with the given -// reason and message. -func newReconcilingCondition(reason, message string) Condition { - return Condition{ - Type: ConditionReconciling, - Status: corev1.ConditionTrue, - Reason: reason, - Message: message, - } -} - -func newStalledCondition(reason, message string) Condition { - return Condition{ - Type: ConditionStalled, - Status: corev1.ConditionTrue, - Reason: reason, - Message: message, - } -} - -// newInProgressStatus creates a status Result with the InProgress status -// and an InProgress condition. -func newInProgressStatus(reason, message string) *Result { - return &Result{ - Status: InProgressStatus, - Message: message, - Conditions: []Condition{newReconcilingCondition(reason, message)}, - } -} - -func newFailedStatus(reason, message string) *Result { - return &Result{ - Status: FailedStatus, - Message: message, - Conditions: []Condition{newStalledCondition(reason, message)}, - } -} - -// ObjWithConditions Represent meta object with status.condition array -type ObjWithConditions struct { - // Status as expected to be present in most compliant kubernetes resources - Status ConditionStatus `json:"status" yaml:"status"` -} - -// ConditionStatus represent status with condition array -type ConditionStatus struct { - // Array of Conditions as expected to be present in kubernetes resources - Conditions []BasicCondition `json:"conditions" yaml:"conditions"` -} - -// BasicCondition fields that are expected in a condition -type BasicCondition struct { - // Type Condition type - Type string `json:"type" yaml:"type"` - // Status is one of True,False,Unknown - Status corev1.ConditionStatus `json:"status" yaml:"status"` - // Reason simple single word reason in CamleCase - // +optional - Reason string `json:"reason,omitempty" yaml:"reason"` - // Message human readable reason - // +optional - Message string `json:"message,omitempty" yaml:"message"` -} - -// GetObjectWithConditions return typed object -func GetObjectWithConditions(in map[string]interface{}) (*ObjWithConditions, error) { - var out = new(ObjWithConditions) - err := runtime.DefaultUnstructuredConverter.FromUnstructured(in, out) - if err != nil { - return nil, err - } - return out, nil -} - -func hasConditionWithStatus(conditions []BasicCondition, conditionType string, status corev1.ConditionStatus) bool { - _, found := getConditionWithStatus(conditions, conditionType, status) - return found -} - -func getConditionWithStatus(conditions []BasicCondition, conditionType string, status corev1.ConditionStatus) (BasicCondition, bool) { - for _, c := range conditions { - if c.Type == conditionType && c.Status == status { - return c, true - } - } - return BasicCondition{}, false -} - -// GetStringField return field as string defaulting to value if not found -func GetStringField(obj map[string]interface{}, fieldPath string, defaultValue string) string { - var rv = defaultValue - - fields := strings.Split(fieldPath, ".") - if fields[0] == "" { - fields = fields[1:] - } - - val, found, err := apiunstructured.NestedFieldNoCopy(obj, fields...) - if !found || err != nil { - return rv - } - - if v, ok := val.(string); ok { - return v - } - return rv -} - -// GetIntField return field as string defaulting to value if not found -func GetIntField(obj map[string]interface{}, fieldPath string, defaultValue int) int { - fields := strings.Split(fieldPath, ".") - if fields[0] == "" { - fields = fields[1:] - } - - val, found, err := apiunstructured.NestedFieldNoCopy(obj, fields...) - if !found || err != nil { - return defaultValue - } - - switch v := val.(type) { - case int: - return v - case int32: - return int(v) - case int64: - return int(v) - } - return defaultValue -} diff --git a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/application_types.go b/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/application_types.go deleted file mode 100644 index 187482ae0..000000000 --- a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/application_types.go +++ /dev/null @@ -1,38 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -type ApplicationPackage struct { - metav1.TypeMeta `json:",inline"` - Bundle *ChartSourceRef `json:"bundle,omitempty"` - Chart ChartSourceRef `json:"chart"` - Channel ChannelType `json:"channel"` -} - -type ChannelType string - -const ( - RapidChannel ChannelType = "Rapid" - RegularChannel ChannelType = "Regular" - StableChannel ChannelType = "Stable" -) diff --git a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/bundle_helpers.go b/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/bundle_helpers.go deleted file mode 100644 index 15fd7fd41..000000000 --- a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/bundle_helpers.go +++ /dev/null @@ -1,27 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import ( - "x-helm.dev/apimachinery/crds" - - "kmodules.xyz/client-go/apiextensions" -) - -func (_ Bundle) CustomResourceDefinition() *apiextensions.CustomResourceDefinition { - return crds.MustCustomResourceDefinition(GroupVersion.WithResource(ResourceBundles)) -} diff --git a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/bundle_types.go b/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/bundle_types.go deleted file mode 100644 index 03c3b34d2..000000000 --- a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/bundle_types.go +++ /dev/null @@ -1,133 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - kmapi "kmodules.xyz/client-go/api/v1" -) - -const ( - ResourceKindBundle = "Bundle" - ResourceBundle = "bundle" - ResourceBundles = "bundles" -) - -//+kubebuilder:object:root=true -//+kubebuilder:subresource:status -//+kubebuilder:resource:scope=Cluster - -// Bundle is the Schema for the bundles API -type Bundle struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec BundleSpec `json:"spec,omitempty"` - Status BundleStatus `json:"status,omitempty"` -} - -type BundleSpec struct { - PackageDescriptor `json:",inline"` - DisplayName string `json:"displayName,omitempty"` - Features []Feature `json:"features,omitempty"` - Namespace string `json:"namespace"` - Packages []PackageRef `json:"packages"` -} - -type PackageRef struct { - Chart *ChartOption `json:"chart,omitempty"` - Bundle *BundleOption `json:"bundle,omitempty"` - OneOf *OneOfBundleOption `json:"oneOf,omitempty"` -} - -type OneOfBundleOption struct { - Description string `json:"description"` - Bundles []*BundleOption `json:"bundles,omitempty"` -} - -type ChartRef struct { - Name string `json:"name"` - SourceRef kmapi.TypedObjectReference `json:"sourceRef"` -} - -type SelectionMode string - -type ChartOption struct { - ChartRef `json:",inline"` - Features []string `json:"features,omitempty"` - Namespace string `json:"namespace,omitempty"` - Versions []VersionDetail `json:"versions"` - MultiSelect bool `json:"multiSelect,omitempty"` - Required bool `json:"required,omitempty"` -} - -type BundleRef struct { - Name string `json:"name"` - SourceRef kmapi.TypedObjectReference `json:"sourceRef"` -} - -type BundleOption struct { - BundleRef `json:",inline"` - Version string `json:"version"` -} - -type VersionOption struct { - Version string `json:"version"` - Selected bool `json:"selected,omitempty"` - ValuesFile string `json:"valuesFile,omitempty"` - // RFC 6902 compatible json patch. ref: http://jsonpatch.com - // +optional - // +kubebuilder:pruning:PreserveUnknownFields - ValuesPatch *runtime.RawExtension `json:"valuesPatch,omitempty"` -} - -type VersionDetail struct { - VersionOption `json:",inline"` - Resources *ResourceDefinitions `json:"resources,omitempty"` - WaitFors []WaitFlags `json:"waitFors,omitempty"` - // jsonpatch path in Values where the license key will be set using replace operation, if defined. - // See: http://jsonpatch.com - LicenseKeyPath string `json:"licenseKeyPath,omitempty"` -} - -//+kubebuilder:object:root=true - -// BundleList contains a list of Bundle -type BundleList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []Bundle `json:"items"` -} - -func init() { - SchemeBuilder.Register(&Bundle{}, &BundleList{}) -} - -type BundleStatus struct { - // ObservedGeneration is the most recent generation observed for this resource. It corresponds to the - // resource's generation, which is updated on mutation by the API Server. - // +optional - ObservedGeneration int64 `json:"observedGeneration,omitempty"` -} - -type InstallOptions struct { - ChartRef `json:",inline"` - Version string `json:"version"` - ReleaseName string `json:"releaseName"` - Namespace string `json:"namespace"` -} diff --git a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/bundle_ui_types.go b/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/bundle_ui_types.go deleted file mode 100644 index 12326e108..000000000 --- a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/bundle_ui_types.go +++ /dev/null @@ -1,57 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type BundleView struct { - metav1.TypeMeta `json:",inline"` - BundleOptionView `json:",inline"` - LicenseKey string `json:"licenseKey,omitempty"` -} - -type BundleOptionView struct { - PackageMeta `json:",inline"` - DisplayName string `json:"displayName"` - Features []Feature `json:"features,omitempty"` - Packages []PackageCard `json:"packages"` -} - -type PackageCard struct { - Chart *ChartCard `json:"chart,omitempty"` - Bundle *BundleOptionView `json:"bundle,omitempty"` - OneOf *OneOfBundleOptionView `json:"oneOf,omitempty"` -} - -type OneOfBundleOptionView struct { - Description string `json:"description"` - Bundles []*BundleOptionView `json:"bundles,omitempty"` -} - -type ChartCard struct { - ChartRef `json:",inline"` - PackageDescriptor `json:",inline"` - Features []string `json:"features,omitempty"` - Namespace string `json:"namespace,omitempty"` - Versions []VersionOption `json:"versions"` - MultiSelect bool `json:"multiSelect,omitempty"` - Required bool `json:"required,omitempty"` - Selected bool `json:"selected,omitempty"` -} diff --git a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/editor_types.go b/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/editor_types.go deleted file mode 100644 index 1569922eb..000000000 --- a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/editor_types.go +++ /dev/null @@ -1,159 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - kmapi "kmodules.xyz/client-go/api/v1" -) - -type Metadata struct { - Resource kmapi.ResourceID `json:"resource"` - Release ObjectMeta `json:"release"` -} - -type MetadataFlat struct { - kmapi.ResourceID `json:",inline"` - ReleaseName string `json:"releaseName"` - Namespace string `json:"namespace"` -} - -type ObjectMeta struct { - Name string `json:"name"` - Namespace string `json:"namespace"` -} - -type ModelMetadata struct { - Metadata `json:"metadata,omitempty"` -} - -type Model struct { - Metadata `json:"metadata,omitempty"` - Resources *unstructured.Unstructured `json:"resources,omitempty"` -} - -type ChartOrder struct { - ChartSourceFlatRef `json:",inline"` - - ReleaseName string `json:"releaseName,omitempty"` - Namespace string `json:"namespace,omitempty"` - Values *unstructured.Unstructured `json:"values,omitempty"` -} - -type EditorParameters struct { - ValuesFile string `json:"valuesFile,omitempty"` - // RFC 6902 compatible json patch. ref: http://jsonpatch.com - // +optional - // +kubebuilder:pruning:PreserveUnknownFields - ValuesPatch *runtime.RawExtension `json:"valuesPatch,omitempty"` -} - -type EditResourceOrder struct { - Group string `json:"group,omitempty"` - Version string `json:"version,omitempty"` - Resource string `json:"resource,omitempty"` - - ReleaseName string `json:"releaseName,omitempty"` - Namespace string `json:"namespace,omitempty"` - Values string `json:"values,omitempty"` -} - -type BucketFile struct { - // URL of the file in bucket - URL string `json:"url"` - // Bucket key for this file - Key string `json:"key"` - Filename string `json:"filename"` - Data []byte `json:"data"` -} - -type BucketObject struct { - // URL of the file in bucket - URL string `json:"url,omitempty"` - // Bucket key for this file - Key string `json:"key,omitempty"` - ResourceObject `json:",inline"` -} - -type BucketFileRef struct { - // URL of the file in bucket - URL string `json:"url"` - // Bucket key for this file - Key string `json:"key"` -} - -type ChartTemplate struct { - ChartSourceRef `json:",inline"` - ReleaseName string `json:"releaseName,omitempty"` - Namespace string `json:"namespace,omitempty"` - CRDs []BucketObject `json:"crds,omitempty"` - Manifest *BucketFileRef `json:"manifest,omitempty"` - Resources []ResourceObject `json:"resources,omitempty"` -} - -type BucketFileOutput struct { - // URL of the file in bucket - URL string `json:"url,omitempty"` - // Bucket key for this file - Key string `json:"key,omitempty"` - Filename string `json:"filename,omitempty"` - Data string `json:"data,omitempty"` -} - -type ChartTemplateOutput struct { - ChartSourceRef `json:",inline"` - ReleaseName string `json:"releaseName,omitempty"` - Namespace string `json:"namespace,omitempty"` - CRDs []BucketFileOutput `json:"crds,omitempty"` - Manifest *BucketFileRef `json:"manifest,omitempty"` - Resources []ResourceFile `json:"resources,omitempty"` -} - -type EditorTemplate struct { - Manifest []byte `json:"manifest,omitempty"` - Values *unstructured.Unstructured `json:"values,omitempty"` - Resources []ResourceObject `json:"resources,omitempty"` -} - -type ResourceOutput struct { - CRDs []ResourceFile `json:"crds,omitempty"` - Resources []ResourceFile `json:"resources,omitempty"` -} - -type ObjectModel struct { - Key string `json:"key"` - Object *unstructured.Unstructured `json:"object"` -} - -type ResourceObject struct { - Filename string `json:"filename,omitempty"` - Key string `json:"key,omitempty"` - Data *unstructured.Unstructured `json:"data,omitempty"` -} - -type ResourceFile struct { - Filename string `json:"filename,omitempty"` - Key string `json:"key,omitempty"` - Data string `json:"data,omitempty"` -} - -type SimpleValue struct { - metav1.TypeMeta `json:",inline,omitempty"` - ObjectMeta ObjectMeta `json:"metadata,omitempty"` -} diff --git a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/groupversion_info.go b/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/groupversion_info.go deleted file mode 100644 index c03881298..000000000 --- a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/groupversion_info.go +++ /dev/null @@ -1,36 +0,0 @@ -/* -Copyright 2023. - -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 v1alpha1 contains API Schema definitions for the releases v1alpha1 API group -// +kubebuilder:object:generate=true -// +groupName=releases.x-helm.dev -package v1alpha1 - -import ( - "k8s.io/apimachinery/pkg/runtime/schema" - "sigs.k8s.io/controller-runtime/pkg/scheme" -) - -var ( - // GroupVersion is group version used to register these objects - GroupVersion = schema.GroupVersion{Group: "releases.x-helm.dev", Version: "v1alpha1"} - - // SchemeBuilder is used to add go types to the GroupVersionKind scheme - SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} - - // AddToScheme adds the types in this group-version to the given scheme. - AddToScheme = SchemeBuilder.AddToScheme -) diff --git a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/helpers.go b/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/helpers.go deleted file mode 100644 index 50dcc2375..000000000 --- a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/helpers.go +++ /dev/null @@ -1,46 +0,0 @@ -package v1alpha1 - -import ( - kmapi "kmodules.xyz/client-go/api/v1" -) - -func (ref *ChartSourceRef) SetDefaults() *ChartSourceRef { - if ref.SourceRef.APIGroup == "" { - ref.SourceRef.APIGroup = SourceGroupHelmRepository - } - if ref.SourceRef.Kind == "" { - ref.SourceRef.Kind = SourceKindHelmRepository - } else if ref.SourceRef.Kind == SourceKindLegacy || - ref.SourceRef.Kind == SourceKindLocal || - ref.SourceRef.Kind == SourceKindEmbed { - ref.SourceRef.APIGroup = SourceGroupLegacy - } - return ref -} - -func (ref *ChartSourceFlatRef) FromAPIObject(obj ChartSourceRef) *ChartSourceFlatRef { - obj.SetDefaults() - - ref.Name = obj.Name - ref.Version = obj.Version - ref.SourceAPIGroup = obj.SourceRef.APIGroup - ref.SourceKind = obj.SourceRef.Kind - ref.SourceNamespace = obj.SourceRef.Namespace - ref.SourceName = obj.SourceRef.Name - return ref -} - -func (ref *ChartSourceFlatRef) ToAPIObject() ChartSourceRef { - obj := ChartSourceRef{ - Name: ref.Name, - Version: ref.Version, - SourceRef: kmapi.TypedObjectReference{ - APIGroup: ref.SourceAPIGroup, - Kind: ref.SourceKind, - Namespace: ref.SourceNamespace, - Name: ref.SourceName, - }, - } - obj.SetDefaults() - return obj -} diff --git a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/hub.go b/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/hub.go deleted file mode 100644 index fd5a337e7..000000000 --- a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/hub.go +++ /dev/null @@ -1,29 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import "x-helm.dev/apimachinery/apis/shared" - -type Hub struct { - Repositories []Repository `json:"repositories"` -} - -type Repository struct { - Name string `json:"name"` - URL string `json:"url"` - Maintainers []shared.ContactData `json:"maintainers,omitempty"` -} diff --git a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/order_helpers.go b/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/order_helpers.go deleted file mode 100644 index 6d06e44f8..000000000 --- a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/order_helpers.go +++ /dev/null @@ -1,27 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import ( - "x-helm.dev/apimachinery/crds" - - "kmodules.xyz/client-go/apiextensions" -) - -func (_ Order) CustomResourceDefinition() *apiextensions.CustomResourceDefinition { - return crds.MustCustomResourceDefinition(GroupVersion.WithResource(ResourceOrders)) -} diff --git a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/order_types.go b/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/order_types.go deleted file mode 100644 index c54bf8d8d..000000000 --- a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/order_types.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" -) - -const ( - ResourceKindOrder = "Order" - ResourceOrder = "order" - ResourceOrders = "orders" -) - -//+kubebuilder:object:root=true -//+kubebuilder:subresource:status -//+kubebuilder:resource:scope=Cluster - -// Order is the Schema for the orders API -type Order struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec OrderSpec `json:"spec,omitempty"` - Status OrderStatus `json:"status,omitempty"` -} - -type OrderSpec struct { - Packages []PackageSelection `json:"items"` - // KubeVersion is a SemVer constraint specifying the version of Kubernetes required. - KubeVersion string `json:"kubeVersion,omitempty"` -} - -type PackageSelection struct { - Chart *ChartSelection `json:"chart,omitempty"` -} - -type ChartSelection struct { - ChartRef `json:",inline"` - Version string `json:"version"` - ReleaseName string `json:"releaseName"` - Namespace string `json:"namespace"` - - // Bundle points to the parent bundle which was used to install this, if any. - // If the chart was installed directly it will be unset. - Bundle *ChartSourceRef `json:"bundle,omitempty"` - - ValuesFile string `json:"valuesFile,omitempty"` - // RFC 6902 compatible json patch. ref: http://jsonpatch.com - // +optional - // +kubebuilder:pruning:PreserveUnknownFields - ValuesPatch *runtime.RawExtension `json:"valuesPatch,omitempty"` - Resources *ResourceDefinitions `json:"resources,omitempty"` - WaitFors []WaitFlags `json:"waitFors,omitempty"` -} - -//+kubebuilder:object:root=true - -// OrderList contains a list of Order -type OrderList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []Order `json:"items"` -} - -func init() { - SchemeBuilder.Register(&Order{}, &OrderList{}) -} - -type OrderStatus struct { - // ObservedGeneration is the most recent generation observed for this resource. It corresponds to the - // resource's generation, which is updated on mutation by the API Server. - // +optional - ObservedGeneration int64 `json:"observedGeneration,omitempty"` -} diff --git a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/package_ui_types.go b/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/package_ui_types.go deleted file mode 100644 index c9571c8fb..000000000 --- a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/package_ui_types.go +++ /dev/null @@ -1,74 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import ( - crdv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - "x-helm.dev/apimachinery/apis/shared" -) - -type PackageDescriptor struct { - // Type is the type of the application (e.g. WordPress, MySQL, Cassandra). - Type string `json:"type,omitempty"` - - // Description is a brief string description of the Application. - Description string `json:"description,omitempty"` - - // Icons is an optional list of icons for an application. Icon information includes the source, size, - // and mime type. - Icons []shared.ImageSpec `json:"icons,omitempty"` - - // Maintainers is an optional list of maintainers of the application. The maintainers in this list maintain the - // the source code, images, and package for the application. - Maintainers []shared.ContactData `json:"maintainers,omitempty"` - - // Keywords is an optional list of key words associated with the application (e.g. MySQL, RDBMS, database). - Keywords []string `json:"keywords,omitempty"` - - // Links are a list of descriptive URLs intended to be used to surface additional documentation, dashboards, etc. - Links []shared.Link `json:"links,omitempty"` - - // Notes contain a human readable snippets intended as a quick start for the users of the Application. - // CommonMark markdown syntax may be used for rich text representation. - Notes string `json:"notes,omitempty"` -} - -type PackageMeta struct { - PackageDescriptor `json:",inline"` - - ChartSourceRef `json:",inline"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type PackageView struct { - metav1.TypeMeta `json:",inline"` - PackageMeta `json:",inline"` - - // Chart value files - ValuesFiles []ValuesFile `json:"valuesFiles,omitempty"` - - // openAPIV3Schema describes the schema used for validation and pruning of the Values file. - // +optional - OpenAPIV3Schema *crdv1.JSONSchemaProps `json:"openAPIV3Schema,omitempty"` -} - -type ValuesFile struct { - Filename string `json:"filename"` - Values *runtime.RawExtension `json:"values,omitempty"` -} diff --git a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/types.go b/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/types.go deleted file mode 100644 index ce9106141..000000000 --- a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/types.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - kmapi "kmodules.xyz/client-go/api/v1" -) - -const ( - SourceGroupHelmRepository = "source.toolkit.fluxcd.io" - SourceKindHelmRepository = "HelmRepository" - - SourceGroupLegacy = "charts.x-helm.dev" - SourceKindLegacy = "Legacy" - SourceKindLocal = "Local" - SourceKindEmbed = "Embed" -) - -// ChartSourceRef references to a single version of a Chart -type ChartSourceRef struct { - Name string `json:"name"` - Version string `json:"version"` - SourceRef kmapi.TypedObjectReference `json:"sourceRef"` -} - -type ChartSourceFlatRef struct { - Name string `json:"name"` - // Version is an optional version indicator for the Application. - // +optional - Version string `json:"version,omitempty"` - SourceAPIGroup string `json:"sourceApiGroup,omitempty"` - SourceKind string `json:"sourceKind"` - SourceNamespace string `json:"sourceNamespace,omitempty"` - SourceName string `json:"sourceName"` -} - -type Feature struct { - Trait string `json:"trait"` - Value string `json:"value"` -} - -type ResourceDefinitions struct { - Owned []metav1.GroupVersionResource `json:"owned"` - Required []metav1.GroupVersionResource `json:"required"` -} - -// wait ([-f FILENAME] | resource.group/resource.name | resource.group [(-l label | --all)]) [--for=delete|--for condition=available] - -type WaitFlags struct { - Resource metav1.GroupResource `json:"resource"` - Labels *metav1.LabelSelector `json:"labels"` - All bool `json:"all"` - Timeout metav1.Duration `json:"timeout"` - ForCondition string `json:"for"` -} diff --git a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/zz_generated.deepcopy.go b/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/zz_generated.deepcopy.go deleted file mode 100644 index 8d23f074e..000000000 --- a/vendor/x-helm.dev/apimachinery/apis/releases/v1alpha1/zz_generated.deepcopy.go +++ /dev/null @@ -1,1287 +0,0 @@ -//go:build !ignore_autogenerated - -/* -Copyright 2023. - -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. -*/ - -// Code generated by controller-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "x-helm.dev/apimachinery/apis/shared" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ApplicationPackage) DeepCopyInto(out *ApplicationPackage) { - *out = *in - out.TypeMeta = in.TypeMeta - if in.Bundle != nil { - in, out := &in.Bundle, &out.Bundle - *out = new(ChartSourceRef) - **out = **in - } - out.Chart = in.Chart -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApplicationPackage. -func (in *ApplicationPackage) DeepCopy() *ApplicationPackage { - if in == nil { - return nil - } - out := new(ApplicationPackage) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ApplicationPackage) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BucketFile) DeepCopyInto(out *BucketFile) { - *out = *in - if in.Data != nil { - in, out := &in.Data, &out.Data - *out = make([]byte, len(*in)) - copy(*out, *in) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BucketFile. -func (in *BucketFile) DeepCopy() *BucketFile { - if in == nil { - return nil - } - out := new(BucketFile) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BucketFileOutput) DeepCopyInto(out *BucketFileOutput) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BucketFileOutput. -func (in *BucketFileOutput) DeepCopy() *BucketFileOutput { - if in == nil { - return nil - } - out := new(BucketFileOutput) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BucketFileRef) DeepCopyInto(out *BucketFileRef) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BucketFileRef. -func (in *BucketFileRef) DeepCopy() *BucketFileRef { - if in == nil { - return nil - } - out := new(BucketFileRef) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BucketObject) DeepCopyInto(out *BucketObject) { - *out = *in - in.ResourceObject.DeepCopyInto(&out.ResourceObject) -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BucketObject. -func (in *BucketObject) DeepCopy() *BucketObject { - if in == nil { - return nil - } - out := new(BucketObject) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Bundle) DeepCopyInto(out *Bundle) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - out.Status = in.Status -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Bundle. -func (in *Bundle) DeepCopy() *Bundle { - if in == nil { - return nil - } - out := new(Bundle) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Bundle) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BundleList) DeepCopyInto(out *BundleList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Bundle, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BundleList. -func (in *BundleList) DeepCopy() *BundleList { - if in == nil { - return nil - } - out := new(BundleList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *BundleList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BundleOption) DeepCopyInto(out *BundleOption) { - *out = *in - out.BundleRef = in.BundleRef -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BundleOption. -func (in *BundleOption) DeepCopy() *BundleOption { - if in == nil { - return nil - } - out := new(BundleOption) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BundleOptionView) DeepCopyInto(out *BundleOptionView) { - *out = *in - in.PackageMeta.DeepCopyInto(&out.PackageMeta) - if in.Features != nil { - in, out := &in.Features, &out.Features - *out = make([]Feature, len(*in)) - copy(*out, *in) - } - if in.Packages != nil { - in, out := &in.Packages, &out.Packages - *out = make([]PackageCard, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BundleOptionView. -func (in *BundleOptionView) DeepCopy() *BundleOptionView { - if in == nil { - return nil - } - out := new(BundleOptionView) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BundleRef) DeepCopyInto(out *BundleRef) { - *out = *in - out.SourceRef = in.SourceRef -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BundleRef. -func (in *BundleRef) DeepCopy() *BundleRef { - if in == nil { - return nil - } - out := new(BundleRef) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BundleSpec) DeepCopyInto(out *BundleSpec) { - *out = *in - in.PackageDescriptor.DeepCopyInto(&out.PackageDescriptor) - if in.Features != nil { - in, out := &in.Features, &out.Features - *out = make([]Feature, len(*in)) - copy(*out, *in) - } - if in.Packages != nil { - in, out := &in.Packages, &out.Packages - *out = make([]PackageRef, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BundleSpec. -func (in *BundleSpec) DeepCopy() *BundleSpec { - if in == nil { - return nil - } - out := new(BundleSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BundleStatus) DeepCopyInto(out *BundleStatus) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BundleStatus. -func (in *BundleStatus) DeepCopy() *BundleStatus { - if in == nil { - return nil - } - out := new(BundleStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BundleView) DeepCopyInto(out *BundleView) { - *out = *in - out.TypeMeta = in.TypeMeta - in.BundleOptionView.DeepCopyInto(&out.BundleOptionView) -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BundleView. -func (in *BundleView) DeepCopy() *BundleView { - if in == nil { - return nil - } - out := new(BundleView) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *BundleView) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ChartCard) DeepCopyInto(out *ChartCard) { - *out = *in - out.ChartRef = in.ChartRef - in.PackageDescriptor.DeepCopyInto(&out.PackageDescriptor) - if in.Features != nil { - in, out := &in.Features, &out.Features - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Versions != nil { - in, out := &in.Versions, &out.Versions - *out = make([]VersionOption, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ChartCard. -func (in *ChartCard) DeepCopy() *ChartCard { - if in == nil { - return nil - } - out := new(ChartCard) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ChartOption) DeepCopyInto(out *ChartOption) { - *out = *in - out.ChartRef = in.ChartRef - if in.Features != nil { - in, out := &in.Features, &out.Features - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Versions != nil { - in, out := &in.Versions, &out.Versions - *out = make([]VersionDetail, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ChartOption. -func (in *ChartOption) DeepCopy() *ChartOption { - if in == nil { - return nil - } - out := new(ChartOption) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ChartOrder) DeepCopyInto(out *ChartOrder) { - *out = *in - out.ChartSourceFlatRef = in.ChartSourceFlatRef - if in.Values != nil { - in, out := &in.Values, &out.Values - *out = (*in).DeepCopy() - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ChartOrder. -func (in *ChartOrder) DeepCopy() *ChartOrder { - if in == nil { - return nil - } - out := new(ChartOrder) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ChartRef) DeepCopyInto(out *ChartRef) { - *out = *in - out.SourceRef = in.SourceRef -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ChartRef. -func (in *ChartRef) DeepCopy() *ChartRef { - if in == nil { - return nil - } - out := new(ChartRef) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ChartSelection) DeepCopyInto(out *ChartSelection) { - *out = *in - out.ChartRef = in.ChartRef - if in.Bundle != nil { - in, out := &in.Bundle, &out.Bundle - *out = new(ChartSourceRef) - **out = **in - } - if in.ValuesPatch != nil { - in, out := &in.ValuesPatch, &out.ValuesPatch - *out = new(runtime.RawExtension) - (*in).DeepCopyInto(*out) - } - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = new(ResourceDefinitions) - (*in).DeepCopyInto(*out) - } - if in.WaitFors != nil { - in, out := &in.WaitFors, &out.WaitFors - *out = make([]WaitFlags, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ChartSelection. -func (in *ChartSelection) DeepCopy() *ChartSelection { - if in == nil { - return nil - } - out := new(ChartSelection) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ChartSourceFlatRef) DeepCopyInto(out *ChartSourceFlatRef) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ChartSourceFlatRef. -func (in *ChartSourceFlatRef) DeepCopy() *ChartSourceFlatRef { - if in == nil { - return nil - } - out := new(ChartSourceFlatRef) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ChartSourceRef) DeepCopyInto(out *ChartSourceRef) { - *out = *in - out.SourceRef = in.SourceRef -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ChartSourceRef. -func (in *ChartSourceRef) DeepCopy() *ChartSourceRef { - if in == nil { - return nil - } - out := new(ChartSourceRef) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ChartTemplate) DeepCopyInto(out *ChartTemplate) { - *out = *in - out.ChartSourceRef = in.ChartSourceRef - if in.CRDs != nil { - in, out := &in.CRDs, &out.CRDs - *out = make([]BucketObject, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Manifest != nil { - in, out := &in.Manifest, &out.Manifest - *out = new(BucketFileRef) - **out = **in - } - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = make([]ResourceObject, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ChartTemplate. -func (in *ChartTemplate) DeepCopy() *ChartTemplate { - if in == nil { - return nil - } - out := new(ChartTemplate) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ChartTemplateOutput) DeepCopyInto(out *ChartTemplateOutput) { - *out = *in - out.ChartSourceRef = in.ChartSourceRef - if in.CRDs != nil { - in, out := &in.CRDs, &out.CRDs - *out = make([]BucketFileOutput, len(*in)) - copy(*out, *in) - } - if in.Manifest != nil { - in, out := &in.Manifest, &out.Manifest - *out = new(BucketFileRef) - **out = **in - } - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = make([]ResourceFile, len(*in)) - copy(*out, *in) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ChartTemplateOutput. -func (in *ChartTemplateOutput) DeepCopy() *ChartTemplateOutput { - if in == nil { - return nil - } - out := new(ChartTemplateOutput) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *EditResourceOrder) DeepCopyInto(out *EditResourceOrder) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EditResourceOrder. -func (in *EditResourceOrder) DeepCopy() *EditResourceOrder { - if in == nil { - return nil - } - out := new(EditResourceOrder) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *EditorParameters) DeepCopyInto(out *EditorParameters) { - *out = *in - if in.ValuesPatch != nil { - in, out := &in.ValuesPatch, &out.ValuesPatch - *out = new(runtime.RawExtension) - (*in).DeepCopyInto(*out) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EditorParameters. -func (in *EditorParameters) DeepCopy() *EditorParameters { - if in == nil { - return nil - } - out := new(EditorParameters) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *EditorTemplate) DeepCopyInto(out *EditorTemplate) { - *out = *in - if in.Manifest != nil { - in, out := &in.Manifest, &out.Manifest - *out = make([]byte, len(*in)) - copy(*out, *in) - } - if in.Values != nil { - in, out := &in.Values, &out.Values - *out = (*in).DeepCopy() - } - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = make([]ResourceObject, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EditorTemplate. -func (in *EditorTemplate) DeepCopy() *EditorTemplate { - if in == nil { - return nil - } - out := new(EditorTemplate) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Feature) DeepCopyInto(out *Feature) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Feature. -func (in *Feature) DeepCopy() *Feature { - if in == nil { - return nil - } - out := new(Feature) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Hub) DeepCopyInto(out *Hub) { - *out = *in - if in.Repositories != nil { - in, out := &in.Repositories, &out.Repositories - *out = make([]Repository, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Hub. -func (in *Hub) DeepCopy() *Hub { - if in == nil { - return nil - } - out := new(Hub) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *InstallOptions) DeepCopyInto(out *InstallOptions) { - *out = *in - out.ChartRef = in.ChartRef -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new InstallOptions. -func (in *InstallOptions) DeepCopy() *InstallOptions { - if in == nil { - return nil - } - out := new(InstallOptions) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Metadata) DeepCopyInto(out *Metadata) { - *out = *in - out.Resource = in.Resource - out.Release = in.Release -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Metadata. -func (in *Metadata) DeepCopy() *Metadata { - if in == nil { - return nil - } - out := new(Metadata) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *MetadataFlat) DeepCopyInto(out *MetadataFlat) { - *out = *in - out.ResourceID = in.ResourceID -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MetadataFlat. -func (in *MetadataFlat) DeepCopy() *MetadataFlat { - if in == nil { - return nil - } - out := new(MetadataFlat) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Model) DeepCopyInto(out *Model) { - *out = *in - out.Metadata = in.Metadata - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = (*in).DeepCopy() - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Model. -func (in *Model) DeepCopy() *Model { - if in == nil { - return nil - } - out := new(Model) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ModelMetadata) DeepCopyInto(out *ModelMetadata) { - *out = *in - out.Metadata = in.Metadata -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ModelMetadata. -func (in *ModelMetadata) DeepCopy() *ModelMetadata { - if in == nil { - return nil - } - out := new(ModelMetadata) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ObjectMeta) DeepCopyInto(out *ObjectMeta) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ObjectMeta. -func (in *ObjectMeta) DeepCopy() *ObjectMeta { - if in == nil { - return nil - } - out := new(ObjectMeta) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ObjectModel) DeepCopyInto(out *ObjectModel) { - *out = *in - if in.Object != nil { - in, out := &in.Object, &out.Object - *out = (*in).DeepCopy() - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ObjectModel. -func (in *ObjectModel) DeepCopy() *ObjectModel { - if in == nil { - return nil - } - out := new(ObjectModel) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *OneOfBundleOption) DeepCopyInto(out *OneOfBundleOption) { - *out = *in - if in.Bundles != nil { - in, out := &in.Bundles, &out.Bundles - *out = make([]*BundleOption, len(*in)) - for i := range *in { - if (*in)[i] != nil { - in, out := &(*in)[i], &(*out)[i] - *out = new(BundleOption) - **out = **in - } - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OneOfBundleOption. -func (in *OneOfBundleOption) DeepCopy() *OneOfBundleOption { - if in == nil { - return nil - } - out := new(OneOfBundleOption) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *OneOfBundleOptionView) DeepCopyInto(out *OneOfBundleOptionView) { - *out = *in - if in.Bundles != nil { - in, out := &in.Bundles, &out.Bundles - *out = make([]*BundleOptionView, len(*in)) - for i := range *in { - if (*in)[i] != nil { - in, out := &(*in)[i], &(*out)[i] - *out = new(BundleOptionView) - (*in).DeepCopyInto(*out) - } - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OneOfBundleOptionView. -func (in *OneOfBundleOptionView) DeepCopy() *OneOfBundleOptionView { - if in == nil { - return nil - } - out := new(OneOfBundleOptionView) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Order) DeepCopyInto(out *Order) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - out.Status = in.Status -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Order. -func (in *Order) DeepCopy() *Order { - if in == nil { - return nil - } - out := new(Order) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Order) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *OrderList) DeepCopyInto(out *OrderList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Order, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OrderList. -func (in *OrderList) DeepCopy() *OrderList { - if in == nil { - return nil - } - out := new(OrderList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *OrderList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *OrderSpec) DeepCopyInto(out *OrderSpec) { - *out = *in - if in.Packages != nil { - in, out := &in.Packages, &out.Packages - *out = make([]PackageSelection, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OrderSpec. -func (in *OrderSpec) DeepCopy() *OrderSpec { - if in == nil { - return nil - } - out := new(OrderSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *OrderStatus) DeepCopyInto(out *OrderStatus) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OrderStatus. -func (in *OrderStatus) DeepCopy() *OrderStatus { - if in == nil { - return nil - } - out := new(OrderStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PackageCard) DeepCopyInto(out *PackageCard) { - *out = *in - if in.Chart != nil { - in, out := &in.Chart, &out.Chart - *out = new(ChartCard) - (*in).DeepCopyInto(*out) - } - if in.Bundle != nil { - in, out := &in.Bundle, &out.Bundle - *out = new(BundleOptionView) - (*in).DeepCopyInto(*out) - } - if in.OneOf != nil { - in, out := &in.OneOf, &out.OneOf - *out = new(OneOfBundleOptionView) - (*in).DeepCopyInto(*out) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageCard. -func (in *PackageCard) DeepCopy() *PackageCard { - if in == nil { - return nil - } - out := new(PackageCard) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PackageDescriptor) DeepCopyInto(out *PackageDescriptor) { - *out = *in - if in.Icons != nil { - in, out := &in.Icons, &out.Icons - *out = make([]shared.ImageSpec, len(*in)) - copy(*out, *in) - } - if in.Maintainers != nil { - in, out := &in.Maintainers, &out.Maintainers - *out = make([]shared.ContactData, len(*in)) - copy(*out, *in) - } - if in.Keywords != nil { - in, out := &in.Keywords, &out.Keywords - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Links != nil { - in, out := &in.Links, &out.Links - *out = make([]shared.Link, len(*in)) - copy(*out, *in) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageDescriptor. -func (in *PackageDescriptor) DeepCopy() *PackageDescriptor { - if in == nil { - return nil - } - out := new(PackageDescriptor) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PackageMeta) DeepCopyInto(out *PackageMeta) { - *out = *in - in.PackageDescriptor.DeepCopyInto(&out.PackageDescriptor) - out.ChartSourceRef = in.ChartSourceRef -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageMeta. -func (in *PackageMeta) DeepCopy() *PackageMeta { - if in == nil { - return nil - } - out := new(PackageMeta) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PackageRef) DeepCopyInto(out *PackageRef) { - *out = *in - if in.Chart != nil { - in, out := &in.Chart, &out.Chart - *out = new(ChartOption) - (*in).DeepCopyInto(*out) - } - if in.Bundle != nil { - in, out := &in.Bundle, &out.Bundle - *out = new(BundleOption) - **out = **in - } - if in.OneOf != nil { - in, out := &in.OneOf, &out.OneOf - *out = new(OneOfBundleOption) - (*in).DeepCopyInto(*out) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageRef. -func (in *PackageRef) DeepCopy() *PackageRef { - if in == nil { - return nil - } - out := new(PackageRef) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PackageSelection) DeepCopyInto(out *PackageSelection) { - *out = *in - if in.Chart != nil { - in, out := &in.Chart, &out.Chart - *out = new(ChartSelection) - (*in).DeepCopyInto(*out) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageSelection. -func (in *PackageSelection) DeepCopy() *PackageSelection { - if in == nil { - return nil - } - out := new(PackageSelection) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PackageView) DeepCopyInto(out *PackageView) { - *out = *in - out.TypeMeta = in.TypeMeta - in.PackageMeta.DeepCopyInto(&out.PackageMeta) - if in.ValuesFiles != nil { - in, out := &in.ValuesFiles, &out.ValuesFiles - *out = make([]ValuesFile, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.OpenAPIV3Schema != nil { - in, out := &in.OpenAPIV3Schema, &out.OpenAPIV3Schema - *out = (*in).DeepCopy() - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageView. -func (in *PackageView) DeepCopy() *PackageView { - if in == nil { - return nil - } - out := new(PackageView) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *PackageView) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Repository) DeepCopyInto(out *Repository) { - *out = *in - if in.Maintainers != nil { - in, out := &in.Maintainers, &out.Maintainers - *out = make([]shared.ContactData, len(*in)) - copy(*out, *in) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Repository. -func (in *Repository) DeepCopy() *Repository { - if in == nil { - return nil - } - out := new(Repository) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ResourceDefinitions) DeepCopyInto(out *ResourceDefinitions) { - *out = *in - if in.Owned != nil { - in, out := &in.Owned, &out.Owned - *out = make([]v1.GroupVersionResource, len(*in)) - copy(*out, *in) - } - if in.Required != nil { - in, out := &in.Required, &out.Required - *out = make([]v1.GroupVersionResource, len(*in)) - copy(*out, *in) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResourceDefinitions. -func (in *ResourceDefinitions) DeepCopy() *ResourceDefinitions { - if in == nil { - return nil - } - out := new(ResourceDefinitions) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ResourceFile) DeepCopyInto(out *ResourceFile) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResourceFile. -func (in *ResourceFile) DeepCopy() *ResourceFile { - if in == nil { - return nil - } - out := new(ResourceFile) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ResourceObject) DeepCopyInto(out *ResourceObject) { - *out = *in - if in.Data != nil { - in, out := &in.Data, &out.Data - *out = (*in).DeepCopy() - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResourceObject. -func (in *ResourceObject) DeepCopy() *ResourceObject { - if in == nil { - return nil - } - out := new(ResourceObject) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ResourceOutput) DeepCopyInto(out *ResourceOutput) { - *out = *in - if in.CRDs != nil { - in, out := &in.CRDs, &out.CRDs - *out = make([]ResourceFile, len(*in)) - copy(*out, *in) - } - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = make([]ResourceFile, len(*in)) - copy(*out, *in) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResourceOutput. -func (in *ResourceOutput) DeepCopy() *ResourceOutput { - if in == nil { - return nil - } - out := new(ResourceOutput) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SimpleValue) DeepCopyInto(out *SimpleValue) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ObjectMeta = in.ObjectMeta -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SimpleValue. -func (in *SimpleValue) DeepCopy() *SimpleValue { - if in == nil { - return nil - } - out := new(SimpleValue) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ValuesFile) DeepCopyInto(out *ValuesFile) { - *out = *in - if in.Values != nil { - in, out := &in.Values, &out.Values - *out = new(runtime.RawExtension) - (*in).DeepCopyInto(*out) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ValuesFile. -func (in *ValuesFile) DeepCopy() *ValuesFile { - if in == nil { - return nil - } - out := new(ValuesFile) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *VersionDetail) DeepCopyInto(out *VersionDetail) { - *out = *in - in.VersionOption.DeepCopyInto(&out.VersionOption) - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = new(ResourceDefinitions) - (*in).DeepCopyInto(*out) - } - if in.WaitFors != nil { - in, out := &in.WaitFors, &out.WaitFors - *out = make([]WaitFlags, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VersionDetail. -func (in *VersionDetail) DeepCopy() *VersionDetail { - if in == nil { - return nil - } - out := new(VersionDetail) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *VersionOption) DeepCopyInto(out *VersionOption) { - *out = *in - if in.ValuesPatch != nil { - in, out := &in.ValuesPatch, &out.ValuesPatch - *out = new(runtime.RawExtension) - (*in).DeepCopyInto(*out) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VersionOption. -func (in *VersionOption) DeepCopy() *VersionOption { - if in == nil { - return nil - } - out := new(VersionOption) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *WaitFlags) DeepCopyInto(out *WaitFlags) { - *out = *in - out.Resource = in.Resource - if in.Labels != nil { - in, out := &in.Labels, &out.Labels - *out = new(v1.LabelSelector) - (*in).DeepCopyInto(*out) - } - out.Timeout = in.Timeout -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WaitFlags. -func (in *WaitFlags) DeepCopy() *WaitFlags { - if in == nil { - return nil - } - out := new(WaitFlags) - in.DeepCopyInto(out) - return out -} diff --git a/vendor/x-helm.dev/apimachinery/apis/shared/types.go b/vendor/x-helm.dev/apimachinery/apis/shared/types.go deleted file mode 100644 index 3efd7cff3..000000000 --- a/vendor/x-helm.dev/apimachinery/apis/shared/types.go +++ /dev/null @@ -1,71 +0,0 @@ -// +kubebuilder:object:generate=true -package shared - -type MediaType string - -const ( - MediaLogo MediaType = "logo" - MediaLogoWhite MediaType = "logo_white" - MediaIcon MediaType = "icon" - MediaIcon192_192 MediaType = "icon_192x192" - MediaHeroImage MediaType = "hero_image" - MediaIntroVideo MediaType = "intro_video" -) - -type LinkType string - -const ( - LinkWebsite LinkType = "website" - LinkSupportDesk LinkType = "support_desk" - LinkFacebook LinkType = "facebook" - LinkLinkedIn LinkType = "linkedin" - LinkTwitter LinkType = "twitter" - LinkTwitterID LinkType = "twitter_id" - LinkYouTube LinkType = "youtube" - LinkSourceRepo LinkType = "src_repo" - LinkStarRepo LinkType = "star_repo" - LinkDocsRepo LinkType = "docs_repo" - LinkDatasheetFormID LinkType = "datasheet_form_id" -) - -// ImageSpec contains information about an image used as an icon. -type ImageSpec struct { - // The source for image represented as either an absolute URL to the image or a Data URL containing - // the image. Data URLs are defined in RFC 2397. - Source string `json:"src"` - - // (optional) The size of the image in pixels (e.g., 25x25). - Size string `json:"size,omitempty"` - - // (optional) The mine type of the image (e.g., "image/png"). - Type string `json:"type,omitempty"` -} - -// MediaSpec contains information about an image/video. -type MediaSpec struct { - // Description is human readable content explaining the purpose of the link. - Description MediaType `json:"description,omitempty"` - - ImageSpec `json:",inline"` -} - -// ContactData contains information about an individual or organization. -type ContactData struct { - // Name is the descriptive name. - Name string `json:"name,omitempty"` - - // Url could typically be a website address. - URL string `json:"url,omitempty"` - - // Email is the email address. - Email string `json:"email,omitempty"` -} - -// Link contains information about an URL to surface documentation, dashboards, etc. -type Link struct { - // Description is human readable content explaining the purpose of the link. - Description string `json:"description,omitempty"` - - // Url typically points at a website address. - URL string `json:"url,omitempty"` -} diff --git a/vendor/x-helm.dev/apimachinery/apis/shared/zz_generated.deepcopy.go b/vendor/x-helm.dev/apimachinery/apis/shared/zz_generated.deepcopy.go deleted file mode 100644 index 0a71c2d07..000000000 --- a/vendor/x-helm.dev/apimachinery/apis/shared/zz_generated.deepcopy.go +++ /dev/null @@ -1,84 +0,0 @@ -//go:build !ignore_autogenerated - -/* -Copyright 2023. - -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. -*/ - -// Code generated by controller-gen. DO NOT EDIT. - -package shared - -import () - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ContactData) DeepCopyInto(out *ContactData) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContactData. -func (in *ContactData) DeepCopy() *ContactData { - if in == nil { - return nil - } - out := new(ContactData) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ImageSpec) DeepCopyInto(out *ImageSpec) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImageSpec. -func (in *ImageSpec) DeepCopy() *ImageSpec { - if in == nil { - return nil - } - out := new(ImageSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Link) DeepCopyInto(out *Link) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Link. -func (in *Link) DeepCopy() *Link { - if in == nil { - return nil - } - out := new(Link) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *MediaSpec) DeepCopyInto(out *MediaSpec) { - *out = *in - out.ImageSpec = in.ImageSpec -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MediaSpec. -func (in *MediaSpec) DeepCopy() *MediaSpec { - if in == nil { - return nil - } - out := new(MediaSpec) - in.DeepCopyInto(out) - return out -} diff --git a/vendor/x-helm.dev/apimachinery/crds/charts.x-helm.dev_chartpresets.yaml b/vendor/x-helm.dev/apimachinery/crds/charts.x-helm.dev_chartpresets.yaml deleted file mode 100644 index 880ef68d4..000000000 --- a/vendor/x-helm.dev/apimachinery/crds/charts.x-helm.dev_chartpresets.yaml +++ /dev/null @@ -1,45 +0,0 @@ - ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - creationTimestamp: null - name: chartpresets.charts.x-helm.dev -spec: - group: charts.x-helm.dev - names: - kind: ChartPreset - listKind: ChartPresetList - plural: chartpresets - singular: chartpreset - scope: Namespaced - versions: - - name: v1alpha1 - schema: - openAPIV3Schema: - description: ChartPreset is the Schema for the chartpresets API - properties: - apiVersion: - description: 'APIVersion defines the versioned schema of this representation - of an object. Servers should convert recognized schemas to the latest - internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' - type: string - kind: - description: 'Kind is a string value representing the REST resource this - object represents. Servers may infer this from the endpoint the client - submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' - type: string - metadata: - type: object - spec: - description: ClusterChartPresetSpec defines the desired state of ClusterChartPreset - properties: - values: - type: object - x-kubernetes-preserve-unknown-fields: true - type: object - type: object - served: true - storage: true - subresources: - status: {} diff --git a/vendor/x-helm.dev/apimachinery/crds/charts.x-helm.dev_clusterchartpresets.yaml b/vendor/x-helm.dev/apimachinery/crds/charts.x-helm.dev_clusterchartpresets.yaml deleted file mode 100644 index 1bcd85709..000000000 --- a/vendor/x-helm.dev/apimachinery/crds/charts.x-helm.dev_clusterchartpresets.yaml +++ /dev/null @@ -1,46 +0,0 @@ - ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - creationTimestamp: null - name: clusterchartpresets.charts.x-helm.dev -spec: - group: charts.x-helm.dev - names: - kind: ClusterChartPreset - listKind: ClusterChartPresetList - plural: clusterchartpresets - singular: clusterchartpreset - scope: Cluster - versions: - - name: v1alpha1 - schema: - openAPIV3Schema: - description: ClusterChartPreset is the Schema for the clusterchartpresets - API - properties: - apiVersion: - description: 'APIVersion defines the versioned schema of this representation - of an object. Servers should convert recognized schemas to the latest - internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' - type: string - kind: - description: 'Kind is a string value representing the REST resource this - object represents. Servers may infer this from the endpoint the client - submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' - type: string - metadata: - type: object - spec: - description: ClusterChartPresetSpec defines the desired state of ClusterChartPreset - properties: - values: - type: object - x-kubernetes-preserve-unknown-fields: true - type: object - type: object - served: true - storage: true - subresources: - status: {} diff --git a/vendor/x-helm.dev/apimachinery/crds/drivers.x-helm.dev_appreleases.yaml b/vendor/x-helm.dev/apimachinery/crds/drivers.x-helm.dev_appreleases.yaml deleted file mode 100644 index 1dd9eb337..000000000 --- a/vendor/x-helm.dev/apimachinery/crds/drivers.x-helm.dev_appreleases.yaml +++ /dev/null @@ -1,386 +0,0 @@ - ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - creationTimestamp: null - name: appreleases.drivers.x-helm.dev -spec: - group: drivers.x-helm.dev - names: - kind: AppRelease - listKind: AppReleaseList - plural: appreleases - singular: apprelease - scope: Namespaced - versions: - - additionalPrinterColumns: - - description: The type of the appRelease - jsonPath: .spec.descriptor.type - name: Type - type: string - - description: The creation date - jsonPath: .spec.descriptor.version - name: Version - type: string - - description: The creation date - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha1 - schema: - openAPIV3Schema: - description: AppRelease is the Schema for the appReleases API - properties: - apiVersion: - description: 'APIVersion defines the versioned schema of this representation - of an object. Servers should convert recognized schemas to the latest - internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' - type: string - kind: - description: 'Kind is a string value representing the REST resource this - object represents. Servers may infer this from the endpoint the client - submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' - type: string - metadata: - type: object - spec: - description: AppReleaseSpec defines the specification for an AppRelease. - properties: - components: - description: Components is a list of Kinds for AppRelease's components - (e.g. Deployments, Pods, Services, CRDs). It can be used in conjunction - with the AppRelease's Selector to list or watch the AppReleases - components. - items: - description: GroupVersionKind unambiguously identifies a kind. It - doesn't anonymously include GroupVersion to avoid automatic coercion. It - doesn't use a GroupVersion to avoid custom marshalling - properties: - group: - type: string - kind: - type: string - version: - type: string - required: - - group - - kind - - version - type: object - type: array - descriptor: - description: Descriptor regroups information and metadata about an - appRelease. - properties: - description: - description: Description is a brief string description of the - AppRelease. - type: string - icons: - description: Icons is an optional list of icons for an appRelease. - Icon information includes the source, size, and mime type. - items: - description: ImageSpec contains information about an image used - as an icon. - properties: - size: - description: (optional) The size of the image in pixels - (e.g., 25x25). - type: string - src: - description: The source for image represented as either - an absolute URL to the image or a Data URL containing - the image. Data URLs are defined in RFC 2397. - type: string - type: - description: (optional) The mine type of the image (e.g., - "image/png"). - type: string - required: - - src - type: object - type: array - keywords: - description: Keywords is an optional list of key words associated - with the appRelease (e.g. MySQL, RDBMS, database). - items: - type: string - type: array - links: - description: Links are a list of descriptive URLs intended to - be used to surface additional documentation, dashboards, etc. - items: - description: Link contains information about an URL to surface - documentation, dashboards, etc. - properties: - description: - description: Description is human readable content explaining - the purpose of the link. - type: string - url: - description: Url typically points at a website address. - type: string - type: object - type: array - maintainers: - description: Maintainers is an optional list of maintainers of - the appRelease. The maintainers in this list maintain the the - source code, images, and package for the appRelease. - items: - description: ContactData contains information about an individual - or organization. - properties: - email: - description: Email is the email address. - type: string - name: - description: Name is the descriptive name. - type: string - url: - description: Url could typically be a website address. - type: string - type: object - type: array - notes: - description: Notes contain a human readable snippets intended - as a quick start for the users of the AppRelease. CommonMark - markdown syntax may be used for rich text representation. - type: string - owners: - description: Owners is an optional list of the owners of the installed - appRelease. The owners of the appRelease should be contacted - in the event of a planned or unplanned disruption affecting - the appRelease. - items: - description: ContactData contains information about an individual - or organization. - properties: - email: - description: Email is the email address. - type: string - name: - description: Name is the descriptive name. - type: string - url: - description: Url could typically be a website address. - type: string - type: object - type: array - type: - description: Type is the type of the appRelease (e.g. WordPress, - MySQL, Cassandra). - type: string - version: - description: Version is an optional version indicator for the - AppRelease. - type: string - type: object - editor: - description: GroupVersionResource unambiguously identifies a resource. It - doesn't anonymously include GroupVersion to avoid automatic coercion. It - doesn't use a GroupVersion to avoid custom marshalling - properties: - group: - type: string - resource: - type: string - version: - type: string - required: - - group - - resource - - version - type: object - formKeys: - items: - type: string - type: array - release: - description: Release regroups information and metadata about a Helm - release. - properties: - firstDeployed: - format: date-time - type: string - form: - type: object - x-kubernetes-preserve-unknown-fields: true - lastDeployed: - format: date-time - type: string - modified-at: - format: date-time - type: string - name: - type: string - status: - type: string - version: - type: string - required: - - name - type: object - resourceKeys: - items: - type: string - type: array - selector: - description: 'Selector is a label query over kinds that created by - the appRelease. It must match the component objects'' labels. More - info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors' - properties: - matchExpressions: - description: matchExpressions is a list of label selector requirements. - The requirements are ANDed. - items: - description: A label selector requirement is a selector that - contains values, a key, and an operator that relates the key - and values. - properties: - key: - description: key is the label key that the selector applies - to. - type: string - operator: - description: operator represents a key's relationship to - a set of values. Valid operators are In, NotIn, Exists - and DoesNotExist. - type: string - values: - description: values is an array of string values. If the - operator is In or NotIn, the values array must be non-empty. - If the operator is Exists or DoesNotExist, the values - array must be empty. This array is replaced during a strategic - merge patch. - items: - type: string - type: array - required: - - key - - operator - type: object - type: array - matchLabels: - additionalProperties: - type: string - description: matchLabels is a map of {key,value} pairs. A single - {key,value} in the matchLabels map is equivalent to an element - of matchExpressions, whose key field is "key", the operator - is "In", and the values array contains only "value". The requirements - are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - type: object - status: - description: AppReleaseStatus defines controller's the observed state - of AppRelease - properties: - components: - description: Object status array for all matching objects - items: - description: ObjectStatus is a generic status holder for objects - properties: - group: - description: Object group - type: string - kind: - description: Kind of object - type: string - link: - description: Link to object - type: string - name: - description: Name of object - type: string - status: - description: 'Status. Values: InProgress, Ready, Unknown' - type: string - type: object - type: array - componentsReady: - description: 'ComponentsReady: status of the components in the format - ready/total' - type: string - conditions: - description: Conditions represents the latest state of the object - items: - description: "Condition contains details for one aspect of the current - state of this API Resource. --- This struct is intended for direct - use as an array at the field path .status.conditions. For example, - \n type FooStatus struct{ // Represents the observations of a - foo's current state. // Known .status.conditions.type are: \"Available\", - \"Progressing\", and \"Degraded\" // +patchMergeKey=type // +patchStrategy=merge - // +listType=map // +listMapKey=type Conditions []metav1.Condition - `json:\"conditions,omitempty\" patchStrategy:\"merge\" patchMergeKey:\"type\" - protobuf:\"bytes,1,rep,name=conditions\"` \n // other fields }" - properties: - lastTransitionTime: - description: lastTransitionTime is the last time the condition - transitioned from one status to another. This should be when - the underlying condition changed. If that is not known, then - using the time when the API field changed is acceptable. - format: date-time - type: string - message: - description: message is a human readable message indicating - details about the transition. This may be an empty string. - maxLength: 32768 - type: string - observedGeneration: - description: observedGeneration represents the .metadata.generation - that the condition was set based upon. For instance, if .metadata.generation - is currently 12, but the .status.conditions[x].observedGeneration - is 9, the condition is out of date with respect to the current - state of the instance. - format: int64 - minimum: 0 - type: integer - reason: - description: reason contains a programmatic identifier indicating - the reason for the condition's last transition. Producers - of specific condition types may define expected values and - meanings for this field, and whether the values are considered - a guaranteed API. The value should be a CamelCase string. - This field may not be empty. - maxLength: 1024 - minLength: 1 - pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ - type: string - status: - description: status of the condition, one of True, False, Unknown. - enum: - - "True" - - "False" - - Unknown - type: string - type: - description: type of condition in CamelCase or in foo.example.com/CamelCase. - --- Many .condition.type values are consistent across resources - like Available, but because arbitrary conditions can be useful - (see .node.status.conditions), the ability to deconflict is - important. The regex it matches is (dns1123SubdomainFmt/)?(qualifiedNameFmt) - maxLength: 316 - pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ - type: string - required: - - lastTransitionTime - - message - - reason - - status - - type - type: object - type: array - observedGeneration: - description: ObservedGeneration is the most recent generation observed. - It corresponds to the Object's generation, which is updated on mutation - by the API Server. - format: int64 - type: integer - type: object - type: object - served: true - storage: true - subresources: - status: {} diff --git a/vendor/x-helm.dev/apimachinery/crds/lib.go b/vendor/x-helm.dev/apimachinery/crds/lib.go deleted file mode 100644 index 2871fe153..000000000 --- a/vendor/x-helm.dev/apimachinery/crds/lib.go +++ /dev/null @@ -1,60 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -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 crds - -import ( - "embed" - "fmt" - - "k8s.io/apimachinery/pkg/runtime/schema" - "kmodules.xyz/client-go/apiextensions" - "sigs.k8s.io/yaml" -) - -//go:embed *.yaml -var fs embed.FS - -func load(filename string, o interface{}) error { - data, err := fs.ReadFile(filename) - if err != nil { - return err - } - return yaml.Unmarshal(data, o) -} - -func CustomResourceDefinition(gvr schema.GroupVersionResource) (*apiextensions.CustomResourceDefinition, error) { - var out apiextensions.CustomResourceDefinition - - v1file := fmt.Sprintf("%s_%s.yaml", gvr.Group, gvr.Resource) - if err := load(v1file, &out.V1); err != nil { - return nil, err - } - - if out.V1 == nil { - return nil, fmt.Errorf("missing crd yamls for gvr: %s", gvr) - } - - return &out, nil -} - -func MustCustomResourceDefinition(gvr schema.GroupVersionResource) *apiextensions.CustomResourceDefinition { - out, err := CustomResourceDefinition(gvr) - if err != nil { - panic(err) - } - return out -} diff --git a/vendor/x-helm.dev/apimachinery/crds/products.x-helm.dev_plans.yaml b/vendor/x-helm.dev/apimachinery/crds/products.x-helm.dev_plans.yaml deleted file mode 100644 index dd9719bb5..000000000 --- a/vendor/x-helm.dev/apimachinery/crds/products.x-helm.dev_plans.yaml +++ /dev/null @@ -1,179 +0,0 @@ - ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - creationTimestamp: null - name: plans.products.x-helm.dev -spec: - group: products.x-helm.dev - names: - kind: Plan - listKind: PlanList - plural: plans - singular: plan - scope: Cluster - versions: - - name: v1alpha1 - schema: - openAPIV3Schema: - properties: - apiVersion: - description: 'APIVersion defines the versioned schema of this representation - of an object. Servers should convert recognized schemas to the latest - internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' - type: string - kind: - description: 'Kind is a string value representing the REST resource this - object represents. Servers may infer this from the endpoint the client - submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' - type: string - metadata: - type: object - spec: - properties: - aggregateUsage: - type: string - amount: - format: int64 - type: integer - amountDecimal: - format: double - type: number - billingScheme: - type: string - bundle: - properties: - name: - type: string - sourceRef: - description: TypedObjectReference represents an typed namespaced - object. - properties: - apiGroup: - type: string - kind: - type: string - name: - description: 'Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names' - type: string - namespace: - description: 'Namespace of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/' - type: string - required: - - name - type: object - required: - - name - - sourceRef - type: object - currency: - type: string - description: - type: string - displayName: - type: string - id: - type: string - includedPlans: - items: - type: string - type: array - interval: - type: string - intervalCount: - format: int64 - type: integer - name: - type: string - phase: - type: string - pricingPattern: - additionalProperties: - properties: - expression: - type: string - sizedPrices: - items: - properties: - cpu: - type: string - memory: - type: string - price: - format: double - type: number - required: - - cpu - - memory - - price - type: object - type: array - type: object - type: object - productID: - type: string - tiers: - items: - description: PlanTier configures tiered pricing - properties: - flatAmount: - format: int64 - type: integer - flatAmountDecimal: - format: double - type: number - unitAmount: - format: int64 - type: integer - unitAmountDecimal: - format: double - type: number - upTo: - format: int64 - type: integer - type: object - type: array - tiersMode: - type: string - transformUsage: - description: PlanTransformUsage represents the bucket billing configuration. - properties: - divideBy: - format: int64 - type: integer - round: - type: string - type: object - trialPeriodDays: - format: int64 - type: integer - usageType: - type: string - weight: - description: Plans for sorted by weight before displaying to users - format: int32 - type: integer - required: - - description - - displayName - - id - - name - - phase - - productID - - weight - type: object - status: - properties: - observedGeneration: - description: ObservedGeneration is the most recent generation observed - for this resource. It corresponds to the resource's generation, - which is updated on mutation by the API Server. - format: int64 - type: integer - type: object - type: object - served: true - storage: true - subresources: - status: {} diff --git a/vendor/x-helm.dev/apimachinery/crds/products.x-helm.dev_products.yaml b/vendor/x-helm.dev/apimachinery/crds/products.x-helm.dev_products.yaml deleted file mode 100644 index 790fa65c4..000000000 --- a/vendor/x-helm.dev/apimachinery/crds/products.x-helm.dev_products.yaml +++ /dev/null @@ -1,167 +0,0 @@ - ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - creationTimestamp: null - name: products.products.x-helm.dev -spec: - group: products.x-helm.dev - names: - kind: Product - listKind: ProductList - plural: products - singular: product - scope: Cluster - versions: - - name: v1alpha1 - schema: - openAPIV3Schema: - properties: - apiVersion: - description: 'APIVersion defines the versioned schema of this representation - of an object. Servers should convert recognized schemas to the latest - internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' - type: string - kind: - description: 'Kind is a string value representing the REST resource this - object represents. Servers may infer this from the endpoint the client - submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' - type: string - metadata: - type: object - spec: - properties: - badges: - items: - properties: - alt: - type: string - logo: - type: string - url: - type: string - required: - - alt - - logo - - url - type: object - type: array - description: - type: string - icons: - items: - description: MediaSpec contains information about an image/video. - properties: - description: - description: Description is human readable content explaining - the purpose of the link. - type: string - size: - description: (optional) The size of the image in pixels (e.g., - 25x25). - type: string - src: - description: The source for image represented as either an absolute - URL to the image or a Data URL containing the image. Data - URLs are defined in RFC 2397. - type: string - type: - description: (optional) The mine type of the image (e.g., "image/png"). - type: string - required: - - src - type: object - type: array - id: - type: string - key: - type: string - keywords: - items: - type: string - type: array - latestVersion: - type: string - links: - items: - description: Link contains information about an URL to surface documentation, - dashboards, etc. - properties: - description: - description: Description is human readable content explaining - the purpose of the link. - type: string - url: - description: Url typically points at a website address. - type: string - type: object - type: array - maintainers: - items: - description: ContactData contains information about an individual - or organization. - properties: - email: - description: Email is the email address. - type: string - name: - description: Name is the descriptive name. - type: string - url: - description: Url could typically be a website address. - type: string - type: object - type: array - name: - type: string - owner: - format: int64 - type: integer - ownerName: - type: string - phase: - type: string - shortName: - type: string - summary: - type: string - tagline: - type: string - unitLabel: - type: string - versions: - items: - properties: - releaseDate: - format: date-time - type: string - version: - type: string - required: - - version - type: object - type: array - required: - - id - - key - - name - - owner - - phase - - shortName - - tagline - type: object - status: - properties: - observedGeneration: - description: ObservedGeneration is the most recent generation observed - for this resource. It corresponds to the resource's generation, - which is updated on mutation by the API Server. - format: int64 - type: integer - type: object - type: object - served: true - storage: true - subresources: - status: {} diff --git a/vendor/x-helm.dev/apimachinery/crds/releases.x-helm.dev_bundles.yaml b/vendor/x-helm.dev/apimachinery/crds/releases.x-helm.dev_bundles.yaml deleted file mode 100644 index 4335c3314..000000000 --- a/vendor/x-helm.dev/apimachinery/crds/releases.x-helm.dev_bundles.yaml +++ /dev/null @@ -1,412 +0,0 @@ - ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - creationTimestamp: null - name: bundles.releases.x-helm.dev -spec: - group: releases.x-helm.dev - names: - kind: Bundle - listKind: BundleList - plural: bundles - singular: bundle - scope: Cluster - versions: - - name: v1alpha1 - schema: - openAPIV3Schema: - description: Bundle is the Schema for the bundles API - properties: - apiVersion: - description: 'APIVersion defines the versioned schema of this representation - of an object. Servers should convert recognized schemas to the latest - internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' - type: string - kind: - description: 'Kind is a string value representing the REST resource this - object represents. Servers may infer this from the endpoint the client - submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' - type: string - metadata: - type: object - spec: - properties: - description: - description: Description is a brief string description of the Application. - type: string - displayName: - type: string - features: - items: - properties: - trait: - type: string - value: - type: string - required: - - trait - - value - type: object - type: array - icons: - description: Icons is an optional list of icons for an application. - Icon information includes the source, size, and mime type. - items: - description: ImageSpec contains information about an image used - as an icon. - properties: - size: - description: (optional) The size of the image in pixels (e.g., - 25x25). - type: string - src: - description: The source for image represented as either an absolute - URL to the image or a Data URL containing the image. Data - URLs are defined in RFC 2397. - type: string - type: - description: (optional) The mine type of the image (e.g., "image/png"). - type: string - required: - - src - type: object - type: array - keywords: - description: Keywords is an optional list of key words associated - with the application (e.g. MySQL, RDBMS, database). - items: - type: string - type: array - links: - description: Links are a list of descriptive URLs intended to be used - to surface additional documentation, dashboards, etc. - items: - description: Link contains information about an URL to surface documentation, - dashboards, etc. - properties: - description: - description: Description is human readable content explaining - the purpose of the link. - type: string - url: - description: Url typically points at a website address. - type: string - type: object - type: array - maintainers: - description: Maintainers is an optional list of maintainers of the - application. The maintainers in this list maintain the the source - code, images, and package for the application. - items: - description: ContactData contains information about an individual - or organization. - properties: - email: - description: Email is the email address. - type: string - name: - description: Name is the descriptive name. - type: string - url: - description: Url could typically be a website address. - type: string - type: object - type: array - namespace: - type: string - notes: - description: Notes contain a human readable snippets intended as a - quick start for the users of the Application. CommonMark markdown - syntax may be used for rich text representation. - type: string - packages: - items: - properties: - bundle: - properties: - name: - type: string - sourceRef: - description: TypedObjectReference represents an typed namespaced - object. - properties: - apiGroup: - type: string - kind: - type: string - name: - description: 'Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names' - type: string - namespace: - description: 'Namespace of the referent. More info: - https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/' - type: string - required: - - name - type: object - version: - type: string - required: - - name - - sourceRef - - version - type: object - chart: - properties: - features: - items: - type: string - type: array - multiSelect: - type: boolean - name: - type: string - namespace: - type: string - required: - type: boolean - sourceRef: - description: TypedObjectReference represents an typed namespaced - object. - properties: - apiGroup: - type: string - kind: - type: string - name: - description: 'Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names' - type: string - namespace: - description: 'Namespace of the referent. More info: - https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/' - type: string - required: - - name - type: object - versions: - items: - properties: - licenseKeyPath: - description: 'jsonpatch path in Values where the license - key will be set using replace operation, if defined. - See: http://jsonpatch.com' - type: string - resources: - properties: - owned: - items: - description: GroupVersionResource unambiguously - identifies a resource. It doesn't anonymously - include GroupVersion to avoid automatic coercion. It - doesn't use a GroupVersion to avoid custom - marshalling - properties: - group: - type: string - resource: - type: string - version: - type: string - required: - - group - - resource - - version - type: object - type: array - required: - items: - description: GroupVersionResource unambiguously - identifies a resource. It doesn't anonymously - include GroupVersion to avoid automatic coercion. It - doesn't use a GroupVersion to avoid custom - marshalling - properties: - group: - type: string - resource: - type: string - version: - type: string - required: - - group - - resource - - version - type: object - type: array - required: - - owned - - required - type: object - selected: - type: boolean - valuesFile: - type: string - valuesPatch: - description: 'RFC 6902 compatible json patch. ref: - http://jsonpatch.com' - type: object - x-kubernetes-preserve-unknown-fields: true - version: - type: string - waitFors: - items: - properties: - all: - type: boolean - for: - type: string - labels: - description: A label selector is a label query - over a set of resources. The result of matchLabels - and matchExpressions are ANDed. An empty label - selector matches all objects. A null label - selector matches no objects. - properties: - matchExpressions: - description: matchExpressions is a list - of label selector requirements. The requirements - are ANDed. - items: - description: A label selector requirement - is a selector that contains values, - a key, and an operator that relates - the key and values. - properties: - key: - description: key is the label key - that the selector applies to. - type: string - operator: - description: operator represents a - key's relationship to a set of values. - Valid operators are In, NotIn, Exists - and DoesNotExist. - type: string - values: - description: values is an array of - string values. If the operator is - In or NotIn, the values array must - be non-empty. If the operator is - Exists or DoesNotExist, the values - array must be empty. This array - is replaced during a strategic merge - patch. - items: - type: string - type: array - required: - - key - - operator - type: object - type: array - matchLabels: - additionalProperties: - type: string - description: matchLabels is a map of {key,value} - pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, - whose key field is "key", the operator - is "In", and the values array contains - only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - resource: - description: GroupResource specifies a Group - and a Resource, but does not force a version. This - is useful for identifying concepts during - lookup stages without having partially valid - types - properties: - group: - type: string - resource: - type: string - required: - - group - - resource - type: object - timeout: - type: string - required: - - all - - for - - labels - - resource - - timeout - type: object - type: array - required: - - version - type: object - type: array - required: - - name - - sourceRef - - versions - type: object - oneOf: - properties: - bundles: - items: - properties: - name: - type: string - sourceRef: - description: TypedObjectReference represents an typed - namespaced object. - properties: - apiGroup: - type: string - kind: - type: string - name: - description: 'Name of the referent. More info: - https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names' - type: string - namespace: - description: 'Namespace of the referent. More - info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/' - type: string - required: - - name - type: object - version: - type: string - required: - - name - - sourceRef - - version - type: object - type: array - description: - type: string - required: - - description - type: object - type: object - type: array - type: - description: Type is the type of the application (e.g. WordPress, - MySQL, Cassandra). - type: string - required: - - namespace - - packages - type: object - status: - properties: - observedGeneration: - description: ObservedGeneration is the most recent generation observed - for this resource. It corresponds to the resource's generation, - which is updated on mutation by the API Server. - format: int64 - type: integer - type: object - type: object - served: true - storage: true - subresources: - status: {} diff --git a/vendor/x-helm.dev/apimachinery/crds/releases.x-helm.dev_orders.yaml b/vendor/x-helm.dev/apimachinery/crds/releases.x-helm.dev_orders.yaml deleted file mode 100644 index e76184345..000000000 --- a/vendor/x-helm.dev/apimachinery/crds/releases.x-helm.dev_orders.yaml +++ /dev/null @@ -1,261 +0,0 @@ - ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - creationTimestamp: null - name: orders.releases.x-helm.dev -spec: - group: releases.x-helm.dev - names: - kind: Order - listKind: OrderList - plural: orders - singular: order - scope: Cluster - versions: - - name: v1alpha1 - schema: - openAPIV3Schema: - description: Order is the Schema for the orders API - properties: - apiVersion: - description: 'APIVersion defines the versioned schema of this representation - of an object. Servers should convert recognized schemas to the latest - internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' - type: string - kind: - description: 'Kind is a string value representing the REST resource this - object represents. Servers may infer this from the endpoint the client - submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' - type: string - metadata: - type: object - spec: - properties: - items: - items: - properties: - chart: - properties: - bundle: - description: Bundle points to the parent bundle which was - used to install this, if any. If the chart was installed - directly it will be unset. - properties: - name: - type: string - sourceRef: - description: TypedObjectReference represents an typed - namespaced object. - properties: - apiGroup: - type: string - kind: - type: string - name: - description: 'Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names' - type: string - namespace: - description: 'Namespace of the referent. More info: - https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/' - type: string - required: - - name - type: object - version: - type: string - required: - - name - - sourceRef - - version - type: object - name: - type: string - namespace: - type: string - releaseName: - type: string - resources: - properties: - owned: - items: - description: GroupVersionResource unambiguously identifies - a resource. It doesn't anonymously include GroupVersion - to avoid automatic coercion. It doesn't use a GroupVersion - to avoid custom marshalling - properties: - group: - type: string - resource: - type: string - version: - type: string - required: - - group - - resource - - version - type: object - type: array - required: - items: - description: GroupVersionResource unambiguously identifies - a resource. It doesn't anonymously include GroupVersion - to avoid automatic coercion. It doesn't use a GroupVersion - to avoid custom marshalling - properties: - group: - type: string - resource: - type: string - version: - type: string - required: - - group - - resource - - version - type: object - type: array - required: - - owned - - required - type: object - sourceRef: - description: TypedObjectReference represents an typed namespaced - object. - properties: - apiGroup: - type: string - kind: - type: string - name: - description: 'Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names' - type: string - namespace: - description: 'Namespace of the referent. More info: - https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/' - type: string - required: - - name - type: object - valuesFile: - type: string - valuesPatch: - description: 'RFC 6902 compatible json patch. ref: http://jsonpatch.com' - type: object - x-kubernetes-preserve-unknown-fields: true - version: - type: string - waitFors: - items: - properties: - all: - type: boolean - for: - type: string - labels: - description: A label selector is a label query over - a set of resources. The result of matchLabels and - matchExpressions are ANDed. An empty label selector - matches all objects. A null label selector matches - no objects. - properties: - matchExpressions: - description: matchExpressions is a list of label - selector requirements. The requirements are - ANDed. - items: - description: A label selector requirement is - a selector that contains values, a key, and - an operator that relates the key and values. - properties: - key: - description: key is the label key that the - selector applies to. - type: string - operator: - description: operator represents a key's - relationship to a set of values. Valid - operators are In, NotIn, Exists and DoesNotExist. - type: string - values: - description: values is an array of string - values. If the operator is In or NotIn, - the values array must be non-empty. If - the operator is Exists or DoesNotExist, - the values array must be empty. This array - is replaced during a strategic merge patch. - items: - type: string - type: array - required: - - key - - operator - type: object - type: array - matchLabels: - additionalProperties: - type: string - description: matchLabels is a map of {key,value} - pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, - whose key field is "key", the operator is "In", - and the values array contains only "value". - The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - resource: - description: GroupResource specifies a Group and a - Resource, but does not force a version. This is - useful for identifying concepts during lookup stages - without having partially valid types - properties: - group: - type: string - resource: - type: string - required: - - group - - resource - type: object - timeout: - type: string - required: - - all - - for - - labels - - resource - - timeout - type: object - type: array - required: - - name - - namespace - - releaseName - - sourceRef - - version - type: object - type: object - type: array - kubeVersion: - description: KubeVersion is a SemVer constraint specifying the version - of Kubernetes required. - type: string - required: - - items - type: object - status: - properties: - observedGeneration: - description: ObservedGeneration is the most recent generation observed - for this resource. It corresponds to the resource's generation, - which is updated on mutation by the API Server. - format: int64 - type: integer - type: object - type: object - served: true - storage: true - subresources: - status: {}